Woocommerce – set Add Order Note checkbox checked by default

Using the Woocommemrce Checkout block, I would like to have the Add Order Note box checked by default. Using jQuery/JS does not seem to work inside the new(ish) block version of the Checkout page.

Code ex:

jQuery(function($){
      $('#checkbox-control-1').attr('checked', true);
   });

I am guessing the Checkout block requires a different approach; the textarea appears to be complete removed from the DOM until the box is checked, and the checkbox never has any ‘checked’ attribute added/removed when clicked.
enter image description here

is it possible to print a string on each iteration of a loop in php without using js or ajax?

my teacher told me to create a countdown timer with php that if you give it three inputs in html (hours,minutes,seconds) it will count down the numbers and show the remaining time in real time . like the timer in your phone . he told me to only use html, css and php . no js or ajax is allowed . with JAVA language i can do it but php is scripting language and shows the results after all the code is executed .

At first I thought the sleep() funtion is the answer but it’s script language .

streaming compressed bytes to s3

I was looking at different ways to compress and upload a file to s3, and I recently came across the CompressionStream api. Basically uploading a file in one go using this seems to be quite straightforward:

const compressedStream = file.stream().pipeThrough(new CompressionStream('gzip'));
response = await fetch(presignedUrl,{
  method: "PUT",
  body: body,
  headers: {
    "Content-Type": contentType,
    "Content-Encoding": "gzip"
  },
});

Since, I target large files (1-3 gb), I was going for a Multipart upload. But, the Compression stream being a stream api can pipe through data as far as I understand(hopefully correctly) .

So, I wanted to combine the advantages of both, and knowing s3 doesn’t support directly streamed uploads, I wanted to upload the chunked bytes on a multipart upload instead.
Yet, I’m not being able to figure out how to do this, it may look something like this:

// Here, I've tried to use TransformStream but , a better approach is really welcomed
// this is pseudocode only
// file = event.target.files[0] , user selected file:
  file
  .stream()
  .pipeThrough(new CompressionStream('gzip'))
  .pipeThrough(new TransformStream({
    start(){},
    transform(chunk, controller) {
           
      uploadPromises.push(
        s3Client
          .send(
            new UploadPartCommand({
              Bucket: bucketName,
              Key: key,
              UploadId: uploadId,
              Body: some_chunk_of_5mb_size, // THIS IS THE CONFUSION
              PartNumber: i + 1,
            }),
          )
     
    },

   }))
  1. What I do not understand is how to get a chunk of size >=5mb , since
    that’s s3’s requirement for a multipart upload.
  2. What is the data type of this chunk even? In the Transform stream docs, it’s being compared to all sort of data type, can I even check the size and concatenate this chunk to make it 5mb for the multipart upload?
  3. Does uploading like this if the chunk has to be for example further converted into buffer or something affect the integrity of the file being uploaded?

recursion with setTimeout flow anomaly

Please see the below code.
I thought the ‘11111111’ line would never be executed but it is.
Can anyone please explain.

function outer()
{
    function inner(dur)
    {
        console.log('in inner');
        
        setTimeout(() => {

            outer();
            console.log('11111111');
            
        }, dur);
                
    }
    console.log('in outer');
    inner(5000);
}

outer();

I expected an infinite loop. That happened.
But I never expected the ‘11111111’ to execute.

How Does JavaScript Handle Asynchronous Recursion in Call Stacks for Deeply Nested Promises?

I’m working on an application where I need to recursively process a deeply nested structure using asynchronous operations (Promised-based API calls), and I’m curious about how JavaScript’s event loop, call stack, and microtask queue manage this. Specifically, I want to understand how recursion interacts with the asynchronous flow of JavaScript.

Here’s a simplified example of the recursion pattern I’m using:

async function processNode(node) {
    if (node.children) {
        for (let child of node.children) {
            await processNode(child);
        }
    }
    return performAsyncTask(node); // Assume this returns a Promise
}

My questions are:

  1. How does JavaScript manage the call stack when processNode is deeply recursive? Does the stack get cleared between async calls due to the await, or can it still lead to stack overflow with deep recursion?

  2. When an await is encountered, I know the function execution is paused and the event loop takes over. At what point does the function get re-entered into the call stack? Does the stack grow with every await resolution in the recursive call?

  3. What strategies could be used to prevent potential stack overflow with deeply recursive async functions?

I’ve seen some discussions around tail call optimization in JavaScript, but I’m unsure how it applies in the case of async/await.

I’d appreciate some clarity on the internal mechanics of the call stack and event loop when recursion and async operations are combined!

cordova.platformId returning as “browser” on android

I am trying to add some platform specific code to resize my game if on mobile. My problem is cordova.platformId is returning as “browser” on my phone after running “cordova run android”.

I created a new Cordova App using the command line. I added the Android platform and got an APK running on my device with “cordova run android”. I made a text file in my game to print the output of cordova.platformId. It outputs “browser”.

Empty Results Field after Implementing Filter Search

I’ve created a cardsByLanguage promise in my api file for my projected, inserted a navbar item for for a filtered results search, and created a click event listener for this navbar item, but no cards display. In my promise, I first filtered for language and then by uid, so both options should be filtered.

I put the following function for my api js file:

`const cardsByLanguage = (language, uid) => new Promise((resolve, reject) => {
  fetch(`${endpoint}/vocab.json?orderBy="language"&equalTo="${language}"`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then((response) => response.json())
    .then((data) => {
      const filteredData = Object.values(data).filter((card) => card.uid === uid);
      resolve(filteredData);
    })
    .catch(reject);
});`

And I’ve put the following for a navbar click event listener:

 `document.querySelector('#allLanguages').addEventListener('click', () => {
    cardsByLanguage(`${firebase.auth().currentUser.uid}`).then(showCards);
  });`

AWS IoT permission policy for user authenticated with Cognito UserPool and Cognito IdentityPool

As stated in docs (https://docs.aws.amazon.com/iot/latest/developerguide/connect-and-pub.html)

For devices not registered as things in the AWS IoT Core registry, the
following policy grants permission to connect to AWS IoT Core with
client ID client1 and restricts the device to publishing on a
clientID-specific MQTT topic:

{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Effect": "Allow",
        "Action":["iot:Publish"],
        "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/${iot:ClientId}"]
      },
      {
        "Effect": "Allow",
        "Action": ["iot:Connect"],
        "Resource": ["arn:aws:iot:us-east-1:123456789012:client/client1"]
      }
    ]
}

