Is there a 64bit/bigint version of Math.clz32() in node?
I know we can loop it twice for 64 bits, but those would yield in 2 instructions at CPU/ALU which wont be efficient since this code is in a highly optimized code path..
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
Is there a 64bit/bigint version of Math.clz32() in node?
I know we can loop it twice for 64 bits, but those would yield in 2 instructions at CPU/ALU which wont be efficient since this code is in a highly optimized code path..
I tried to find some information on how sessions work on an SSO and OAuth2 authorization server from the backend side but couldn’t find specific details. I need this information because I am building my own SSO and OAuth2 authorization server. The only information I managed to find is that they use cookies and an ID token, at least some of them, or access and refresh tokens.
I need to verify a token on both sides when refreshing the token or logging out from the account on the authorization server, both in the request and stored somewhere on the server. (And I’m not talking about the action of your application and the authorization server, but the user and the authorization server.)
I asked several friends, and each one told me something different, like I should store the refresh token as cookies, in a database, or in local storage. I also heard that I should use cache/Redis/sessions and that I shouldn’t use these either. While searching for information on the internet, I came across a statement that the refresh token should not be stored in cookies or local storage because it should remain confidential.
That’s why I decided to ask this question here, because I want to do it correctly and professionally like on those large services. Although large services probably use NoSQL databases and similar solutions.
I wonder if there is a simpler way to write this, or is it already in it’s most basic form?
A ? (B && C) : B
I am building a NestJS RESTful API for a library. I have a Book entity and a Category entity. Each book has a category.
Book entity
@Entity()
export class Book {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column()
author: string;
@ManyToOne(() => Category, (category) => category.id)
category: Category;
@ManyToOne(() => User)
@JoinColumn({ name: 'createdBy', referencedColumnName: 'id' })
user: User;
@Column()
createdBy: number;
}
Category entity
@Entity()
export class Category {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
description: string;
@OneToMany(() => Book, (book) => book.category)
books: Book[];
}
This is the DTO to create a book:
export class CreateBookDto {
@IsString()
@MinLength(3)
title: string;
@IsString()
@MinLength(3)
author: string;
@IsString()
category: string;
}
This is the function that creates a new book:
async create(createBookDto: CreateBookDto, user: ActiveUserInterface) {
const category = await this.validateCategory(createBookDto.category);
return await this.bookRepository.save({
...createBookDto,
category: category,
createdBy: user.sub,
});
}
And this is the function that validates categories:
private async validateCategory(category: string) {
const categoryEntity = await this.categoryRepository.findOneBy({
name: category,
});
if (!categoryEntity) {
throw new NotFoundException('Category not found');
}
return categoryEntity;
}
My question is: why do I need to add again the category on the function to save the book on the DB if it’s already defined on the DTO? Actually it works as I expect, but why don’t they overlap each other at the time it’s saved on the DB?
I tried to create a new book, and it works as expected. I just don’t understand why does it work.
The error is continuously coming:
> return new RegExp(path, flags);
^
SyntaxError: Invalid regular expression: /^function asyncUtilWrap(...args) {
const fnReturn = fn(...args)
const next = args[args.length-1]
return Promise.resolve(fnReturn).catch(next)
}/?$/i: Range out of order in character class
at new RegExp (<anonymous>)
at pathtoRegexp (C:UserszAdministratorDesktopFull-StackMERN-AUTHnode_modulespath-to-
regexpindex.js:128:10)
at new Layer (C:UserszAdministratorDesktopFull-StackMERN-
AUTHnode_modulesexpresslibrouterlayer.js:45:17)
at Function.route (C:UserszAdministratorDesktopFull-StackMERN-
AUTHnode_modulesexpresslibrouterindex.js:505:15)
at proto.<computed> [as get] (C:UserszAdministratorDesktopFull-StackMERN-
AUTHnode_modulesexpresslibrouterindex.js:520:22)
at file:///C:/Users/zAdministrator/Desktop/Full-Stack/MERN-AUTH/backend/routes/userRoutes.js:16:25
at ModuleJob.run (node:internal/modules/esm/module_job:222:25)
at async ModuleLoader.import (node:internal/modules/esm/loader:316:24)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:123:5)
Node.js v20.15.1
I’ve been documenting my JS using jsdoc and am now converting to d.ts files in order to have these exported as types from my package. I want to keep things as DRY as possible.
declare class CallHistory {
constructor(globalConfig: FetchMockConfig, router: Router);
...
}
export default CallHistory
/**
* @import CallHistory from '../types/CallHistory';
*/
class CallHistory {
constructor(globalConfig, router) {
/** @type {CallLog[]} */
this.callLogs = [];
this.config = globalConfig;
this.router = router;
}
}
I’m getting warnings that globalConfig and router “implicitly has an ‘any’ type.”
I’ve tried adding /** @type {CallHistory} */, /** @class {CallHistory} */, /** @class CallHistory */, /** @class */, /** @type {typeof CallHistory} */ in order to get the methods to make use of the types from the class definition in the CallHistory.d.ts file, but none work.
How do I get the typechecker to understand that my js class is the implementation of the ts class?
Please explain the process of sourcing profiles or resumes on stack overflow
Explain to source resumes through normal and Boolean where all the skill must to entered through the search options.
There can be full or part of skills mentioned in the resume also to find the resumes.
I am just starting with Next.js I have been trying to access the web cam for a project I have been working on but I have found an issue when it comes to writing in the “script” tag
Here is the simple code for page.js
export default function Live(){
return(
<html>
<body>
<video id="webCam" autoPlay width="600" height="600"></video>
<a download>Take Picture</a>
<script src="myscript.js" />
</body>
</html>
);
}
Here is the code for the “myscript.js” file
console.log("in")
const webCamEle = document.getElementByID("webCam");
navigator.mediaDevices.getUserMedia({video: true}).then((stream)=> {
webCamEle.srcObject = stream
}).catch((error) => {console.error(error)});
I don’t even get the console logs which leads me to believe that it’s not finding the file at all. Every video I have followed showed that I have been doing the right things and when I run the app, all I get is the button popping up. I’m hoping to get a live camera feed to pop up eventually but now I just want to know that the “myscript.js” file is being read.
I want to all files that start with T- and contain only numbers to return a match:
T-123-32.DOCX
But if the file contains letters it does not return a match:
T-12G-XX-X.DOCX
How can I have it ignore the file extension?
This is currently what I have:
T-[0-9-]+.[^.]*$
so the thing is that I have slider in which each card has link over it and when I try to do mousedown event on the whole element if that mouse is on the card it is perceived as click.
<div class="offers-slider">
<div class="slider-inner">
<div class="offer">
<a href="#">
<div class="image-container">
<img src="./assets/offer-slider1.jpg">
</div>
<div class="offer-content">
<p>dfsd</p>
<h3>sdfasf</h3>
</div>
</a>
</div>
<div class="offer"></div>
<div class="offer">
</div>
<div class="offer"></div>
<div class="offer"></div>
<div class="offer"></div>
</div>
</div>
so this is the element and I just want it to become draggable
let isPressed = false;
let cursorXSpace;
let scrollLeft;
slider.addEventListener("mousedown", (e) => {
isPressed = true;
cursorXSpace = e.clientX - sliderInner.getBoundingClientRect().left;
scrollLeft = sliderInner.scrollLeft;
slider.style.cursor = "grabbing"; // Change cursor to grabbing when dragging
});
window.addEventListener("mouseup", () => {
isPressed = false;
slider.style.cursor = "grab"; // Change cursor back to grab when not dragging
});
slider.addEventListener("mousemove", (e) => {
if (!isPressed) return;
e.preventDefault();
const x = e.clientX;
const move = (x - cursorXSpace);
sliderInner.scrollLeft = scrollLeft - move;
boundCards();
});
function boundCards() {
const slider_rect = slider.getBoundingClientRect();
const sliderInner_rect = sliderInner.getBoundingClientRect();
if (sliderInner.scrollLeft < 0) {
sliderInner.scrollLeft = 0;
} else if (sliderInner.scrollLeft + sliderInner.clientWidth > sliderInner.scrollWidth) {
sliderInner.scrollLeft = sliderInner.scrollWidth - sliderInner.clientWidth;
}
}
I tried this
I’m trying to transform a JavaScript class which dynamically manages other classes for use in a web-based game engine into a TypeScript class for proper type checking (or, more accurately, write a .d.ts description of said class which follows its behavior). This class is called ScriptContainer, and allows one to dynamically add or remove scripts derived from the abstract ElementScript class, the details of which aren’t important for this post.
The way scripts are added and accessed via the ScriptContainer works as follows: say we have a script called HelloWorld that we want to add to the container. You would call the add method of the ScriptContainer, with the constructor HelloWorld and any parameters that need to be forwarded to said constructor as parameters:
class HelloWorld extends ElementScript {
constructor(a, b) {
super(/* ... */);
}
someMethod() { /* ... */ }
}
const scripts = new ScriptContainer(/* ... */).add(HelloWorld, /* ... */);
You’d then be able to access the newly added script as a member of the script container via the constructor’s name:
scripts.HelloWorld.someMethod(/* ... */);
(or, alternatively, provide you own name for the added script like this:)
new ScriptContainer(/* ... */).add('Foo', HelloWorld, /* ... */).Foo;
And fire methods with the same name across multiple loaded scripts via this interface:
scripts.run('someMethod', /* ... */);
The biggest problem I’ve ran into so far in regards to properly representing this behavior via TypeScript is that I can’t get a specifically typed representation of a class’s name from the passed-in constructor. The closest workaround I’ve been able to implement so far is to make use of Symbol.toStringTag, but it’s obviously not ideal:
class HelloWorld extends ElementScript {
/* ... */
get [Symbol.toStringTag]() { return 'HelloWorld' as const; }
}
// == .d.ts FILE =============================================================================== //
type ScriptContainer<Scripts extends Record<string, ElementScript> = {}> = {
add<Cons extends { new(...args: any[]): ElementScript; }>(
script: Cons,
...args: ConstructorParameters<Cons>
): Cons extends { new(...args: any[]): infer Klass extends ElementScript; } ?
Klass extends { [_ in typeof Symbol.toStringTag]: infer Name extends string; } ?
ScriptContainer<Scripts & { [_ in Name]: Klass; }> : never : never;
add<Name extends string, Cons extends { new(...args: any[]): ElementScript; }>(
name: Name,
script: Cons,
...args: ConstructorParameters<Cons>
): Cons extends { new(...args: any[]): infer Klass extends ElementScript; } ?
ScriptContainer<Scripts & { [_ in Name]: Klass; }> : never;
/* ... */
};
I’ve tried to infer the constructor name via Cons extends { name: infer Name extends string }, but the inferred Name always seems to resolve to a string and nothing else more specific.
Does anybody know a better way to do this?
I am trying to achieve a rolling y-axis list which I successfully coded. Here is the behaviour.

