Font styling not captures with exporting html element to pngs

I am trying to export an html element (a div containing mostly an svg). There are no extra styles being applied (classes, etc) to the element.
The html element looks like this
enter image description here

But the saved png looks like enter image description here

Here are the different code snippets I have tried which all produce the same result

html2canvas:

const canvas = await html2canvas(el, { useCORS: true, copyStyles: true });
const image = canvas.toDataURL("image/png");
...

saveSvgAsPng

saveSvgAsPng.svgAsPngUri(
`filename.png`,{ scale: 1, encoderOptions: 1, excludeCss: true }).then(url => {
...
})

html-to-image

toPng(element).then((url) => {
...
}

Any advice or suggestions are greatly appreciated!

Flexmonster how to apply row/column freezing/pinning like excel

I would like to know whether is it possible to freeze/pin column

Is there option to do row pinning/freezing or column pinning/freezing and if so can freeze/pin particular column/row using flexmonster.
Please help needed

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flexmonster Column Pinning Example</title>
    <link rel="stylesheet" href="https://cdn.flexmonster.com/2.8.16/flexmonster.css">
    <style>
        #pivot-container {
            height: 600px;
        }
    </style>
    <script src="https://cdn.flexmonster.com/2.8.16/flexmonster.js"></script>
</head>
<body>
    <div id="pivot-container"></div>

    <script>
        const pivot = new Flexmonster({
            container: "#pivot-container",
            toolbar: true,
            height: "100%",
            report: {
                dataSource: {
                    data: [
                        { "Product": "Apple", "Region": "North", "Sales": 1500 },
                        { "Product": "Orange", "Region": "South", "Sales": 1200 },
                        { "Product": "Banana", "Region": "East", "Sales": 1300 },
                        { "Product": "Grapes", "Region": "West", "Sales": 1700 }
                    ]
                },
                slices: {
                    rows: [{
                        uniqueName: "Product"
                    }],
                    columns: [{
                        uniqueName: "Region"
                    }],
                    measures: [{
                        uniqueName: "Sales",
                        aggregation: "sum"
                    }]
                }
            },
          
        });
    </script>
</body>
</html>

How do JavaScript instances access private methods without prototype inheritance?

My understanding is that private methods are not part of the prototype chain, and therefore, are not inherited by subclasses. However, I am confused about how instances of a class access private methods when those methods are invoked through public methods of the class.

class MyClass {
  #privateMethod() {
    return 'I am a private method';
  }

  publicMethod() {
    return this.#privateMethod(); // Access private method from within the class
  }
}

const instance = new MyClass();
console.log(instance.publicMethod()); // Logs: I am a private method

When instance.publicMethod() is called, this inside publicMethod refers to instance. Since private methods are not part of the instance itself or the prototype chain, how does this.#privateMethod() work? How does the private method get accessed even though the instance doesn’t directly contain the private method?

Why does my Flask website keep refreshing?

I am trying to make a social media website, (similar to TikTok) but the watch page keeps refreshing.

My JS sends JSON like this to the backend, which keeps track of likes, dislikes, views, etc. in a SQLite database:

{
  "action": {action e.g. like, dislike, view}
  "id": {video_id e.g. 1)
}

Then, the backend processes it with this function:

@app.route('/trackStatistics', methods=['POST'])
def track_statistics():
    try:
        # Get the JSON data from the request
        data = request.get_json()

        # Validate the action and id
        if 'action' not in data or 'id' not in data:
            return jsonify({'error': 'Invalid request'}), 400

        action = data['action']
        video_id = data['id']

        data = get_video(video_id)

        print(data)

        if action == "like":
            data["likes"] = int(data["likes"]) + 1
        elif action == "dislike":
            data["dislikes"] = int(data["dislikes"]) + 1
        elif action == "unlike":
            data["likes"] = int(data["likes"]) - 1
        elif action == "undislike":
            data["dislikes"] = int(data["dislikes"]) - 1
        elif action == "view":
            data["views"] = int(data["views"]) + 1
        
        update_video(video_id, data["publisher"], data["title"], data["likes"], data["dislikes"], data["views"], data["comments"], False)

        print(data)

        # Return the updated data
        return jsonify(data), 200

    except Exception as e:
        print(str(e))
        return jsonify({'error': str(e)}), 500

