In a firebase web app using cloud functions I’d like to confirm an email exists before changing it. This is achieved through verifyBeforeUpdateEmail(), but I would like to use my own email to send the link. For example, generatePasswordResetLink requires the user account to be existing before sending the email, so it wouldn’t work without further revisions.
Category: javascript
Category Added in a WPeMatico Campaign
How to split a hex string into individual bytes?
I am trying to split a hexadecimal string, 3E8.8F5C28F5C28, into individual bytes. I tried the following code to split the string:
const string = "3E8.8F5C28F5C28";
const res = string.split(/([dw]{2})/).filter(e => e);
But it gave me this result:
[
'3E', '8.', '8F',
'5C', '28', 'F5',
'C2', '8'
]
I need to split the given hex string like 03 E8 8F. I don’t want the fractional values after 8F.
How to achieve this?
Split a hex string into individual bytes using JavaScript
I am trying to split a hexadecimal string, 3E8.8F5C28F5C28, into individual bytes. I tried the following code to split the string:
const string = "3E8.8F5C28F5C28";
const res = string.split(/([dw]{2})/).filter(e => e);
But it gave me this result:
[
'3E', '8.', '8F',
'5C', '28', 'F5',
'C2', '8'
]
I need to split the given hex string like 03 E8 8F. I don’t want the fractional values after 8F.
How to achieve this?
split the hex string into individual bytes using JavaScript
I am trying to split the given hexadecimal string 3E8.8F5C28F5C28 into individual bytes. I tried the following code to split the given hexadecimal string const string = "3E8.8F5C28F5C28"; const res = string.split(/([dw]{2})/).filter(e => e); but it gave me a result like [ '3E', '8.', '8F', '5C', '28', 'F5', 'C2', '8' ] but I need to split the given hex string like 03 E8 8F.I don’t want the fractional values after 8F.how to achieve this help me.
iframe not decreeing by puppeteer
import puppeteer from "puppeteer";
let url="https://www.google.com/maps/place/Skittle+Lane/data=!4m7!3m6!1s0x6b12ae3f49692bed:0x4f8c7cbe2bac3f02!8m2!3d-33.8686!4d151.2048!16s%2Fg%2F11c3sx27qv!19sChIJ7StpST-uEmsRAj-sK758jE8?authuser=0&hl=en&rclk=1";
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
//Visiting google map url
await page.goto(url, {waitUntil: "load"});
let elementHandle = await page.$('iframe[align="middle"]');
console.log(elementHandle);
await browser.close();
})();
puppeteer not detecting iframe but with raw JS in browser console iframe got detected
Advice needed to load images on looping page
I have a gallery page using the Image Photo Gallery Final Tiles Grid WordPress plugin.
I want the page/scroll to continuously repeat (so as a user scroll down the page the gallery is repeated.
The following script seems to do the repeating nicely but the images aren’t loading and I can’t seem to figure it out, any ideas?
<script>
jQuery(document).ready(function($) {
const $gallery = $(".final-tiles-gallery");
const originalContent = $gallery.html(); // Save the original gallery content
// Function to append the content again
function appendContent() {
$gallery.append(originalContent); // Duplicate the gallery content
// Re-initialize the gallery plugin after appending new content
setTimeout(function() {
// Trigger the gallery plugin to reprocess the newly added images
if (typeof jQuery.fn.ftgInit === 'function') {
$gallery.ftgInit(); // This is specific to the Final Tiles Gallery plugin
}
// Ensure the gallery layout is recalculated after new images are appended
const instance = $gallery.data('ftg-instance'); // Get the gallery instance
if (instance) {
instance.setCurrentColumnSize(); // Recalculate column size for layout
instance.setCurrentImageSizeFactor(); // Adjust image size factor for new content
instance.setCurrentGridSize(); // Adjust grid size for the new layout
instance.refresh(); // Recalculate and refresh layout
}
}, 100); // Adjust the timeout delay as needed
}
// Trigger infinite scroll
jQuery(window).on("scroll", function() {
const scrollPosition = jQuery(window).scrollTop() + jQuery(window).height(); // Current scroll position
const documentHeight = jQuery(document).height(); // Total document height
// If the user scrolls near the bottom, append more content
if (scrollPosition >= documentHeight - 100) {
appendContent();
}
});
});
Here’s the page if it helps…
Many thanks (in advance)!
How to get an element with attribute name and again set a new attribute to the same element?
How to get an element with attribute name and again set a new attribute to the same element, suppose I have an <a href="#" myOwnAttributeName="hello"></a>.
Now I know how to select this element using document.querySelectorAll('a[myOwnAttribute="#hello"]') I need to know how will I set an attribute to the selected element. My final tag should look like <a href="#" myOwnAttributeName="hello" class="class-hello"></a> here I need to add a class name.
Using the setAttribute doesn’t work.
document.querySelectorAll('a[myOwnAttribute="#hello"]')
<html>
<a href="#" myOwnAttribute="hello">Click me</a>
</html>
How to prevent a Countdown timer to be jumpy/ pushing the number next to it using (HTML, CSS, JS only)
I am working on a project where countdown is the main focus. But when the count down starts as the numbers count down certain numbers push and pull other numbers like when eg. 22:00 changes it pulls the number on the right towards left eg. 21:59. This makes the countdown look jumpy and weird.
I want to avoid this behaviour. What I am thinking is that each number occupy a certain space and stay at its place fixed while the countdown. I don’t want to use a monospace font for visual reasons.
...
<div id="timer-container">
...
<div id="time-left">25:00</div>
</div>
...
timer-container {
position: relative;
margin-top: 0.5rem;
display: flex;
justify-content: center;
align-items: center;
background-color: transparent;
cursor: pointer;
border: 2px solid transparent;
border-radius: 50px;
transition: border-color 0.2s ease-in-out;
overflow: hidden;
max-height: 180px;
padding: 0px 20px;
}
#timer-container:hover {
border-color: black;
}
#time-left {
font-family: "Karla", sans-serif;
font-size: 10.375rem;
font-weight: 800;
text-align: center;
margin-bottom: 1rem;
letter-spacing: -5px;
user-select: none;
position: relative;
z-index: 1;
opacity: 1;
}
let timeLeft = 25 * 60; // seconds
const timeLeftEl = document.getElementById('time-left');
// ...
// Function to update the time left text content
function updateTimeLeftTextContent() {
const minutes = Math.floor(timeLeft / 60);
const seconds = timeLeft % 60;
timeLeftEl.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
I am quite new to pure HTML, CSS, Javascript. So a breif explaination on this is possible is much appriciated.
I have tried to separate the timer into individual span tags ’00’, ‘:’, ’00’ then tried to make block of fixed size but it just made it more werid. I also tired ch for the timer-container and the time-left but it didnt work.
I want the timer to stay in one place like monospace characters but the text is not monospace font, that what I want to solve
Composition vs Inheritance in Modern JS
Composition tends to bloat code and can become unreadable within large projects, however DRY is a must. Most tutorials and articles covert classes to functions and compose functionalities. One other added those functionalities to a Class prototype which is also awesome, why not directly assign it as a method to that class then?
The aim is to keep classes and at the same time benefit from composition with the help of modules.
Approach 1? Why?
const prepare = () => {
return {
prepare: () => console.log("Preparing..."),
};
};
const ready = () => {
return {
ready: () => console.log("Ready!"),
};
};
const createPizza = () => {
const pizza = {
....
}
return {
...pizza,
...prepare(),
...ready()
}
}
const pipi = createPizza();
pipi.prepare();
Approach 2? Why not?
const prepare = () => console.log("Preparing...");
const ready = () => console.log("Ready!");
class Pizza {
}
Pizza.prototype.prepare = prepare;
Pizza.prototype.ready = ready;
Approach 3? why not?
const prepare = () => console.log("Preparing...");
const ready = () => console.log("Ready!");
class Pizza {
prepare() {
prepare();
}
ready() {
ready();
}
}
Why wouldn’t I follow approach 3, does it violate other design patterns? how?
Isn’t both approaches of 2 and 3 more memory efficient here?
All approaches give the same results and perhaps approaches 2 and 3 are more memory efficient.
JS: Recursive function not making it past the first recursive call
In a node app, I’m trying to recursively query a database and then process the rows until the returned COUNT query would have 0 results. I’ve set up a recursive function that calls the query, then identifies the count from the results. The condition is met only twice, no matter the result of COUNT the third time. I am guessing this has to do with scope of the variables included but I can’t figure it out.
Using sf/sforce and db/dbase as connected classes that wrap jsforce and mysql2.
Recursive function
let queryMore = (dbase, sforce, callback) => {
let db = dbase;
let sf = sforce;
let cb = callback;
db.connection.promise().query('SELECT COUNT(*) FROM STATUS WHERE STATUS = '' + constants.statusOption.NOT_SENT + '' AND Type = ''+constants.typeOption.EMPLOYER+'';')
.then((results) => {
let count = results[0][0]['COUNT(*)'];
console.log(count);
if(count !== 0){
sendToSalesforceAndUpdateRows(db, sf).then(() => {
queryMore(db,sf,cb);
})
.catch(error => {
throw error;
})
}else{
cb();
}
})
.catch(error => {
throw error;
});
}
Query more calls sendToSalesforceAndUpdateRows and associated functions
let sendToSalesforceAndUpdateRows = (db, sf) => {
return new Promise((resolve, reject) => {
sendToSalesforce(db,sf)
.then(({successfulStream,failedStream}) => {
try{
console.log('sent. Updating rows');
let promises = [updateRecordsInDbase(successfulStream, db), updateRecordsInDbase(failedStream, db)];
Promise.all(promises)
.then(() => {
console.log('Updated Records');
resolve();
})
.catch(err => {
reject(err);
})
}catch(updateErr) {
reject(updateErr);
}
})
.catch(error => {
reject(error);
})
})
}
let sendToSalesforce = (db, sf) => {
return new Promise(async (resolve, reject) => {
let job = sf.createBulk2JobForStatus();
try{
job.on('inProgress', (jobinfo) => {
console.log('Job Info: ' + JSON.stringify(jobinfo));
})
job.on('error', (error) => {
console.log('Job Error');
throw error;
})
console.log('opening job');
await job.open();
console.log('job opened');
job.uploadData(db.queryRowsToPushAsStream(constants.typeOption.EMPLOYER)
.stream()
.pipe(prepRows)
.pipe(csv.stringify({
header : true,
columns : ['Claim_Number__c', 'File_Date__c','JSON__c','MySQL_Id__c','Type__c']
})))
.then(async () => {
await job.close();
await job.poll(3000, 600000);
let successfulStream = await sf.getSuccessfulResultsAsStream(job);
let failedStream = await sf.getFailedResultsAsStream(job);
resolve({successfulStream, failedStream});
});
}catch(e){
await job.close();
reject(e);
}
})
}
let updateRecordsInDbase = (recordStream, db) => {
return new Promise((resolve, reject) => {
try{
db.updateStatusRowsFromTStream(recordStream
.pipe(chunkResults), () => {
resolve();
});
}catch (error){
reject(error);
}
})
}
The query is limited to returning 10,000 records at a time due to heap size limitations when asking for results from the salesforce bulk api, but I will routinely have >30k rows to send, so I want to string these together and maintain the ability to write back to the database along the way.
What is supposed to happen for 30k records:
queryMore =>
count = 30000 =>
sendResultsToSalesforceAndUpdateRows =>
queryMore =>
count = 20000 =>
sendResultsToSalesforceAndUpdateRows =>
queryMore =>
count = 10000 =>
sendResultsToSalesforceAndUpdateRows =>
queryMore =>
count = 0 =>
callback
What I am seeing instead:
queryMore =>
count = 30000 =>
sendResultsToSalesforceAndUpdateRows =>
queryMore =>
count = 20000 =>
sendResultsToSalesforceAndUpdateRows =>
callback
Converting HTML with img tags with base64_encoded data in Lexical
I have HTML that I need converting to Lexical JS. The html contains img tags with base64 encoded values.
But when I run through this code the data for the img tag is none existent.
useEffect(() => {
const parser = new DOMParser();
const dom = parser.parseFromString(content, 'text/html');
const structure = analyzeNode(dom.body);
setNodeStructure(structure);
const editor = createEditor({
namespace: 'HeadlessEditor',
onError: (error) => console.error(error),
nodes: [
HeadingNode,
QuoteNode,
ListNode,
ListItemNode,
TableNode,
TableCellNode,
TableRowNode,
LinkNode
]
});
// Convert HTML to Lexical nodes
editor.update(() => {
const root = $getRoot();
root.clear();
const nodes = $generateNodesFromDOM(editor, dom);
console.log('Generated nodes:', nodes);
nodes.forEach(node => {
console.log('Appending node:', node);
root.append(node);
});
}, {
onUpdate: () => {
// Get editor state after update is complete
const editorState = editor.getEditorState();
console.log('Editor State:', editorState);
const jsonContent = editorState.toJSON();
console.log('Editor JSON Content:', jsonContent);
setEditorContent(JSON.stringify(jsonContent, null, 2));
}
});
}, [content]);
The HTML DOM contains something like this:
{
"type": "element",
"tag": "p",
"children": [
{
"type": "element",
"tag": "img",
"attributes": {
"src": "data:image/png;base64,iV...
After conversion, it it just this:
{
"children": [],
"direction": null,
"format": "",
"indent": 0,
"type": "paragraph",
"version": 1,
"textFormat": 0,
"textStyle": ""
}
How do I make it so that Lexical JS has my image tags?
Note that when I use the Editor I can see the image – it is base64_encoded and displaying it.
Thank you!
Why do I have an error for the @emotion/react package even though the package versions match?
I am using React JS and Next JS to create a website. Currently, I have this in my terminal when I try to do npm install.
npm error While resolving: [email protected]
npm error Found: [email protected]
npm error node_modules/react
npm error react@"^19.0.0-rc-69d4b800-20241021" from the root project
npm error
npm error Could not resolve dependency:
npm error peer react@">=16.8.0" from @emotion/[email protected]
npm error node_modules/@emotion/react
npm error @emotion/react@"^11.13.5" from the root project
As you can see, there is an error with the @emotion/react package I downloaded due to using MUI. However, it says that it requires react >= 16.8.0, and I have version 19 which is greater than 16. Am I understanding the error message wrong? How can I fix this error?
SyntaxError: The requested module ‘./routes/authRoutes.js’ does not provide an export named ‘default’
I am trying to implement endpoints for my book catalog using Node js and I could encounter thee below error when setting up the base urls.
index.js
import express from 'express';
import mongoose from 'mongoose';
import connectDB from './config/db.js';
import bookRoutes from './routes/bookRoutes.js';
import authRoutes from './routes/authRoutes.js';
const PORT = 3000;
const app = express();
app.use(express.json());
connectDB();
app.use('/auth', authRoutes);
app.listen(PORT, (req, res) => {
console.log(`Server is up and running in port ${PORT}`);
})
authRoutes.js
import express from 'express';
import User from '../models/User.js';
const router = express.Router();
//Registration
router.post('/register', async (req, res) => {
const {username, password} = req.body;
try{
const user = new User({username, password});
await user.save();
}catch(err){
alert(err);
res.send(401).send('Error occurred while registering the new user');
}
res.status(200).send('User registered.')
});
//Login
router.post('/login', async (req, res) => {
const{username, password} = req.body;
const user = await User.findOne({username});
if(!user || user.password !== password){
return res.status(401).send('Invalid username or password');
}
res.status(200).send('login successful');
});
module.exports = router;
Can someone please point to what I am missing?
Thank you in advance!
Custom Pie Animation in Highcharts: Multiple Animations and Inner Radius Not Working with Data Labels Disabled
I’m using a custom animation for a Highcharts pie chart with two points. One of the points can sometimes be 0, and the other is always 100. However, I’m encountering two issues:
-
Multiple Animations: When one point is 0 and the other is 100, the animation runs multiple times for the point with value 100.
-
Inner Radius Animation: The inner radius of the pie chart does not animate as expected.
I found this reference: Highcharts Custom Entrance Animation, and adapted the code for my chart. I’ve also set dataLabels to false for the chart. I will always have two points only in the pie chart, if the values are not 100 and 0 in the data the animation is working fine.
I can replicate same issue of animation running multiple in the reference fiddle as well if i set two data objects and set one to 100 and another to 0.
Has anyone encountered similar behavior with pie chart animations? How can I fix the issue with multiple animations and ensure that the inner radius animates correctly?
Here is the code I’m using:
(function (H) {
H.seriesTypes.pie.prototype.animate = function (init) {
const series = this,
chart = series.chart,
points = series.points,
{ animation } = series.options,
{ startAngleRad } = series;
function fanAnimate(point, startAngleRad) {
const graphic = point.graphic,
args = point.shapeArgs;
if (graphic && args) {
graphic
// Set initial animation values
.attr({
start: startAngleRad,
end: startAngleRad,
opacity: 1
})
// Animate to the final position
.animate({
start: args.start,
end: args.end
}, {
duration: animation.duration / points.length
}, function () {
// On complete, start animating the next point
if (points[point.index + 1]) {
fanAnimate(points[point.index + 1], args.end);
}
// On the last point, fade in the data labels
if (point.index === series.points.length - 1) {
series.dataLabelsGroup.animate({
opacity: 1
}, {
duration: 200 // Set duration for data label fade-in
});
}
});
}
}
if (init) {
// Hide points on init
points.forEach(point => {
point.graphic.attr({
opacity: 0
});
point.dataLabel.attr({
opacity: 0 // Hide data labels initially
});
});
} else {
fanAnimate(points[0], startAngleRad);
}
};
}(Highcharts));
Vue transition cloudn’t be loaded automatically
I have a Vue page like below. But it will not be auto loaded when I open it, but I have manually click the refresh to see the content of it.
If I comment out the transition, the page can be shown, indicating that the content has no issue.
I also print the route path, that’s correct as expected, indicating the route works fine.
I want to consult how to make the page be automatically loaded? And also achieving the goal to make it be refreshed when switch back to this page. Thanks in advance!
The vue file:
<template>
<section class="app-main">
<router-view v-slot="{ Component, route }">
<p>route = {{ route.fullPath }}</p>
<transition name="fade-transform" mode="out-in">
<keep-alive :include="cachedViews">
<component :is="Component" :key="route.fullPath" />
</keep-alive>
</transition>
</router-view>
</section>
</template>
<script setup >
import { computed } from 'vue';
import useStore from '@/store';
const { tagsView } = useStore();
const cachedViews = computed(() => tagsView.cachedViews);
</script>
<style lang="scss" scoped>
.app-main {
/*50 = navbar */
min-height: calc(100vh - 50px);
width: 100%;
position: relative;
overflow: hidden;
}
.fixed-header + .app-main {
padding-top: 50px;
}
.hasTagsView {
.app-main {
/* 84 = navbar + tags-view = 50 + 34 */
min-height: calc(100vh - 84px);
}
.fixed-header + .app-main {
padding-top: 84px;
}
}
</style>
<style lang="scss">
// fix css style bug in open el-dialog
.el-popup-parent--hidden {
.fixed-header {
padding-right: 15px;
}
}
</style>
The scss
/* fade-transform */
.fade-transform-enter-active,
.fade-transform-leave-active {
transition: opacity 0.5s, transform 0.5s;
}
.fade-transform-enter-from {
opacity: 0;
transform: translateX(-30px);
}
.fade-transform-enter-to {
opacity: 1;
transform: translateX(0);
}
.fade-transform-leave-from {
opacity: 1;
transform: translateX(0);
}
.fade-transform-leave-to {
opacity: 0;
transform: translateX(30px);
}