Now I have a user authenticated with a Cognito user pool (by the hosted-ui). The user comes back to my webapp (frontend) and I use the id_token (returned by the hosted-ui redirect) with AWS.CognitoIdentityCredentials() class to get back a temporary key/secret/etc..

So that my AWS.config.credentials.identityId has valid value.

How should I update the policy to allow the logged user to connect/publish to a “abc” topic?

I tried replacing the ${iot:ClientId} and client1 (sample values) with:

  1. the user pool id,
  2. the webapp clientId,
  3. the user id (that would make sense to me)…

but without success ;( .

Extra White space in the page

extra white space is showing in the webpage in responsive design for mobile only after applying the script tag how to remove it

help me with the solution on how to remove it and get rid of these white spaces which are unnecessary coming on my page

Unable to update state in React while creating Like Button

I am new in learning React. I am encountering a small problem and have grinded my brain over the issue, but not been able to come up with the solution.
I am making Comment’s like/dislike component. I am unable to maintain the state on initial run. It gets undefined on initial run, but state gets updated after pressing like button for second time. Following is my JSX:

<div className="flex justify-between gap-5" onL>
   <h4 className="text-text font-medium text-base">
       {comment?.userID?.name}
   </h4>
   <Button
     className="flex-shrink-0 flex-grow-0"
     onClick={() => {
       setHasLiked((prevHasLiked) => {
           return {
             ...prevHasLiked,
             [comment?.userID?._id]:
             !prevHasLiked[comment?.userID?._id],
             };
           });

           onSubmmitLikeComment(
             comment?._id,
             comment?.userID?._id
            );
           }}
           >
           {hasLiked[comment?.userID._id] ? (
             <Empheart stroke="red" fill="red" />
                ) : (
                  <Empheart stroke="black" fill="black" />
                    )}

                    {comment?.like_count}
           </Button>
         </div>

Following is my onSubmmitLikeComment:

const onSubmmitLikeComment = async (commentID, userID) => {
    console.log("userID", userID); //getiing userID correctly
    const userHasLiked = hasLiked[userID]; //getting undefined in initial click render. But this state gets updated after clicking like button like button for second time
    console.log("userHasLiked", userHasLiked);
    console.log("hasLiked", hasLiked);
    try {
      const response = await fetch("/api/likeComment", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-App-Type": "WEB_APP",
        },
        body: JSON.stringify({ commentID, userID, hasLiked: userHasLiked }),
      });
      const result = await response.json();
      console.log("result", result);
      if (result.isSuccess) {
        setComments((prevComments) =>
          prevComments.map((comment) =>
            comment?._id == commentID && comment?.userID?._id === userID
              ? {
                  ...comment,
                  like_count: userHasLiked
                    ? comment.like_count - 1
                    : comment.like_count + 1,
                }
              : comment
          )
        );
        setHasLiked((prev) => ({
          ...prev,
          [userID]: !userHasLiked,
        }));
      }
    } catch (error) {
      console.error("Unable to update like/unlike comment ", error);
      alert(
        "An error occurred while liking/disliking comment. Please try again."
      );
    }
  };