Here’s the file with my update_video, get_video, and create_video functions defined:

import sqlite3
import json
from datetime import datetime

def get_video(video_id):
    conn = sqlite3.connect('../databases/videos.db')
    c = conn.cursor()
    c.execute("SELECT * FROM videos WHERE id = ?", (video_id,))
    video = c.fetchone()
    comments = json.loads(video[6]) if video[6] else []
    video = list(video)
    video[6] = comments
    conn.close()
    return {
        "id": video[0],
        "publisher": video[1],
        "title": video[2],
        "likes": video[3],
        "dislikes": video[4],
        "views": video[5],
        "comments": video[6],
        "created_at": video[7],
        "updated_at": video[8]
    }

def create_video(publisher, title, likes, dislikes, views, comments):
    conn = sqlite3.connect('../databases/videos.db')
    c = conn.cursor()
    now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    comments_json = json.dumps(comments)
    c.execute("INSERT INTO videos (publisher, title, likes, dislikes, views, comments, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", 
              (publisher, title, likes, dislikes, views, comments_json, now, now))
    conn.commit()
    conn.close()
    return c.lastrowid

def update_video(video_id, publisher, title, likes, dislikes, views, comments, update_time):
    conn = sqlite3.connect('../databases/videos.db')
    c = conn.cursor()

    # Get the current updated_at time
    c.execute("SELECT updated_at FROM videos WHERE id = ?", (video_id,))
    last_updated = c.fetchone()[0]

    if update_time:
        now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    else:
        now = last_updated

    comments_json = json.dumps(comments)
    c.execute("UPDATE videos SET publisher = ?, title = ?, likes = ?, dislikes = ?, views = ?, comments = ?, updated_at = ? WHERE id = ?",
              (publisher, title, likes, dislikes, views, comments_json, now, video_id))
    conn.commit()
    conn.close()

I tried to keep track of the video stats and the server seems to work, it prints the correct data! But, after giving code 200 success, it refreshes the page.

Here’s the JS I’m using to interact with the backend:

let liked = false;
let disliked = false;
let followed = false;
let commentsOpen = false;
const url = window.location.search;
const urlParams = new URLSearchParams(url);
const id = urlParams.get('c');
const trackStatisticsRoute = 'http://localhost:5005/trackStatistics';

$(document).ready(() => {
  if (id) {
    document.title = "ByteClips - " + id;
  }

  const vidFile = `../videos/${id}/video.mp4`;

  console.log(vidFile);
  $('#vidSrc').attr('src', vidFile);
  $('.video')[0].load();

    updateRating('view', id);

  $('.video-buttons div button').hover(
    () => {
      $(this).find('i').css('opacity', 0);
      $(this).find('.counter').css('opacity', 1);
    },
    () => {
      $(this).find('i').css('opacity', 1);
      $(this).find('.counter').css('opacity', 0);
    }
  );
});

function updateRating(action, id) {
  const requestData = {
    action,
    id
  };

  $.ajax({
    type: 'POST',
    url: trackStatisticsRoute,
    data: JSON.stringify(requestData),
    contentType: 'application/json',
    success: data => {
      updateUI(data);
    },
    error: (jqXHR, textStatus, errorThrown) => {
      console.log('AJAX request error:', textStatus, errorThrown);
      console.log('Response:', jqXHR.responseText);
    }
  });
}

function updateUI(data) {
  const newData = typeof data === 'string' ? JSON.parse(data) : data;
  $('#like .counter').text(newData.likes);
  $('#dislike .counter').text(newData.dislikes);
  $('#share .counter').text(newData.views);
  $('#comment .counter').text(newData.comments.length);
}

