There is a table that is displayed on screen, I have to click on each row and then click the submit button. This process has to be repeated for all the rows present. I wanted to automate the process using JavaScript in chrome console. How do I simulate a click on a row using javascript?
Category: javascript
Category Added in a WPeMatico Campaign
Checking angles to find the top most triangular slice of a circle?
I’m using HTML5 canvas and Javascript to identify the top most triangle in a spin wheel. The following code is helping me identify the slice in the top most position.
Math.abs((sliceCenterAngle - 3 * Math.PI / 2) % (Math.PI * 2)) < sliceAngle / 2;
whereas
Math.abs((sliceCenterAngle - Math.PI / 2) % (Math.PI * 2)) < sliceAngle / 2;
Is showing me the bottom most position.
Why does it seem like this behavior is backwards?
For more context here is the preceding code:
for (let i = 0; i < numSlices; i++) {
const sliceAngle = Math.PI * 2 / numSlices;
const startAngle = i * sliceAngle + angle;
const endAngle = startAngle + sliceAngle;
const sliceCenterAngle = startAngle + sliceAngle / 2;
const isTopSlice = Math.abs((sliceCenterAngle - 3 * Math.PI / 2) % (Math.PI * 2)) < sliceAngle / 2;
In VSCode, why does function type inference break across a property accessor but not a function call
I am writing a typescript declaration file declarations.d.ts that describes some interfaces and a global object. The declarations will be use to assist JavaScript developers that are writing script for an embedded v8 engine that offers global objects like the one being described.
There is a global variable Global of interface type SomeGlobal, which in turn has a property someType of interface type SomeType, and finally SomeType has a callback property of type function like (other:OtherType) => void. Here is the entire file:
declarations.d.ts
interface OtherType
{
stringProperty: string;
}
interface SomeType
{
callback: (other:OtherType) => void;
}
interface SomeGlobal
{
someType: SomeType;
getSomeType(): SomeType;
}
declare var Global: SomeGlobal;
and the jsconfig.json being used to ensure that code in main.js can see these types:
{
"compilerOptions": {
"target": "es6",
"lib": ["es6"],
"strict": true
},
"include": [
"*.js",
"declarations.d.ts"
]
}
From here on, working in main.js:
In VSCode when you attempt to assign the callback property of SomeType and open the parentheses to start building the arrow function like so:
Global.someType.callback = (
I would expect to see autocomplete help like callback(other: OtherType): void, prompting me to complete the statement like:
Global.someType.callback = (other) => {/* do something*/};
But this is not what happens. If I hover over callback VS will display the appropriate signature for the property (property) SomeType.callback: (other: OtherType) => void, but inside the arrow function param list or funtion body, the other param just shows up as type any.
What’s interesting is that if I go through a function call instead of a property:
Global.getSomeType().callback = (
Then there is correct function type inference for callback and I get the intellisense autocomplete you’d expect.
Am I just missing something silly here?
I have tried searches of all kinds via Google and SO. I have tried various combinations of declaring the types as “type”, “interface” or “class”. I have tried declaring the types as classes and then just doing:
let testGlobal = new SomeGlobal();
// then
testGlobal.someType.callback = (other) => {};
still no dice, so it’s not the way the global is declared.
Issue with Importing Images from PHP to PDFKit in Browser – fs.readFileSync is not a function
I’m working with PDFKit in a browser environment and attempting to generate a PDF document with images fetched from a PHP backend. I am facing an issue when trying to load these images, which causes the error:
TypeError: fs.readFileSync is not a function
Here’s what I am doing, I’ve tried many other option from th most simple from pdf kit documentation or other option but that didn’t work for me :
here is my code :
document.getElementById("generate-pdf").addEventListener("click", async function () {
const doc = new PDFDocument({size: 'A4', margins: { top: 30, left: 30, right: 30, bottom: 80 }});
const stream = doc.pipe(blobStream());
const wakaImageUrl = "<?= $page->waka_structure()->toFiles()->first()?->url() ?>"; const coverImageUrl = "<?= $page->images()->template('cover')->first()?->url() ?>";
const response = await fetch(wakaImageUrl);
const wakaImageBuffer = await response.arrayBuffer();
doc.image(wakaImageBuffer, 50, 50, { width: 200 });
…
doc.end();
stream.on("finish", function () {
const url = stream.toBlobURL("application/pdf");
const a = document.createElement("a");
a.href = url;
a.download = "fiche_film.pdf";
a.click();
});
});
Tried also :
const wakaImageResponse = await fetch("<?= $page->waka_structure()->toFiles()->first()?->url() ?>");
const wakaImageBlob = await wakaImageResponse.blob();
const wakaImageURL = URL.createObjectURL(wakaImageBlob);
const coverImageResponse = await fetch("<?= $page->images()->template('cover')->first()?->url() ?>");
const coverImageBlob = await coverImageResponse.blob();
const coverImageURL = URL.createObjectURL(coverImageBlob);
doc.image(wakaImageURL, 50, 50, { width: 200 });
doc.image(coverImageURL, 100, 200, { fit: [400, 300], align: 'center', valign: 'top' });
How can I properly import these images into PDFKit for generating dinamically the images in the PDF it’s the last step to my project and I admit that I’m quite lost at the moment ? Sorry if it’s a dumb question but haven’t found any answer that work for me
Is it possible to shift API call to websocket?
I was asked me to shift api call to websocket in gofiber. Since I’m totally unfamilier with websocket so I googled and watched youtube videos to solve this problem, but The more I searched, the more I felt it is impossible to call api with websocket.
Am I missing something or is it really impossible to call api by websocket? If it is possible, can you please show me an example how to do it
Set Cookie of API Headers Response in browser cookies in App router in nextjs 14
I am trying to set the cookies in the browser Application. I get the cookies values from the response of the API’s headers as set-cookie. This is the value:
'set-cookie': 'sessionid=dbiufbewifbiuewbfuwebufefbew; expires=Sun, 22 Nov 2025 04:02:33 GMT; HttpOnly; Max-Age=31536000; Path=/, expires=Sat, 04 Nov 2024 04:02:33 GMT; HttpOnly; Max-Age=5453453; Path=/',
Here is the page calling the API on the server side.
import { getMainData } from "@/api/server";
export default async function Home() {
const response = await getMainData();
return (
<div>
Home Data
</div>
);
}
This is the API function.
import { BASE_URL } from "@/lib/constants";
export async function getMainData() {
try {
const _res = await fetch(`${BASE_URL}/main/data/`, {
method: "GET",
credentials: "include",
mode: "cors",
});
console.log("_res", _res);
const _data = await _res.json();
return {
response: _data,
};
} catch (error) {
return {
response: error,
};
}
}
Kindly give the solution to set the cookies in the browser.
How to Modify ECharts ThemeRiver to Display as a Stacked Stream Area Chart?
I created a graph using ECharts, based on this example:
https://echarts.apache.org/examples/en/editor.html?c=themeRiver-lastfm&edit=1&reset=1
However, I would like the chart to appear as a stacked stream area, like the image shown above. I’m not sure where or how to modify the code to achieve this. Can someone guide me on how to make these adjustments?
Although I don’t think it’s directly related to the issue, I am also sharing my code below for reference:
async function loadData() {
try {
const response = await fetch("h");
const csvText = await response.text();
const rows = csvText.split("n").filter(row => row.trim() !== "");
const userArray = [];
const headers = rows[0].split(",");
for (let i = 1; i < rows.length; i++) {
const regex = /(".*?"|[^",s]+)(?=s*,|s*$)/g;
const values = rows[i].match(regex).map(value => value.replace(/^"|"$/g, "").trim());
const releaseDate = new Date(values[1]);
const releaseYear = releaseDate.getFullYear();
if (releaseYear !== 2004) continue;
const dailySales = values.slice(2).map(value => {
if (!value || value === "") return 0;
return parseInt(value.replace(/,/g, ""), 10);
});
const extendedDates = Array.from({ length: dailySales.length }, (_, index) => {
const date = new Date(releaseDate);
date.setDate(date.getDate() + index);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
return `${year}/${month}/${day}`;
});
const dataObject = {
영화: values[0],
개봉일: releaseDate,
개봉일차: extendedDates,
일수_매출액: dailySales
};
userArray.push(dataObject);
}
return userArray;
} catch (error) {
console.error("데이터 로드 중 오류 발생:", error);
}
}
function getISOWeek(date) {
const tempDate = new Date(date);
tempDate.setHours(0, 0, 0, 0);
tempDate.setDate(tempDate.getDate() + 3 - ((tempDate.getDay() + 6) % 7));
const week1 = new Date(tempDate.getFullYear(), 0, 4);
return Math.round(((tempDate - week1) / (7 * 24 * 60 * 60 * 1000)) + 1);
}
async function createChart() {
try {
const userArray = await loadData();
const chartDom = document.getElementById("root1");
const myChart = echarts.init(chartDom);
let labels = userArray.map(obj => obj.영화);
let rawData = userArray.map(obj => obj.일수_매출액);
let movieDates = userArray.map(obj => obj.개봉일);
let data = [];
for (let i = 0; i < rawData.length; i++) {
const releaseWeek = getISOWeek(movieDates[i]);
let weeklySales = [];
for (let j = 0; j < rawData[i].length; j += 7) {
const weeklyTotal = rawData[i]
.slice(j, j + 7)
.reduce((sum, value) => sum + value, 0);
weeklySales.push(weeklyTotal);
}
for (let k = 0; k < weeklySales.length; k++) {
let label = labels[i];
let weekNumber = releaseWeek + k;
data.push([weekNumber, weeklySales[k], label]);
}
}
option = {
singleAxis: {
max: 'dataMax'
},
dataZoom: [
{
type: 'slider',
show: true,
start: 0,
end: 100,
handleSize: 8
},
{
type: 'inside',
start: 94,
end: 100
}
],
series: [
{
type: 'themeRiver',
data: data,
label: {
show: false
},
emphasis: {
itemStyle: {
shadowBlur: 20,
shadowColor: 'rgba(0, 0, 0, 0.8)'
},
focus: 'self'
},
}
]
};
myChart.setOption(option);
} catch (error) {
console.error("Error creating chart:", error);
}
}
createChart();
The goal is to find a way to modify the ThemeRiver chart provided by ECharts to display in a stacked stream area format.
how to change the window open page title in react
I want to set the window open new page’s title(this page will open. a pdf file in browser), this is how I do it:
export const handleOpenInBrowserDirect = (projectId: string) => {
if (projectId) {
getPreviewUrl(projectId).then((res) => {
if (ResponseHandler.responseSuccess(res)) {
var newWindow = window.open(res.result, "_blank");
setTimeout(() => {
if (newWindow) {
newWindow.document.title = "New title";
}
}, 300);
}
});
}
};
when I open the new page, the title was changed to New title. But when the new page rendered done. the title changed to preview. Am I missing something? what should I do to change the new page title that opened by window open in react?
I have also tried to listening the load event:
export const handleOpenInBrowserDirect = (projectId: string) => {
if (projectId) {
getPreviewUrl(projectId).then((res) => {
if (ResponseHandler.responseSuccess(res)) {
var newWindow = window.open(res.result, "_blank");
if (newWindow) {
newWindow.addEventListener("load", () => {
if (newWindow) {
newWindow.document.title = "New title";
}
});
}
}
});
}
};
error firebase/firestore: Firestore (11.0.1): Could not reach Cloud Firestore backend
enter image description here[2024-11-23T00:53:36.799Z] @firebase/firestore: Firestore (11.0.1): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=invalid-argument]: 3 INVALID_ARGUMENT: Invalid resource field value in the request.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.
[2024-11-23T00:53:36.797Z] @firebase/firestore: Firestore (11.0.1): GrpcConnection RPC ‘Listen’ stream 0x8e2414ab error. Code: 3 Message: 3 INVALID_ARGUMENT: Invalid resource field value in the request.
[2024-11-23T00:53:36.955Z] @firebase/firestore: Firestore (11.0.1): GrpcConnection RPC ‘Write’ stream 0x8e2414ad error. Code: 3 Message: 3 INVALID_ARGUMENT: Invalid resource field value in the request.
[2024-11-23T00:53:36.980Z] @firebase/firestore: Firestore (11.0.1): GrpcConnection RPC ‘Write’ stream 0x8e2414ae error. Code: 3 Message: 3 INVALID_ARGUMENT: Invalid resource field value in the request.
[2024-11-23T00:53:37.668Z] @firebase/firestore: Firestore (11.0.1): GrpcConnection RPC ‘Write’ stream 0x8e2414af error. Code: 3 Message: 3 INVALID_ARGUMENT: Invalid resource field value in the request.
[2024-11-23T00:53:39.783Z] @firebase/firestore: Firestore (11.0.1): GrpcConnection RPC ‘Write’ stream 0x8e2414b0 error. Code: 3 Message: 3 INVALID_ARGUMENT: Invalid resource field value in the request.
[2024-11-23T00:53:41.486Z] @firebase/firestore: Firestore (11.0.1): GrpcConnection RPC ‘Write’ stream 0x8e2414b1 error. Code: 3 Message: 3 INVALID_ARGUMENT: Invalid resource field value in the request.
[2024-11-23T00:53:44.754Z] @firebase/firestore: Firestore (11.0.1): GrpcConnection RPC ‘Write’ stream 0x8e2414b2 error. Code: 3 Message: 3 INVALID_ARGUMENT: Invalid resource field value in the request.enter image description here
I tried troubleshooting the issue with Firebase Firestore by checking the configuration, validating the request data, and ensuring my Firestore rules are correct. I expected to resolve the error so I could proceed with deploying my portfolio website without connection issues
Why Tesla don’t make a transportation with or like a box teleport? I wish it [closed]
My home town so far. If any box teleport to my hometown. That’s minimize the time.
I try make a object that I can move it with teleport box. But my project unsuccessful. I hope it can, and than I’ll try with a human. Everyone will be happy if that happens.
Is there a way to get around, “www.google.com refused to connect?”
I’ve been trying to make a proxy server, and I’m having trouble requesting data from Google and displaying it. As mentioned in the title, it just says, “www.google.com refused to connect.” I’m mostly a beginner at JS- learned Java when I was in 5th grade and started JS in 7th. However, I only have experience with Pure JS, and not HTML/CSS. Here’s the code I used-
HTML/CSS:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tabbed Interface</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f1f3f4;
}
.tabs {
display: flex;
justify-content: center;
align-items: center;
background-color: white;
border-bottom: 1px solid #ccc;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
padding: 10px 0;
position: sticky;
top: 0;
z-index: 10;
}
.tab {
padding: 10px 20px;
margin: 0 5px;
cursor: pointer;
font-size: 16px;
color: #5f6368;
border-bottom: 3px solid transparent;
transition: border-color 0.3s;
}
.tab:hover {
color: #202124;
}
.tab.active {
color: #1a73e8;
border-bottom: 3px solid #1a73e8;
}
.add-tab {
font-size: 24px;
font-weight: bold;
cursor: pointer;
color: #5f6368;
padding: 0 10px;
transition: color 0.3s;
}
.add-tab:hover {
color: #202124;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
text-align: center;
margin-top: 50px;
}
.logo {
margin: 20px auto;
}
.search-box {
margin: 20px auto;
width: 60%;
display: flex;
align-items: center;
border: 1px solid #dfe1e5;
border-radius: 24px;
background-color: white;
padding: 5px 15px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.search-box input {
flex: 1;
border: none;
outline: none;
font-size: 16px;
padding: 10px;
}
.search-box button {
background: none;
border: none;
cursor: pointer;
color: #5f6368;
font-size: 18px;
}
.buttons {
margin: 20px auto;
}
.buttons button {
margin: 5px;
padding: 10px 20px;
font-size: 14px;
color: white;
background-color: #1a73e8;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
.buttons button:hover {
background-color: #1669c1;
}
</style>
</head>
<body>
<div class="tabs">
<div class="tab active" onclick="showTab('tab1')">Tab 1</div>
<div class="add-tab" onclick="addNewTab()">+</div>
</div>
<div id="tab1" class="tab-content active">
<img src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" alt="Google Logo" class="logo">
<div class="search-box">
<input type="text" placeholder="Search Google or type a URL">
<button>🔍</button>
</div>
<div class="buttons">
<button>Google Search</button>
<button>I'm Feeling Lucky</button>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
JS (Only the “subtabbing” works. The request doesn’t):
let tabCount = 1;
function showTab(tabId) {
const tabs = document.querySelectorAll('.tab-content');
tabs.forEach(tab => {
tab.classList.remove('active');
});
document.getElementById(tabId).classList.add('active');
const tabElements = document.querySelectorAll('.tab');
tabElements.forEach(tab => {
tab.classList.remove('active');
});
event.target.classList.add('active');
}
function addNewTab() {
tabCount++;
const newTabId = `tab${tabCount}`;
const newTab = document.createElement('div');
newTab.className = 'tab';
newTab.textContent = `Tab ${tabCount}`;
newTab.setAttribute('onclick', `showTab('${newTabId}')`);
document.querySelector('.add-tab').before(newTab);
const newTabContent = document.createElement('div');
newTabContent.id = newTabId;
newTabContent.className = 'tab-content';
newTabContent.innerHTML = `
<img src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" alt="Google Logo" class="logo">
<div class="search-box">
<input type="text" id="${newTabId}-search-input" placeholder="Search Google or type a URL">
<button id="${newTabId}-search-btn">🔍</button>
</div>
<div class="buttons">
<button>Google Search</button>
<button>I'm Feeling Lucky</button>
</div>
<div id="${newTabId}-results" class="search-results">
<!-- Iframe for displaying the Google page -->
<iframe id="${newTabId}-iframe" class="search-iframe" style="width: 100%; height: 80vh; display: none;" frameborder="0"></iframe>
</div>
`;
document.body.appendChild(newTabContent);
}
I’ve looked at other proxies (e.g. Rammerhead web-proxy, link: https://freenomisratelimitingme.gq/), but I just don’t understand how they get it to work. I think they use HTTP/HTTPS requests instead of direct fetches to Google’s API, but I’d greatly appreciate it if anyone could get this to work (requesting and loading the data from Google)!
TanStack Start example with javascript if its possible?
Is it possible to use TanStack Start with Javascript instead of Typescript?
If yes – can someone point me to an example online?
I had an additional question – if thats ok. In their documentation (see link below) they specify ssr.tsx in the same place as the client code.
How does one deploy the server separately? I don’t understand this part.
https://tanstack.com/router/latest/docs/framework/react/quick-start
Given a datetime string and a time zone identifier, how can I get the corresponding UTC datetime, server-side?
I’m in a situation where, on the server, I have two values:
- a datetime string like
"2020-01-01T00:00:00" - a timezone string like
"America/Chicago"
How can I create a UTC Date corresponding to this moment in time?
Build cache files are corrupted while trying to run million lint with next
VERSIONS
Next.JS: 14.2.3
React: ^18
DESCRIPTION
Recently I saw a linter which helps you optimize your react code and decided to connect it to my Next.JS project. According to official Get Started section I wrote
npx million@latest
and it ran installation. After installation completed, it changed next.config.mjs
Then when I’m starting localhost in dev mode it shows me error:
⚠ Internal Error: Your build cache files are corrupted and has been reset. Please restart your dev server.
And here is full console logs:
vladi@vlud CLANGARM64 ~/Documents/code/rest/million/reproducible_example (master)
$ npm run dev
> [email protected] dev
> next dev
(node:7096) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
▲ Next.js 14.2.3
- Local: http://localhost:3000
✓ Starting...
(node:10536) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
⚡ Million Lint v1.0.12
✓ Ready in 0.29ms
✓ Ready in 2.6s
○ Compiling / ...
warn - The `content` option in your Tailwind CSS configuration is missing or empty.
warn - Configure your content sources or your generated CSS will be missing styles.
warn - https://tailwindcss.com/docs/content-configuration
✓ Compiled / in 2.2s (504 modules)
GET / 200 in 2291ms
⚠ Internal Error: Your build cache files are corrupted and has been reset. Please restart your dev server.
vladi@vlud CLANGARM64 ~/Documents/code/rest/million/reproducible_example (master)
Example was ran in a clean next.js#14.2.3 project
page.tsx:
"use client";
import { useState } from "react";
export default function Home() {
const [count, setCount] = useState<number>(0);
const increase = () => {
setCount(count + 1);
};
const decrease = () => {
setCount(count - 1);
};
return (
<main>
<button onClick={increase}>+</button>
<p>{count}</p>
<button onClick={decrease}>-</button>
</main>
);
}
next.config.mjs:
import MillionLint from "@million/lint";
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default MillionLint.next({
enabled: true,
rsc: true,
})(nextConfig);
javascript fetch() breaks execution and throws 404
I have a static azure web app and an azure function, both running locally. The function is working and showing results in the browser.
The application is a vanilla javascript app. And I have the following code:
The fetch function
async function fetchResources(city) {
try {
const response = await fetch("http://localhost:7071/api/GetResources/Bogotá");
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
return data;
} catch (error) {
console.error('Error fetching data:', error);
//cityListContainer.innerHTML = `<p>Lo sentimos, no pudimos cargar los datos.</p>`;
}
}
I have a function that loads content according to the path.
else if (path === "/Bogotá") {
const resources = fetchResources("Bogotá");
resources.forEach((resource) => {
const item = document.createElement('div');
item.innerHTML = `
<h3>${resource.name}</h3>
<p>Coordinador: ${resource.coordinator}</p>
<p>Hora: ${resource.time}</p>
<a href="${resource.whatsappGroup}" target="_blank">Grupo de WhatsApp</a>
`;
container.appendChild(item);
});
}
when I go to the web app url: http://127.0.0.1:5500/Bogot%C3%A1, it is succesfully enrouted, and then it enters the fetch function and crashes, without any message in the line “const response = await fetch(“http://localhost:7071/api/GetResources/Bogotá”);”. Or If I don’t step into the method, it reaches “resources.forEach((resource)” in the load content function. Once I hit F10 again, it crashes.
the result is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /Bogot%C3%A1</pre>
</body>
</html>
and the message is:
Bogot%C3%A1:1
GET http://127.0.0.1:5500/Bogot%C3%A1 404 (Not Found)
That response comes from the web app not the function. In the function output I get this.
[2024-11-22T22:19:59.560Z] Executing 'Functions.GetResources' (Reason='This function was programmatically called via the host APIs.', Id=fe5e3e91-c355-4fa5-9253-09b3206f954d)
[2024-11-22T22:19:59.572Z] C# HTTP trigger function processed a request.
[2024-11-22T22:19:59.573Z] Executing OkObjectResult, writing value of type 'Azure.Core.PageableHelpers+FuncPageable`1[[Azure.Data.Tables.TableEntity, Azure.Data.Tables, Version=12.9.1.0, Culture=neutral, PublicKeyToken=92742159e12e44c8]]'.
[2024-11-22T22:20:00.175Z] Executed 'Functions.GetResources' (Succeeded, Id=fe5e3e91-c355-4fa5-9253-09b3206f954d, Duration=615ms)
I cannot figure out what I am missing. I understand the function was run correctly and the response sent, but the web app did not received it.
