The prompt function in python is not working in VS code!
How to take input in Javascript in vs code? It shows Reference error in terminal.f
I want a solution of my question very precise and accurate.Please answer as fast as possible
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
The prompt function in python is not working in VS code!
How to take input in Javascript in vs code? It shows Reference error in terminal.f
I want a solution of my question very precise and accurate.Please answer as fast as possible
i want register. post json request. Consol log json data, i have under sign up text “JSON.parse: unexpected end of data at line 1 column 1 of the JSON data”.
import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
export default function SingUp() {
const [formData, setFormData] = useState({});
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const handleChange = (e) => {
setFormData({
...formData,
[e.target.id]: e.target.value,
});
};
const handleSubmit = async (e) => {
e.preventDefault();
console.log(formData);
try {
setLoading(true);
const res = await fetch("/api/auth/signup", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData),
});
const data = await res.json();
console.log(data);
if (data.success === false) {
setLoadnig(false);
setError(data.message);
return;
}
setLoading(false);
setError(null);
navigate("/sign-in");
} catch (error) {
setLoading(false);
setError(error.message);
}
};
return (
<div onSubmit={handleSubmit} className="p-3 max-w-lg mx-auto">
<h1
className="text-3xl text-center font-semibold
my-7"
>
Sign Up
</h1>
<form className="flex flex-col gap-4">
<input
type="text"
placeholder="username"
className="bord p-3 rounded-lg"
id="username"
onChange={handleChange}
/>
<input
type="email"
placeholder="email"
className="bord p-3 rounded-lg"
id="email"
onChange={handleChange}
/>
<input
type="password"
placeholder="password"
className="bord p-3 rounded-lg"
id="password"
onChange={handleChange}
/>
<button
disabled={loading}
className="bg-slate-700 text-white p-3 rounded-lg uppercase hover:opacity-95 disabled:opacity-80"
>
{loading ? "Loading..." : "Sign Up"}
</button>
</form>
<div className="flex gap-2 mt-5">
<p>Have an account?</p>
<Link to={"/sign-in"}>
<span className="text-blue-700">Sign in</span>
</Link>
</div>
{error && <p className="text-red-500 mt-5">{error}</p>}
</div>
);
}
i want register. post json request. Consol log json data, i have under sign up text “JSON.parse: unexpected end of data at line 1 column 1 of the JSON data”.
i try to send inf to server, and i get “POST
http://localhost:5173/api/auth/signup
[HTTP/1.1 500 Internal Server Error 4065ms]
I’m trying to download or use an array of images that I have saved into the firebase storage bucket.
I have a form with a file input where the user can upload an image to the firebase storeage bucket and then i’m saving that firestore image link into an array called ImageArray.
When the image is uploaded to Firebase storage the file type is Image/png which is what I want. I can also get the link saved in the array and display the images as thumbnails as I like.
However when I then press “Submit” and send all form data to firebase to be saved. the image types in the array of images turn into type application/octet-stream and there for cannot be used as images. But again I have the image link saved in the firestore database.
I’m not sure why the type is changing only when i’m pressing submit and i’m only doing the firebase store handling when uploading and downloading to show as a thumbnail/preview of said image.
Here are some screenshots to help with understanding.
All but the first image in the array change type to application/octet-stream.
only 02_b.png & 02_c.png are in the imageArray
When the user uploads a file They look like this
When user uploads images
When the user presses “Submit” the files look like this
When user has pressed Submit
I’ve tried doing something along the lines of Promise.all and looping through the array and going await getDownloadURL with the correct storeage ref. I best guess is that it’s somewhere within the submit function and the way i’m saving everything at once.
Here is a screenshot of the data that gets saved into the firebase collection
Firebase collection data
My Submit function code looks something like this
const storage = getStorage();
const storageRef = ref(
storage,
`${loggedInUser[0].user_id}/` + 'images/' + `${title}/` + imageName
);
const imagesList = await listAll(storageRef);
// Get download URLs for each image
const imageUrls = await Promise.all(
imagesList.items.map(async (storageRef) => {
const downloadUrl = await getDownloadURL(storageRef);
console.log(downloadUrl);
return downloadUrl;
})
);
console.log('listingImage', listingImage);
console.log('image array', imageArray);
const docRef = await addDoc(collection(db, 'setups'), {
title: title,
description,
listingImage: imageUrl,
images: imageArray,
styles: styleArray,
colours: colourArray,
products: productArray,
ownerId: loggedInUser[0].user_id,
createdAt: new Date(),
slug: title.toLowerCase().replace(/ /g, '-') + '-by-' + loggedInUser[0].username,
featured: false,
approved: false,
createdBy: loggedInUser[0].username,
user: loggedInUser[0].username
});
To summarize, i’m not sure as to why the type changes from images/png to application/octet-stream when pressing the submit button.
Im not sure if i’m on the right path either so any help would be amazing. Also if there is anymore info I can provide ill do my best to provide anything that is needed.
Context:
Using FileSaver.js for downloading a PDF from a URL is opening the download link in a new tab in Safari & Firefox. The saveAs implementation in FileSaver.js is explicitly setting target="_blank". But I couldn’t find the context behind FileSaver.js using target="_blank".
In Chrome, downloads are smooth and target="_blank" doesn’t seem to impact any UX. In Firefox, I notice a little lag in auto closing the new tab after download is closed. But it’s reasonable. But in Safari, the new tab doesn’t close after the download is complete. So the users will see a blank page.
To fix this issue, I have used below code to force open the download link in same tab
const downloadObjectUrl = (objectUrl, filename) => {
const a = document.createElement('a');
a.style.display = 'none';
a.href = objectUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
};
The problem:
With above code, the downloads are working in same tab. BUT, any Fetch calls queued after are failing. In Safari, I don’t see any useful error but in Firefox I see the error NS_BINDING_ABORTED on failed requests.
Please note, the download URL origin & the current web page origins are different.
I tried adding an onclick handled on the link to return false. It resolved issues in Firefox but the download isn’t working in Safari any more.
a.onclick = (ev) => {
return false;
};
I’m facing an issue while trying to read and process a CSV file in Python. I’ve tried using the csv module, but I’m encountering an error that I can’t seem to resolve. Here’s a simplified version of my code:
import csv
file_path = 'path/to/my/file.csv'
try:
with open(file_path, 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
# Process each row (perform some operations)
print(row)
except Exception as e:
print(f"An error occurred: {e}")
basically i was creating a ecommerce website but i,am actually very much confused that how can i first get payment
successfully and then place the order or the
i explain you with some examples
suppose i have a currentOrder Object that contains all the items and my address paymentMethod etc
when i click on pay now button it redirects me to stripe checkout page where i fill all my card details and then the clicks the pay after that it successfully redirects me to order success page where i call a function that then place’s currentOrder in to myOrders array and that way the order gets placed btw here in these examples i use reduxjs toolkit to store current order etc if in case you guys might be wondering
but here the problem is that even if i visit this order success Page by typing that ordersuccess endpoint in the url it will place an order without taking any kind of payment if any currentOrder exist's as i calls that function using useEffect so each time page refreshes it runs and each time an order keeps getting placed
but i dont want this i want to create something that only place's order when the user payment's successully and then order get's placed else not
I’m trying to do the following in a playground:
elt = document.createElement("div")
document.body.prepend(elt)
elt.innerHTML = `<div id="app">
<button @click="count++">
Count is: {{ count }}
</button>
</div>`
app = vue.createApp({setup() { return {count: vue.ref(0)}}});
app.mount("#app")
This basically erases the content from the div but doesn’t do anything else. What am I doing wrong?
I am currently using React Mui Component to render a table view with columns and rows consist of displaying the data retrieved from the database.
Instead of listing all records row by row from the database I want to aggregate all the data that are the same into 1 row. For example, the database shows
type have 4 records of pencils, 2 records of pens, and 1 record of book. Instead of
| type | count |
|---|---|
| pencil | N/A |
| pencil | N/A |
| pencil | N/A |
| pencil | N/A |
| pen | N/A |
| pen | N/A |
| book | N/A |
I want it as
| type | count |
|---|---|
| pencil | 4 |
| pen | 2 |
| book | 1 |
This is what currently have in my component,
<StyledTableCell
id={`type-${schoolId}`}
>
{type || 'N/A'}
</StyledTableCell> // displays type column
<StyledTableCell
id={`count-${schoolId}`}
>
{`${totalAccessories.length}` || 'N/A'} // currently prints N/A
</StyledTableCell>
I almost got it to render as
| type | count |
|---|---|
| pencil 4 pen 2 book 1 | N/A |
| pencil 4 pen 2 book 1 | N/A |
| pencil 4 pen 2 book 1 | N/A |
| pencil 4 pen 2 book 1 | N/A |
| pencil 4 pen 2 book 1 | N/A |
| pencil 4 pen 2 book 1 | N/A |
| pencil 4 pen 2 book 1 | N/A |
with
const uniqueTypes = [...new Set(records.map((record) => record.type))];
const typeCounts = uniqueTypes.reduce((counts, type) => {
counts[type] = records.filter((record) => record.type === type).length;
return counts;
}, {});
return (
<table>
<thead>
<tr>
<th>Type</th>
<th>Count</th>
</tr>
</thead>
<tbody>
{Object.entries(typeCounts).map(([type, count]) => (
<tr key={type}>
<StyledTableCell>{type}</StyledTableCell>
<StyledTableCell>{count}</StyledTableCell>
</tr>
))}
</tbody>
</table>
But it was just creating new row and aggregating with duplicates. And I dont want to use tr or thead since mui react already took care of it. I am fairly new to front end react coding can some fix the current issue to display result correctly with styleTableCell and group each result into 1 and separate pencil, pen, book. Thank you
When I click a button:
cy.contains('Copy Token').click()
I want to automate verification that a specific set of text was copied. And before you ask: the Copy Token button works and always shares the same Token every time, so I know its not a problem with the website itself.
I am using a Cypress Project with Javascript.
I found this article: Testing copy to clipboard with Cypress
So I went ahead and tried converting this solution to my code:
it('should verify that the correct token was copied', () => {
...
token = '<almost 1900 character token>'
cy.contains('Copy Token').click()
cy.assertValueCopiedToClipboard(token)
}
Cypress.Commands.add('assertValueCopiedToClipboard', value => {
cy.window().then(win => {
win.navigator.clipboard.readText().then(text => {
expect(text).to.eq(value)
})
})
})
This code does no verification. It’s as if Cypress skips trying to verify what’s been copied to the Clipboard, and I don’t know why. It doesn’t matter what I set token to.
This was a suggestion in a StackOverflow Solution Comment here, linking to this GitHub link. So I tried this:
cy.contains('Copy Token').click()
cy.window().its('navigator.clipboard')
.then((clip) => clip.readText())
.should('equal', token)
I will receive the error:
-then function(){}
NotAllowedError
Document is not focused.
According to Cypress’s official page, .focus() should be on the end of the command. So I’ve tried this (since I’m not supposed to focus on cy.window, right?)
cy.contains('Copy Token').click().focus()
cy.window().its('navigator.clipboard')
.then((clip) => clip.readText())
.should('equal', token)
Still the same error. I feel like the 2nd Solution might be on the right track though, since I see the following in the output before the error:
its navigator.clipboard
I’ve also tried a couple other things, but they’ve resulted in Syntax Errors and I really don’t think any of them are on the right track at all.
What should I do? Am I at least on the right track?
how to use dynamic routes in nextjs and accessing params in the second page
here is what the pages structure looks like :
My Code :
/jobs/[id]/index.tsx
"use client"
import React, { useState } from 'react'
import { createClient } from '@supabase/supabase-js';
export default function JobDetails({ params }: { params: { id: string } }) {
const [job, setJob] = useState<any[] | null>([])
console.log(params)
async function fetchJobDetails() {
const supabase = createClient(supabaseUrl, supabaseAnonKey);
const { data: fetchedJob } = await supabase
.from('jobs')
.select("*")
.eq('id', params.id)
setJob(fetchedJob)
}
fetchJobDetails()
return (
<div>
<p>asd</p>
</div>
)
}
jobsTable.tsx
import React, { useState } from 'react'
import { Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from '@mui/material'
import { createClient } from '@supabase/supabase-js';
import Link from 'next/link';
export default function JobsTable() {
const [jobs, setJobs] = useState<any[] | null>([])
async function fetchCountries() {
const supabase = createClient(supabaseUrl, supabaseAnonKey);
const { data: fetchedJobs } = await supabase.from("jobs").select("*,cities!inner(*)");
setJobs(fetchedJobs)
}
fetchCountries();
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }} aria-label='simple table'>
<TableHead>
<TableRow>
<TableCell>Title En|AR</TableCell>
</TableRow>
</TableHead>
<TableBody>
{jobs?.map((job: any) =>
(
<TableRow
key={job.id}
sx={{
'&:last-of-type td, &:last-of-type th': {
border: 0
}
}}
>
<Link href={`/jobs/${job.id}`} passHref>
<TableCell component='th' scope='row'>
{job.title_en} | {job.title_ar}
</TableCell>
</Link>
</TableRow>
)
)}
</TableBody>
</Table>
</TableContainer>
)
}
But I am unable to catch params at all. the output of console.log(params) is always undefined
I am new at React Native and struggling with the FlatList component. I currently have two functions, inside function “ItemHolders”, I have a flatlist that calls my second function, “WardrobeSubsection”. The problem is that, even though inside my WardrobeSubsection function both subsections are displayed in the terminal (due to the console log), only one is appearing on my screen. How can I solve this?
Here is the data I try to pass to flatlist inside ItemHolders:
const [itemData] = useState<Items | null>({
title: 'Tops',
subcategory: [
{
id: '12',
title: 'Tank Tops',
item: [{id: '4'}, {id: '5'}],
},
{
id: '14',
title: 'Sweaters',
item: [{id: '6'}, {id: '7'}],
},
],
});
Here is the flatlist (I pass itemData.subcategory):
return (
<View style={styles.container}>
<TouchableOpacity
onPress={() => setShowFullSection(!showFullSection)}
style={styles.headingContainer}>
<Text style={styles.title}>{itemData?.title}</Text>
</TouchableOpacity>
{showFullSection && (
<FlatList
keyExtractor={item => item.id}
data={itemData?.subcategory}
renderItem={({item}) => <WardrobeSubsection subcategory={item} />}
/>
)}
</View>
);
The WardrobeSubsection:
const WardrobeSubsection: React.FC<SubcategoryProps> = props => {
console.log('Subcategory data:', props.subcategory);
return (
<View style={styles.container}>
<View style={styles.headingContainer}>
<Text style={styles.title}>{props.subcategory.title}</Text>
</View>
{props.subcategory.item.map(items => (
<Text key={items.id}>{items.id}</Text>
))}
</View>
);
};
The output of the console log:
LOG Subcategory data: {"id": "12", "item": [{"id": "4"}, {"id": "5"}], "title": "Tank Tops"}
LOG Subcategory data: {"id": "14", "item": [{"id": "6"}, {"id": "7"}], "title": "Sweaters"}
However, it is displayed as:
displayed result
I was expecting to see both Sweaters and Tank Tops.
Thank you for your time!
Previously, I had solve the question easily by making the logics .But now a days I had forgotten my concepts of programing language and facing problem to solving the question.
I had tried by firstly doing revision after that I had to Jump on solving question .But it is not worth it for me .
I am building a website that will display some generated content and would like to prevent XSS. Rendered templates are HTML content, but can I somehow (with CSP response headers) prevent or disallow execution of any Javascript?
Or sanitization of content to detect script (onclick, …) content is the only way?
If that’s the case, is there some standard .NET Core library to sanitize JS and leave other HTML tags?
Following is my code:
useEffect(() => {
const handler = ev => {
console.log(ev.data, src, ev.data.form);
if (ev.data.type === "height") {
if (ev.data.form === src) {
setHeight((parseInt(ev.data.message, 10) + 10) + "px");
}
}
if (ev.data.type === "popup") {
if (ev.data.form === src) {
setPopUpModel(ev.data.message);
}
}
};
if (typeof window !== "undefined") {
window.addEventListener("message", handler);
return () => window.removeEventListener("message", handler);
}
},
In web form I have a Submit button and it looks very good when I resize my screen the submit button gets cut like below:

Can anyone help me with what should I add to my syntax to solve this issue?
I am using Typescript on my Vue page and trying to fetch user data from API.
<script setup lang="ts">
const { data: user } = await useFetch('/api/user/info', {
headers: useRequestHeaders(['cookie'])
});
if (!user.value)
throw createError('Problems when fetching current user!');
</script>
However I get tons of errors!
When I try to use user.value in script I get user.value possibly null errors and inside template I get __VLS_ctx.user possibly null errors.
Errors disappear when I remove lang="ts" attribute from script but I don’t want to do this. How to fix this problem?