$('#like').css('background', liked ? '#fff' : '#26daa5');
$('#like').css('color', liked ? '#26daa5' : '#fff');
$('#dislike').css('background', disliked ? '#fff' : '#26daa5');
$('#dislike').css('color', disliked ? '#26daa5' : '#fff');
$('#follow').css('background', followed ? '#fff' : '#26daa5');
$('#follow').css('color', followed ? '#26daa5' : '#fff');
$('#follow i').attr('class', followed ? 'fa-solid fa-user-minus' : 'fa-solid fa-user-plus');

$('#like').on('click', () => {
  if (liked) {
    liked = false;
    updateRating('unlike', id);
  } else {
    if (disliked) {
      updateRating('undislike', id);
    }
    liked = true;
    disliked = false;
    updateRating('like', id);
  }
  updateLikeDislike();
});

$('#dislike').on('click', () => {
  if (disliked) {
    disliked = false;
    updateRating('undislike', id);
  } else {
    if (liked) {
      updateRating('unlike', id);
    }
    disliked = true;
    liked = false;
    updateRating('dislike', id);
  }
  updateLikeDislike();
});

$('#follow').on('click', () => {
  followed = !followed;
  $('#follow i').attr('class', followed ? 'fa-solid fa-user-minus' : 'fa-solid fa-user-plus');
  $('#follow').css('background', followed ? '#fff' : '#26daa5');
  $('#follow').css('color', followed ? '#26daa5' : '#fff');
});

$('#comment').on('click', () => {
  console.log('comments opened');
  commentsOpen = !commentsOpen;
  $('#comment').css('background', commentsOpen ? '#fff' : '#26daa5');
  $('#comment').css('color', commentsOpen ? '#26daa5' : '#fff');
});

function updateLikeDislike() {
  $('#like').css('background', liked ? '#fff' : '#26daa5');
  $('#like').css('color', liked ? '#26daa5' : '#fff');
  $('#dislike').css('background', disliked ? '#fff' : '#26daa5');
  $('#dislike').css('color', disliked ? '#26daa5' : '#fff');
}

How to free webgpu gpu mem in onnxruntime web

I use onnxruntime web with following code

/**
 *
 * @param model don't pass session but pass model path and create session in infer inner. In this way, after infer finish, it will auto free gpu mem to prevent mem overflow
 * @param inputTensor
 */
export async function infer2(model: string, inputTensor: Tensor) {
  const session = await newSession(model)
  const feeds: any = {};
  const inputNames = session.inputNames;
  feeds[inputNames[0]] = inputTensor;
  const results = await session.run(feeds);
  const tensor = results[session.outputNames[0]]
  // await session.release() // free gpu mem
  await session.release() // free gpu mem
  return tensor;
}

/**
 * Load the ONNX model and perform inference
 * @param model don't pass session but pass model path and create session in infer inner. In this way, after infer finish, it will auto free gpu mem to prevent mem overflow
 * @param {onnxruntime.Tensor} inputTensor - Input tensor
 * @param {number[]} inputShape - Input tensor shape
 * @returns {Promise<Float32Array>} - Output tensor data
 */
export const infer = async (model: string, input: Ndarray) => {
  let inputTensor = ndarrayToTensor(input)
  const outTensor = await infer2(model, inputTensor);
  let na = new Ndarray(Array.from(outTensor.data as Float32Array) as number[], outTensor.dims as number[])
  inputTensor.dispose()
  outTensor.dispose()
  return na
  // const {data: out, dims: outShape} = results[session.outputNames[0]]
  // return {out: out as Float32Array, outShape: outShape as number[]}
};

and following is my test code

  let input = await imgToNdarray(t);
  let out = await infer(model, input)
  let imgDataUrl = outToImgDataUrl(out)
  testReact(<img src={imgDataUrl}/>)

