In material table one of the column has to be trim ..for example input is ramesh-123-india ,the output should be come as only “india”….how to do this
Category: javascript
Category Added in a WPeMatico Campaign
specific item from an object in local storage is not removing
let cartItems = localStorage.getItem("ProductsinCart");
cartItems = JSON.parse(cartItems);
Object.values(cartItems).map(item => {
let productNumbers2 = localStorage.getItem('cartNumbers2');
productNumbers2 = parseInt(productNumbers2);
let cartcost = localStorage.getItem('totalCost');
cartcost = parseFloat(cartcost);
let inCart = item.inCart;
if (item.id === id)
{
localStorage.removeItem(cartItems[item.tag]);
console.log(cartItems);
}
CodingAllInOne:
description: “notNow”
id: 4
imgSrc: “./imagesForCart/programmingBooks/CodingAllInOne.jfif”
inCart: 1
inStock: 39
name: “Coding All In One”
price: 29.99
tag: “CodingAllInOne”
[[Prototype]]: Object
DesignPatterns:
description: “notNow”
id: 6
imgSrc: “./imagesForCart/programmingBooks/DesignPatterns.jfif”
inCart: 1
inStock: 39
name: “Design Patterns”
price: 9.99
tag: “DesignPatterns”
[[Prototype]]: Object
how to map a json object into another new object
i have a payload response which goes like:
"requirementDetails": {
"requirementId1": "A",
"requirementId2": "B",
"requirementId3": "C",
"requirementId4": "D",
"requirementId5": "E",
"requirementId6": "",
"requirementId7": "",
"requirementId8": "",
"requirementId9": "",
}
and i want to create new array of the requirements which will not take the blank requirements using javascript map function and i want the resultant array to look like this:
data = [ "A","B","C","D","E"]
can anybody please help me out.
Chrome Extension “Uncaught Type Error: Cannot read properties of undefined (reading ‘query’) error”. querry property there was a mistake
I am trying to develop an extension for chrome. I did the necessary operations in the Process.js file. The codes worked but I got an undefined query error. This error did not prevent the code. There was a problem only in the share part in Google Slides. what do you think is the reason?
The system is working, but how can i prevent that warning ?
Please help me ?
Share google slides button not working. It works when I remove the plugin.
process.js
chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
let url = tabs[0].url;
url = url.replace('//', ';;').replace(/[/]/g, ';');
let pageTitle = tabs[0].title;
pageTitle = pageTitle.replaceAll("'", '*');
pageTitle = pageTitle.replaceAll('"', '**');
pageTitle = pageTitle.replace('//', '__').replace(/[/_]/g, '_');
});
google Slides and chrome extension image
chrome extension error log image
manifest.json
{
"name": "DergiPark",
"description": "This is a DergiPark Product. Powered by DergiPark.",
"content_scripts": [
{
"js": [
"/js/jquery.min.js",
"/js/alert_util.js",
"process.js"
],
"css": [
"/css/bootstrap.css"
],
"matches": [
"http://*/*",
"https://*/*"
]
}
],
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"icons": {
"48": "icons/DP-02.png",
"128": "icons/DP-02.png"
},
"action": {
"default_icon": {
"16": "icons/DP-02.png",
"24": "icons/DP-02.png",
"32": "icons/DP-02.png"
},
"default_popup": "popup.html"
},
"permissions": [
"activeTab", "tabs"
]
}
FormData not sending File object through Post request
I am making an axios.post() request in my Vue component to send some formData holding a media File to upload through a PHP script. I know the file object is being appended correctly as I log the data before the request here:
// this.postMedia is a Vue array holding any post media objects to be uploaded
this.postMedia.forEach((mediaObj, index) => {
formData.append('media[' + index + ']', mediaObj.media);
formData.append('mediaType[' + index + ']', mediaObj.mediaType);
});
// Logging formData
for (let p of formData.entries()) {
console.log(p);
}
This logs the information of the file object and the corresponding media type as expected.
// This is the media data
File {
lastModified: 1627299857401
lastModifiedDate: Mon Jul 26 2021 07:44:17 GMT-0400 (Eastern Daylight Time) {}
name: "test-image.jpg"
size: 12295
type: "image/jpeg"
webkitRelativePath: ""
}
// This is the mediaType data
1
I am then passing this data through an axios request and logging the response data as follows:
// Vue.js file
axios.post('/api/createPostV2', formData, config)
.then(success => {
console.log(success.data);
})
.catch(function(err) {
console.log(err.response);
});
// PHP file being requested (/api/createPostV2)
public static function createPostV2(Request $request)
{
// Just return request to check data
return $request->all();
}
Here is what gets logged:
media: Array(1)
0: {}
length: 1
[[Prototype]]: Array(0)
mediaType: ['1']
So it is passing the media array, but the actual file is not being passed as you can see by the empty object at index 0. As you can see the mediaType is passed correctly, keep in mind both ‘media’ and ‘mediaType’ are arrays to support uploading multiple files. Am I missing something here? Why is the file data being lost when I am passing it through formData?
jquery ajax header sending error Access to XMLHttpRequest at https://discord.com/api/guilds/1234567890
<script>
const URL = "https://discord.com/api/guilds/899175503565553714";
$.ajax({
url: URL,
type: "GET",
headers: { Authorization: 'Bot ' + token } })
</script>
Here is my code
index.html:1 Access to XMLHttpRequest at 'https://discord.com/api/guilds/899175503565553714' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
How can I send headers and receive values ​​successfully with jquery ?
Get data from google firebase’s firestore, put into global object/array javascript, react
I am trying to read from firestore and push that data into a global variable. I am able to push however the array acts differently outside the function (I’ve attached a screenshot from the console showing the dif). For example I can call data[0]
or data[1]
inside the function just fine but outside it returns “undefined“. Can anyone help with this?
This is for a react project, so if there is a way to do it using react hooks or something like that, I can implement no problem.
let fbData = [];
const GetData = async () => {
const q = query(collection(db, "surveys"), where("surveyComplete", "==", true));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
fbData.push({
[doc.data().surveyId]: {
"name": doc.data().surveyName,
"id": doc.data().surveyId
}
});
},
function (error) {
console.log("Error getting documents: ", error);
});
}
And yes I know the way I structure my data is weird, I’m planning on fixing it once I figure this issue out.
thanks
Devskiller Angular test questions [closed]
Angular Interview Questions from Devskiller?
- In Angular 2+, the method bypassSecurityTrustResourceUrl marked value as ____
(a) Low Risk
(b) trusted
(c) Compatible
(d) acceptable
2. Which of the following are proper ways to create an interface/type Point3D which would include all properties of Point and additionally z: number?
(a) type Point3D = Point <{
z: number
}>
(b) type Point3D = Record<"x" | "y" | "z", number>
(c) type Point3D = Point & {z: number}
(d) interface Point3D extends Point {
z:number
}
3. Which of the following statements are correct about relations between observables and promises?
(a) The promises can return to their pending state, contrary to observables.
(b) Observables can be cancelled, there is no way to cancel promise
(c) A promise can easily be converted to an observable using from pipeable operator
(d) They are the same and such can be used interchangeably
(e) A promise changes state only once, an observable can receive several events
Decrement the value of a variable at every function call
I am creating a slot machine program using JavaScript, and want to decrement the value of coins at every function call. For example, coins = 20
. It should decrement after every time the casino()
function is called. Basically the function can be called as many times until coins = 0
.
Is this a situation where the application of let
vs var
comes into play?
Here is a snippet of my code:
let reel1 = ["cherry", "lemon", "apple", "lemon", "banana", "banana", "lemon", "lemon"]
let reel2 = ["lemon", "apple", "lemon", "lemon", "cherry", "apple", "banana", "lemon"]
let reel3 = ["lemon", "apple", "lemon", "apple", "cherry", "lemon", "banana", "lemon"]
let slotReel = []
let coins = 20
function casino(r1, r2, r3) {
coins = coins - 1
let random1 = reel1[Math.floor(Math.random() * reel1.length)]
let random2 = reel2[Math.floor(Math.random() * reel3.length)]
let random3 = reel3[Math.floor(Math.random() * reel3.length)]
slotReel.push(random1, random2, random3)
//.....some logic
}
casino(reel1, reel2, reel3)
set Dynamic Default Value for select dropdown in react
I have a form, where I need to set the default value of the select dropdown in formik.
SelectDropDown.js
{props.options.map((option) => {
return (
<option key={option.id} value={option.id} title={option.title}>
{option.name}
</option>
);
})}
App.js
<SelectDropdown
control="select"
name="episodeType"
data-testid="episodeType"
id="episodeType"
label="Episode Type"
options={dropDownValues} // how to pass defualt a props
/>
How to pass the default values as props so the page is loaded the values is selected.
Thank you.
How to select variant class in styled components?
In styled-components
we can have contextual styles using component selector patterns. But how do we parents variant to contextual the child component? For example, we have three components here, Child
, NoteWrapper
, and Note
.
const Child = styled.div<{ editing?: boolean }>`
${props => props.editing && css`some styles`}
`
const NoteWrapper = styled.div<{ compact?: boolean }>`
${props => props.compact && css`some styles`}
`
const Note = styled.input`
/* How do I style this when Child is editing and NoteWrapper is compact */
`
const App = () => {
return (
<Child editing>
<NoteWrapper compact>
<Note/>
</NoteWrapper>
</Child>
)
}
`
With plain CSS we could do something like this
.child.editing .note-wrapper.compact .note {
/* Contextual styles here */
}
My question is how do I style Note
when Child
is editing
and NoteWrapper
is compact
in styled components selector pattern ?
What should I answer when asked about the toughest/challenging task you did as a front-end developer? [closed]
As my experience with react and angular, I don’t think I have done anything challenging where I had to scratch my head as most of my experience comes from business applications where there are fewer users. Only the complexities lie in business logic. Anyone can give some scenario like this can be very helpful.
how to retrieve key and value from object search?
I want to find a page url searching by an input. I have an object that contains keywords and urls. Then when press enter it will do a check, if the keywords are the same or exist, it will display the url, if not it will display not found.
So for example in the input I type “home”, when I enter it will display the url “/homepage” because the keywords are exist, if I type “contact” it will show not found because the keywords doesn’t exist.
I’ve made the code like below but why the map doesn’t work? can anyone help me?
$(document).ready(function(){
$("#searchKeywords").on("keypress", function(e){
if(e.which == 13){
const pageKeywords = {
"home" : "/homepage",
"about" : "/about-us"
}
pageKeywords.map((key,value) => {
console.log(key)
if($(this).val() == key){
console.log(value)
}else{
console.log('not found')
}
})
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="searchKeywords">
populate items from promotion node express js
promotion Modele
const mongoose = require("mongoose");
const PromotionSchema = mongoose.Schema({
name: { type: String, required: true },
item1: {
type: mongoose.Schema.Types.ObjectId,
ref: "itemPromotion",
required: true,
},
item2: {
type: mongoose.Schema.Types.ObjectId,
ref: "itemPromotion",
required: false,
},
item3: {
type: mongoose.Schema.Types.ObjectId,
ref: "itemPromotion",
required: false,
},
startDate: { type: Date, required: false },
endOfDate: { type: Date, required: false },
status: { type: Boolean, required: false },
totalPrice: { type: Number, required: false },
discount: { type: Number, required: false },
});
module.exports = new mongoose.model("Promotion", PromotionSchema);
promotion Items its item with price and quantity and discount pourcent in promotion
const mongoose = require("mongoose");
const ItemPromotionSchema = mongoose.Schema({
item: { type: mongoose.Schema.Types.ObjectId, ref: "Item", required: true },
price: { type: Number, required: true },
quantity: { type: Number, required: true },
discount: { type: Number, required: true },
});
module.exports = new mongoose.model("itemPromotion", ItemPromotionSchema);
items its the orginal item
const mongosse = require("mongoose");
const ItemSchema = mongosse.Schema({
code: {
type: String,
required: true,
},
label: {
type: String,
required: true,
},
itemCategory: {
type: mongosse.Schema.Types.ObjectId,
ref: "ItemCategory",
required: false,
},
// category: {
// type: CategorySchema,
// required: false,
// },
itemFamilly: {
type: mongosse.Schema.Types.ObjectId,
ref: "ItemFamilly",
required: false,
},
description: {
type: String,
required: false,
},
picture: {
type: String,
required: false,
},
Price: [{
type: mongosse.Schema.Types.ObjectId,
ref: "Price",
required: false,
}, ],
tempPrice: { type: Number, required: false },
active: {
type: Boolean,
required: true,
},
});
module.exports = new mongosse.model(“Item”, ItemSchema);
and I have also the methode get (route)
where I need to get my data
promotion with itemsPromotions with label of item
router.get("/config", async(req, res) => {
try {
const PromotionInDataBase = await Promotion.find().populate("item1").populate("item1.item");
res.json(PromotionInDataBase);
} catch (error) {
res.json({ message: error });
}
});
Detect pixelated images by using opencv and javascript
I’m trying to find out whether user uploaded photo is blur/pixelated. For that i’m using OpenCV4Nodejs package. It only detects blur not the pixelated one. So i found a python code to detect pixelated images but i wanted to do it in node/javascript. I tried converting it but couldn’t as i’m new to python. Can someone help me convert it. if cannot then could you please suggest is there any other way we can detect pixelated images?
Python Code:
import numpy as np
import Image, ImageChops
im = Image.open('fireworks-pixelate-02.gif')
im2 = im.transform(im.size, Image.AFFINE, (1,0,1,0,1,1))
im3 = ImageChops.subtract(im, im2)
im3 = np.asarray(im3)
im3 = np.sum(im3,axis=0)[:-1]
mean = np.mean(im3)
peak_spacing = np.diff([i for i,v in enumerate(im3) if v > mean*2])
mean_spacing = np.mean(peak_spacing)
std_spacing = np.std(peak_spacing)
print 'mean gap:', mean_spacing, 'std', std_spacing