I’m working on a React component where I dynamically apply Tailwind CSS classes based on a prop (deviceWidth). The problem is that on the first render, the component does not apply the desired styles. However, if I hardcode the values and then switch back to the dynamic approach, the styles apply correctly.
import React, { useState, useEffect, useRef } from 'react';
function Hero(props) {
const [currentIndex, setCurrentIndex] = useState(40);
const myRef = useRef(null);
useEffect(() => {
const element = myRef.current;
let intervalId;
const updateScroll = () => {
if (currentIndex <= 160) {
setCurrentIndex(prevIndex => prevIndex + 40);
element.scroll({ top: currentIndex, behavior: 'smooth' });
} else {
setCurrentIndex(0);
element.scroll({ top: currentIndex, behavior: 'smooth' });
}
};
intervalId = setInterval(updateScroll, 1000);
return () => clearInterval(intervalId);
}, [currentIndex]);
const roles = ["Title 1", "Title 2", "Title 3", "Title 4"];
const sizing = {
"sm" : {
h: "2",
t: "4"
},
"md" :{
h: "4",
t: "5"
},
"lg" :{
h: "6",
t: "6"
}
};
const deviceSizing = sizing[props.deviceWidth] || sizing.sm;
return (
<header className="mt-6 flex flex-col">
<div className="text-center text-4xl font-semibold">I'm</div>
<div className={`m-2 h-${deviceSizing.h} snap-y snap-mandatory overflow-y-hidden text-center text-${deviceSizing.t}xl font-semibold`} ref={myRef}>
{roles.map(item => (
<div key={item} className="mb-2 snap-center underline decoration-green-500">{item}</div>
))}
</div>
</header>
);
}
export default Hero;
Steps to Reproduce:
Create a React component that uses dynamic Tailwind CSS classes based on a prop.
Pass different values to the prop (deviceWidth) and observe the initial render.
Notice that the styles are not applied correctly on the first render.
What I’ve Tried:
Hardcoding the values instead of using the dynamic approach works.
Switching back to dynamic values after hardcoding seems to fix the issue temporarily.
Question: How can I ensure that Tailwind CSS applies the dynamic classes correctly on the initial render?
Additional Information:
I’m using Tailwind CSS with JIT mode enabled.
The issue occurs regardless of the value passed to deviceWidth (e.g., “sm”, “md”, “lg”).
Any help or suggestions on how to resolve this issue would be greatly appreciated!
Given an integer array nums and an integer k, find the number of subarrays whose sum is equal to k.
The solution they gave to this problem (includes negative numbers)
var subarraySum = function(nums, k) {
let counts = new Map();
counts.set(0, 1);
let ans = 0, curr = 0;
for (const num of nums) {
curr += num;
ans += counts.get(curr - k) || 0;
counts.set(curr, (counts.get(curr) || 0) + 1);
}
return ans;
};
I then gave an input of [-3,6,-3,6,-3] and k= 3, but it returns 5 instead of 4. It just so happens that the Map contains key=0, count=2 and adding that 2 in messes things up. I was really trying to understand this maintaining counts of total sums by trying varying arrays.
thanks!
There example of [1, 2, 1, 2, 1] and k=3 works but then I changed it to negatives since that is supposed to be possible.
I am trying to figure out why we care about keeping track of how many times things add up to 0, things add up to 1, things add up to x. I thought we only care about how many things add up to k(and in this case, k=3).
I have code like this:
for (const item of items) {
myMap[`${item.id}`] = {
valueA: item.A,
valueB: item.B,
valueC: item.C,
valueD: item.D
};
}
This is creating output like:
"1234": {
"valueA": "A",
"valueB": "B",
"valueC": "C",
"valueD": "D"
},
"5678": {
"valueA": "E",
"valueB": "F",
"valueC": "G",
"valueD": "H"
},
"9876": {
"valueA": "A",
"valueB": "B",
"valueC": "C",
"valueD": "D"
}
The id is changing but the contents of the object within the map are the same. How can I amend this so a value only gets added to the map collection if the entire contents of the map are unique. So in my example data above the item with id 9876 would not get added too myMap because the values are already present with id 1234
while testing my html5,js,php project form, i discovered that if i type .htaccess into a text input field or a textarea field that it causes the 403 forbidden page when i submit the form.
I understand that .htaccess file is a text file but i do have it secured deny all from public. I also noticed that the 403 happens before js can filter the content or before php can echo the $_POST value of the form. It goes directly to 403 when form submitted.
Is this a security issue or expected behavior.
To duplicate the issue i have to type dot htaccess example .htaccess, just typing the word htaccess processes like normal text.
I tried other web pages to see if same behavior and that test was mostly negative. I was expecting any kind of code to be removed from the text via js or php filter.
Can anyone explain why this might be happening. Thank You