but fater infer, nvidia-smi show the gpu mem is still in use

Javascript slider add counter slide number

I have a slider built in Javascript, CSS and HTML with no dependencies. The slider works fine.

How could I display the counter slide number in Javascript inside the div element .gallery-counter?

For example if there is a total of 8 slides, the first slide would display: 1/8.

The HTML:

<section id="gallery">
    <div class="gallery-container">
        <figure class="gallery-item">
            <img src="img-1.jpg" />
        </figure>
        <figure class="gallery-item">
            <img src="img-2.jpg" />
        </figure>
        <figure class="gallery-item">
            <img src="img-3.jpg" />
        </figure>
    </div>
    <div class="gallery-counter"></div>
    <nav class="gallery-navigation">
        <button class="nav-button prev-button"><span>&#60;</span></button>
        <button class="nav-button next-button"><span>&#62;</span></button>
    </nav>
</section>

The JS:

let currentIndex = 0;

document.querySelector('.prev-button').addEventListener('click', () => {
    navigate(-1);
});

document.querySelector('.next-button').addEventListener('click', () => {
    navigate(1);
});

// Navigation
function navigate(direction) {
    const galleryContainer = document.querySelector('.gallery-container');
    const totalImages = document.querySelectorAll('.gallery-item').length;
    
    currentIndex = (currentIndex + direction + totalImages) % totalImages;
    const offset = -currentIndex * 100;
    
    galleryContainer.style.transform = `translateX(${offset}%)`;
}

// Autoplay
let autoplayInterval = null;

function startAutoplay(interval) {
    stopAutoplay();
    autoplayInterval = setInterval(() => {
        navigate(1);
    }, interval);
}

function stopAutoplay() {
    clearInterval(autoplayInterval);
}

startAutoplay(3000);

// Stop autoplay when user interacts
document.querySelectorAll('.nav-button').forEach(button => {
    button.addEventListener('click', stopAutoplay);
});

Thank you.

Using UTC for a calendar built from scratch

Let’s say I have to build a calendar from scratch in Angular or any other frontend framework. Considering the following points:

  • I can only use the native Date class.

  • It must allow users to select a date, which can be saved into their browser and loaded afterwards. The user can switch timezones, but the shown date must stay the same.

  • The selected value will be sent to a web service in a timezone agnostic format, such as DD-MM-YYYY.

Taking these points into account, I’ve decided the best option for the calendar would be to build the cells using UTC, and to expect / emit values in UTC as well. However, I’ve encountered an issue when integrating the calendar with other date components (such as datepickers), because they always reflect the date in the local timezone.

This made me think: is this really the best approach? Is there a more flexible solution?

equivalent of javascript code in swift or Objective-C

I want to convert the function in Swift or Objective-C so I can use in Native module of React Native.

export const provisionWithCertificate = async (
    scopeId,
    registrationId,
    keyPath,
    certificatePath,
  ) => {
    const data = {
      registrationId: registrationId,
    };
    const cert = await RNFS.readFile(certificatePath, 'utf8');
    const key = await RNFS.readFile(keyPath, 'utf8');

    try {
      const httpsAgent = new https.Agent({
        cert: cert,
        key: key,
      });
      console.log('httpsAgent', httpsAgent);
      const response = await axios({
        method: 'PUT',
        url: `https://global.azure-devices-provisioning.net/${scopeId}/registrations/${registrationId}/register?api-version=2021-06-01`,
        data: data,
        httpsAgent: httpsAgent,
        headers: {
          'Content-Type': 'application/json',
          'Content-Encoding': 'utf-8',
        },
      });
      return response.data;
    } catch (err) {
      console.log('err', err);
      return err;
    }
  };
  

I tried this using some AI to convert but I am not able find the satisfactory solution.

Animations in Framer Motion

I was trying to implement Framer Motion, to understand how it works, in a personal project of mine.