These are two states being used:
const [comments, setComments] = useState([]);
const [hasLiked, setHasLiked] = useState({});

Your help will make my day. 🙂

SVG line chart using d3 is not rendering to full height along y-axis

I am rendering a svg line chart using d3. For y axis the maximum value in chart data is 104 and minimum is 0. I have taken height of chart to 500. But the maximum value i.e 104 should be rendered at top height but its rendering at height somewhere near height of 270.
Also how can I get y value of svg path from x position inside svg bounds?

I am using timestamps for x axis values in chart data

My Code:

import * as shape from "d3-shape";
import { scaleLinear } from "d3-scale";
const SIZE = 500
const data2 = [
    { "weight": 0, "date": 1723939200000 },
    { "weight": 0, "date": 1724284800000 },
    { "weight": 0, "date": 1724371200000 },
    { "weight": 60, "date": 1724493742250 },
    { "weight": 0, "date": 1724544000000 },
    { "weight": 104, "date": 1724653305251 },
    { "weight": 0, "date": 1724716800000 },
    { "weight": 0, "date": 1724803200000 },
    { "weight": 0, "date": 1725235200000 }]

const formattedValues = data2.map((rec) => [rec.weight, rec.date] as [number, number]);
const weights = formattedValues.map((value) => value[0]);
const dates = formattedValues.map((value) => value[1]);
const scaleX = scaleLinear().domain([Math.min(...dates), Math.max(...dates)]).range([0, SIZE]);
const minWeight = Math.min(...weights);
const maxWeight = Math.max(...weights);
const scaleY = scaleLinear().domain([maxWeight, minWeight]).range([0, SIZE])
const path = shape.line().x(([, x]) => scaleX(x) as number).y(([y]) => {
    return scaleY(y) as number
})
    .curve(shape.curveBasis)(formattedValues) as string
export function Home() {
    return (
        <div className="homeContainer">
            <svg 
                height={SIZE} width={SIZE} fill="yellow" style={{ border: '2px solid blue' }}>
                <path
                    d={path}
                    stroke="black"
                    strokeWidth={2}
                />
            </svg>

        </div>
    )
}

export default Home

blue border is svg width and height and this is how chart renders

converting WebService response to JSON

I want to convert indexed Object response to proper JSON. I’ve already tried using JSON.stringify but no success. Here is the response:

enter image description here

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
        var catsorted;

        $(document).ready(function () {
            getCategoriesSorted();

            var recordset = catsorted;
            //console.log(recordset);
            var rset = GenerateNestedJSON(recordset);
            var arr = rset;
            console.log(arr);
        });

        function GenerateNestedJSON(recordset) {
            var array = recordset;

                async function getNestedChildren(arr, parent) {
                    var children = [];
                    for (var i = 0; i < arr.length; ++i) {
                        if (arr[i].parentid == parent) {
                            var grandChildren = await getNestedChildren(arr, arr[i].id);
                            if (grandChildren.length) {
                                arr[i].children = grandChildren;
                            }
                            children.push(arr[i]);
                        }
                    }
                    return children;
                }
                nest = getNestedChildren(array, 0);
            return nest;
        }

        function getCategoriesSorted() {

            $.ajax({

                type: 'POST',
                url: '/CategorieService.asmx/GetCategoriesSorted',
                data: "{}",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                async: false,
                success: function (response) {

                    catsorted = response.d;

                },
                error: function (xhr) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                }
            });
        }
    </script>
</head>
<body>

</body>
</html>

getCategoriesSorted() calls a C# webservice. This webservice returns id, parentid and catname from a table. GenerateNestedJSON(recordset) nests children for each category.

Buffer is not defined

Here’s an improved version of your description:


I am using the @otplib/preset-browser package, which requires the buffer. I’ve polyfilled buffer using vite-plugin-node-polyfills. This works in development mode (vite dev), but I encounter an error buffer is not defined in the production build.

Here is my vite.config.js:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { nodePolyfills } from "vite-plugin-node-polyfills";
import inject from "@rollup/plugin-inject";

// https://vitejs.dev/config/
export default defineConfig(async () => ({
  plugins: [
    react(),
    nodePolyfills({
      include: ["buffer"],
    }),
  ],

  // Vite options for Tauri development, applied in `tauri dev` or `tauri build`
  clearScreen: false, // Prevents Vite from obscuring Rust errors
  server: {
    port: 1420, // Tauri expects a fixed port, fails if unavailable
    strictPort: true,
    watch: {
      ignored: ["**/src-tauri/**"], // Tells Vite to ignore the `src-tauri` directory
    },
  },
}));

I’ve tried every solution found in google with query buffer is not defined vite.