For now, I wrote the following code (100% working), in these two components:

  • Modal.jsx

    import { createPortal } from "react-dom";
    import { motion } from "framer-motion";
    
    export default function Modal({ title, children, onClose }) {
      return createPortal(
        <>
          <div className="backdrop" onClick={onClose} />
          <motion.dialog
            variants={{
              open: { opacity: 1, translateY: 0 },
              closed: { opacity: 0, translateY: 30 },
            }}
            initial="closed"
            animate="open"
            exit="closed"
            open
            className="modal"
          >
            <h2>{title}</h2>
            {children}
          </motion.dialog>
        </>,
        document.getElementById("modal")
      );
    }
    
  • NewChallenge.jsx

    import { useContext, useRef, useState } from "react";
    import { motion } from "framer-motion";
    
    import { ChallengesContext } from "../store/challenges-context.jsx";
    import Modal from "./Modal.jsx";
    import images from "../assets/images.js";
    
    export default function NewChallenge({ onDone }) {
      const title = useRef();
      const description = useRef();
      const deadline = useRef();
    
      const [selectedImage, setSelectedImage] = useState(null);
      const { addChallenge } = useContext(ChallengesContext);
    
      function handleSelectImage(image) {
        setSelectedImage(image);
      }
    
      function handleSubmit(event) {
        event.preventDefault();
        const challenge = {
          title: title.current.value,
          description: description.current.value,
          deadline: deadline.current.value,
          image: selectedImage,
        };
    
        if (
          !challenge.title.trim() ||
          !challenge.description.trim() ||
          !challenge.deadline.trim() ||
          !challenge.image
        ) {
          return;
        }
    
        onDone();
        addChallenge(challenge);
      }
    
      return (
        <Modal title="New Challenge" onClose={onDone}>
          <form id="new-challenge" onSubmit={handleSubmit}>
            <p>
              <label htmlFor="title">Title</label>
              <input ref={title} type="text" name="title" id="title" />
            </p>
    
            <p>
              <label htmlFor="description">Description</label>
              <textarea ref={description} name="description" id="description" />
            </p>
    
            <p>
              <label htmlFor="deadline">Deadline</label>
              <input ref={deadline} type="date" name="deadline" id="deadline" />
            </p>
    
            <motion.ul
              id="new-challenge-images"
              variants={{
                open: { transition: { staggerChildren: 0.05 } },
              }}
              initial="closed"
              animate="open"
            >
              {images.map((image) => (
                <motion.li
                  key={image.alt}
                  onClick={() => handleSelectImage(image)}
                  className={selectedImage === image ? "selected" : undefined}
                  variants={{
                    closed: { opacity: 0, scale: 0 },
                    open: { opacity: 1, scale: 1 },
                  }}
                >
                  <img {...image} />
                </motion.li>
              ))}
            </motion.ul>
    
            <p className="new-challenge-actions">
              <button type="button" onClick={onDone}>
                Cancel
              </button>
              <button>Add Challenge</button>
            </p>
          </form>
        </Modal>
      );
    }
    

All animations, after various tests, work correctly, in particular:

  • The animation in Modal.jsx, animates the <dialog> with a fade-in-from-bottom style animation

  • The animations in New Challenge.jsx animates the list <ul> by setting an animation delay on the elements of the list with staggerChildren and the list items <li> with a bounce style animation.

As mentioned above, everything works and the animations are triggered correctly.

What I wanted to understand is, where does the list <ul> get the initial state “closed” from? From the Modal?

Is there a better way to do what I’m trying to do?

I am not an expert in using this library, but I find it very useful and would like to learn how to use it in the best possible way.

Could anyone help me understand?

http fetch reset not recognized in javascript

The following JavaScript code sends a file to an embedded LWIP HTTP server in chunks.

As can be seen in the Wireshark trace, a reset sometimes occurs during transmission. In this case, the request is aborted, however the script does not receive any information from this and returns true even in case of an error.

Does anyone have a tip on how to teach the script to recognize such an error?

The function should only return true if the request was successful, otherwise the call will repeated again with the same chunk.

reset while http post

async function uploadChunk(chunk) {
  let result = false;
  const formData = new FormData();
  formData.append("file", chunk);
  sleep(10);
  
  try {
    const response = await fetch("http://" + target_ip + "/update", {
      method: "POST",
      mode: "no-cors",
      body: formData
    });
    res = await response;
    const ok_string = "OK";
    result = (response.ok & (response.statusText === ok_string));
    console.log(res);
  } catch (error) {
    console.error("Failed to upload chunk: ", error);
  }
  
  return result;
}

Get live chat open up using external button

This is my script for the live chat which is embedded in header.php in wordpress environment.

<script src="https://widgets.leadconnectorhq.com/loader.js" 
 data-resources-url="https://widgets.leadconnectorhq.com/chat-widget/loader.js" 
 data-widget-id="668ecb1edad1ad570c3c3c41"></script>

I want to use another div like structure more of a button to have it open and toggle it

I’ve tried adding js to trigger button but failed due to same-origin policy of google

How to implement global exception handling in grpc-js server interceptor?

I’m trying to implement global error handling using a gRPC server interceptor in grpc-js.

Below is my implementation:

function errorHandlingServerInterceptor(methodDescriptor, call) {
    const listener = (new grpc.ServerListenerBuilder())
        .withOnReceiveMetadata((metadata, next) => {
            try {
                next(metadata);
            } catch (error) {
                handleAndLogError(call, error);
            }
        })
        .withOnReceiveMessage((message, next) => {
            try {
                next(message);
            } catch (error) {
                handleAndLogError(call, error);
            }
        })
        .withOnReceiveHalfClose((next) => {
            try {
                next();
            } catch (error) {
                handleAndLogError(call, error);
            }
        })
        .withOnCancel(() => {
            logger.error(`Request was cancelled by the client.`);
        })
        .build();

    const responder = (new grpc.ResponderBuilder())
        .withStart(next => {
            next(listener);
        })
        .withSendMetadata((metadata, next) => {
            next(metadata);
        })
        .withSendMessage((message, next) => {
            next(message);
        })
        .withSendStatus((status, next) => {
            if (status.code !== grpc.status.OK) {
                logger.error(`Error status code: ${status.code}, details: ${status.details}`);
            }
            next(status);
        })
        .build();

    return new grpc.ServerInterceptingCall(call, responder);
}

I expected that errors thrown within the service methods would be caught by the try-catch blocks in the interceptor. However, this doesn’t seem to be happening. Can anyone explain why the errors thrown in service methods aren’t being caught and provide a solution to properly catch and handle these errors for global error handling?

html2canvas doesn’t capture text in textarea in SVG

I am working on an Angular node-based application, the nodes in which are html tables containing <textarea>. When I try to generate project previews using html2canvas, neither the text in <textarea> nor <mat-icons> are rendered, maybe it’s the same problem.
Here is the expectation/result:

And also the html structure of the component:

Why does CASL allow unrestricted read access in my conditionally defined rule?

I have defined a CASL rule for a User subject, with a condition to allow read access only to users belonging to a specific Org. Here is my implementation:

function defineAbilityFor(user) {
   const { can } = new AbilityBuilder();
   can("read", "User", { orgId: user.orgId });
   return build();
}

The rule works as expected when I check permissions for a specific user object:

defineAbilityFor({ orgId: "123" }).can("read", subject("User", { orgId: "123" })); // true

However, this also returns true:

defineAbilityFor({ orgId: "123" }).can("read", "User"); // true

I don’t understand why the second example returns true since I expected it to only allow read access when the orgId matches. Could someone explain why this is happening? A reference to the relevant documentation would be helpful.

Additionally, how can I modify my defineAbilityFor function to ensure that only the first example returns true and the second returns false?