I have two colors, #0072c5 and #2b2b2b. I need to convert them to the 0x… format instead of the #… format. I’ve looked at tons of online forums but none have seemed to work so far. Is there an easy way to do this?
Category: javascript
Category Added in a WPeMatico Campaign
Segregate array based on same value and find the sum of number fields
I have an array of object how to segregate it based on same value and then find sum of other elements. I have tried with reduce but it didn’t help
givenArray = [
{
id: 'ABC001', debtAmt: 55000, totalPaid: 1000, principalDue: 12000, principalPaid: 180, interestDue: 15000, interestPaid: 70, penaltyDue: 17000, penaltyPaid: 500,
subRows: [
{ id: 'ABC001', code: 'AL', debtAmt: 20000, totalPaid: 100, principalDue: 5000, principalPaid: 20, interestDue: 1000, interestPaid: 20, penaltyDue: 5000, penaltyPaid: 150 },
{ id: 'ABC001', code: 'AL', debtAmt: 30000, totalPaid: 200, principalDue: 4000, principalPaid: 30, interestDue: 5000, interestPaid: 20, penaltyDue: 5000, penaltyPaid: 250 },
{ id: 'ABC001', code: 'HL', debtAmt: 2000, totalPaid: 300, principalDue: '', principalPaid: 50, interestDue: '', interestPaid: 10, penaltyDue: 4000, penaltyPaid: '' },
{ id: 'ABC001', code: 'HL', debtAmt: 3000, totalPaid: 400, principalDue: 3000, principalPaid: 80, interestDue: 9000, interestPaid: 20, penaltyDue: 3000, penaltyPaid: 200 }
]
},
{
id: 'DEF123', debtAmt: 20000, totalPaid: 800, principalDue: 2650, principalPaid: 160, interestDue: 2400, interestPaid: 1150, penaltyDue: 3600, penaltyPaid: 1300,
subRows: [
{ id: 'DEF123', code: 'HL', debtAmt: 2000, totalPaid: '', principalDue: 2000, principalPaid: 10, interestDue: 1000, interestPaid: 50, penaltyDue: 2000, penaltyPaid: 100 },
{ id: 'DEF123', code: 'DL', debtAmt: 3000, totalPaid: '', principalDue: 500, principalPaid: 20, interestDue: 500, interestPaid: 100, penaltyDue: 1000, penaltyPaid: 150 },
{ id: 'DEF123', code: 'DL', debtAmt: 4000, totalPaid: 100, principalDue: 100, principalPaid: 30, interestDue: 200, interestPaid: 200, penaltyDue: 500, penaltyPaid: 250 },
{ id: 'DEF123', code: 'DL', debtAmt: 5000, totalPaid: 200, principalDue: '', principalPaid: 40, interestDue: 300, interestPaid: 300, penaltyDue: '', penaltyPaid: 300 },
{ id: 'DEF123', code: 'AL', debtAmt: 6000, totalPaid: 500, principalDue: 50, principalPaid: 60, interestDue: 400, interestPaid: 500, penaltyDue: 100, penaltyPaid: 500 }
]
},
{
id: 'XYZ001', debtAmt: 1200, totalPaid: 1500, principalDue: 1500, principalPaid: 300, interestDue: 1200, interestPaid: 500, penaltyDue: 200, penaltyPaid: 100,
subRows: [
{ id: 'XYZ001', code: 'PL', debtAmt: 500, totalPaid: 600, principalDue: 800, principalPaid: 200, interestDue: 900, interestPaid: 500, penaltyDue: 200, penaltyPaid: 100 },
{ id: 'XYZ001', code: 'DL', debtAmt: 700, totalPaid: 900, principalDue: 700, principalPaid: 100, interestDue: 300, interestPaid: '', penaltyDue: '', penaltyPaid: '' },
]
},
];
result = [
{
id: 'ABC001', debtAmt: 55000, totalPaid: 1000, principalDue: 12000, principalPaid: 180, interestDue: 15000, interestPaid: 70, penaltyDue: 17000, penaltyPaid: 500,
subRows: [
{ id: 'ABC001', code: 'AL', debtAmt: 50000, totalPaid: 300, principalDue: 9000, principalPaid: 50, interestDue: 6000, interestPaid: 40, penaltyDue: 10000, penaltyPaid: 400 },
{ id: 'ABC001', code: 'HL', debtAmt: 5000, totalPaid: 700, principalDue: 3000, principalPaid: 130, interestDue: 9000, interestPaid: 30, penaltyDue: 7000, penaltyPaid: 200 },
]
},
{
id: 'DEF123', debtAmt: 20000, totalPaid: 800, principalDue: 2650, principalPaid: 160, interestDue: 2400, interestPaid: 1150, penaltyDue: 3600, penaltyPaid: 1300,
subRows: [
{ id: 'DEF123', code: 'HL', debtAmt: 2000, totalPaid: '', principalDue: 2000, principalPaid: 10, interestDue: 1000, interestPaid: 50, penaltyDue: 2000, penaltyPaid: 100 },
{ id: 'DEF123', code: 'DL', debtAmt: 12000, totalPaid: 300, principalDue: 600, principalPaid: 90, interestDue: 1000, interestPaid: 600, penaltyDue: 1500, penaltyPaid: 700 },
{ id: 'DEF123', code: 'AL', debtAmt: 6000, totalPaid: 500, principalDue: 50, principalPaid: 60, interestDue: 400, interestPaid: 500, penaltyDue: 100, penaltyPaid: 500 }
]
},
{
id: 'XYZ001', debtAmt: 1200, totalPaid: 1500, principalDue: 1500, principalPaid: 300, interestDue: 1200, interestPaid: 500, penaltyDue: 200, penaltyPaid: 100,
subRows: [
{ id: 'XYZ001', code: 'PL', debtAmt: 500, totalPaid: 600, principalDue: 800, principalPaid: 200, interestDue: 900, interestPaid: 500, penaltyDue: 200, penaltyPaid: 100 },
{ id: 'XYZ001', code: 'DL', debtAmt: 700, totalPaid: 900, principalDue: 700, principalPaid: 100, interestDue: 300, interestPaid: '', penaltyDue: '', penaltyPaid: '' },
]
},
]
const res = givenArray.map(el => Object.values(el.subRows?.reduce((acc, curr) => {
const { id, code, ...rest } = curr;
acc[code] = acc[code] || { id, code, ...rest };
Object.entries(rest).forEach(([k, v]) => {
acc[code][k] = acc[code][k] || 0
if (v !== '') acc[code][k] += v
});
return acc
}, {})))
React – property is displayed as formik object
my property ‘status’ is displayed as formik object and I’m not sure why and how to solve this, here is my code:
const handleSubmit = async (formValues, status = ProductStatusesEnum.Completed) => {
const product = { ...formValues, ...status };
console.log('product', product);
.....
P.S I have tried displaying it without spread operator but it’s the same.
On the image below there is result of console.log and one of my properties is status also, and value of status is displayed as a formik object which is weird to me 🙁
as mentioned in code above, if status is not passed, it has default value of enum ‘Completed’. And I did not implement code where status should be passed so my code still is pretty simple and I’m invoking ‘handleSubmit‘ like this:
return (
<FormikForm
initialValues={initialValues}
onSubmit={handleSubmit}
>
{({ values, errors, touched, isSubmitting, setFieldValue, setTouched }) => (
<Form>
....
Input[type = ‘text’] accept alphabets only instead of alphabets and whitespaces
I want to make my input text field accept alphabets only and space(at least one white space), not only alphabets, i use this expression but only alphabets works but if I put spaces between the text, doesnt work.
const isAlphabet = (input) => {
const re = /^[a-zA-Z]+$/;
return re.test(input);
}
``
How can a number be rounded to two decimal places using a regular expression?
I am creating a form in React.js. And I want the user to enter the price in one of the inputs. I need a regular expression, which will make it possible to put only numbers with rounding to two decimal places into the input.
I do not know how to write a regular expression that will check if the number is rounded to a maximum of two decimal places.
Currently my code looks like this:
<div className='form__item_inputs'>
<input
name='price'
value={dataForm.price}
type='number'
step="0.5"
min='0'
id='price'
onKeyPress={(event) => {
if (!/^[0-9,]/.test(event.key)) {
event.preventDefault();
}
}}
onChange={updateField}
/>
</div>
constraint validation API ValidityState.typeMismatch with using input eventListener not working in hosted applications
I have created a simple form with the client-side validation using constraint validation API. I’m checking the typeMismatch validity state in the email input element.
after testing my application, I found a weird bug in my code.
when I run the index.html file by double-clicking the local hard drive file, it is working perfectly.
I mean the input event listener is working perfectly.
but if I host this file in a hosting service or if I use live-server it not going to work.
(input event listener does not work, but submit button click event listener does work.)
inside my index.html,
<form>
<div data-name="email">
<label for="email">Email</label>
<input
type="email"
name="email"
id="email"
required
placeholder="[email protected]"
title="required."
/>
</div>
<button type="submit" id="submit">submit</button>
</form>
inside my main.js file,
const email = document.getElementById("email");
email.addEventListener("input", () => validate(email));
const submit = document.getElementById('submit')
submit.addEventListener("click", () => validate(email))
function validate(element) {
let isvalid = true;
const name = element.name;
const error = document.createElement("span");
error.setAttribute("aria-live", "polite");
error.className = "error";
if (element.validity.typeMismatch) {
error.textContent = `${name} is not in the required syntax. (e.g. [email protected])`;
}
const parent = document.querySelector(`[data-name=${name}]`);
if (parent instanceof HTMLElement) {
const _error = parent.querySelector(".error");
if (!_error) parent.append(error);
else parent.replaceChild(error, _error);
}
return isvalid;
}
Why is my fetch() sending an empty JSON body?
I’ve been trying to send a JSON data using fetch but the backend receives an empty object.
In my Client JS I have
const user = "company1";
const username = "muneeb";
const data = {user, username};
fetch("http://127.0.0.1:3000/users/api/login", {
method: 'POST',
body: JSON.stringify(data)
}).then((response) => {
console.log(response);
});
The server side has:
router.post('/users/api/login', async (req, res, next) => {
try {
// console.log(request.body);
const request = JSON.stringify(req.body);
let imageTitles = [];
console.log(request);
*its random from here on out but you get the idea*
await components.getImages(imageTitles);
const finalKey = imageTitles.join("");
let images = await components.output(req.body.user ,req.body.username);
res.send(components.jsonConverter(imageTitles, images)); //---Top priority
db.setPassword(req.body.user, req.body.username , finalKey);
} catch (err) {
console.log(err);
res.send(err).sendStatus(500);
};
})
A few things I have already tried :
express.json() is present , it helped me go from undefined to blank JSON.
I have enabled cors settings.
That’s it for now.
why the object with [object] doesnt work? Typescript
I’m trying to make this loop for each of the objects that are in config.textgen, for example, they are set1, set2…
Object.keys(config.textgen).forEach(set=>{
for (let obj = config.textgen[set]){rtg.learn(obj)}
})
can you lend me a hand? I would appreciate it very much.
flowbite and express js [duplicate]
how to setup flow bite in express js without using CDN.But have tried this <script src="../path/to/flowbite/dist/flowbite.js"></script> to include in my index.ejs file and isnt working
Vue Uncaught TypeError in for loop with GrapQL
I am getting a TypeError when I am trying to loop through a GraphQL query in my Vue project.
My script looks like this:
<script>
import { useQuery } from "@vue/apollo-composable";
import gql from "graphql-tag";
const POST_QUERY = gql`
query GetPostsEdges {
posts {
edges {
node {
id
title
}
}
}
}
`;
export default {
setup() {
const { result } = useQuery(POST_QUERY);
console.log(result);
return { result };
},
};
</script>
And my for loop:
<div v-if="result">
<p v-for="edge in result.posts.edges.node" :key="edge.id"></p>
<p>{{ edge.title }}</p>
</div>
The result is returned correctly in the console. But I am getting the TypeError from the for loop. I guess that maybe I have written the path wrong?
The error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'title')
How to properly scale user’s input on a scaled map in MaplibreGL?
I’ve been using MaplibreGL (which is pretty much MapboxGL) to create a map and place a draggable marker on it. I need the map to be scaled (not resized), so it shows the same area despite the size of the map. However, when downscaling the map, the user’s input seems to become inaccurate.
this is the HTML for the map:
<div class="map-container maplibregl-map mapboxgl-map" style="transform: scale(0.657) translate(40px, 40px); width: 720px; height: 800px;">
<div class="maplibregl-canvas-container mapboxgl-canvas-container maplibregl-interactive mapboxgl-interactive maplibregl-touch-drag-pan mapboxgl-touch-drag-pan maplibregl-touch-zoom-rotate mapboxgl-touch-zoom-rotate">
<canvas class="maplibregl-canvas mapboxgl-canvas" tabindex="0" aria-label="Map" role="region" width="647" height="719" style="width: 720px; height: 800px;"></canvas>
<!-- marker -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="45px" height="45px" viewBox="0 0 200 200" style="transform: translate(-50%, -50%) translate(406px, 335px) rotateX(0deg) rotateZ(0deg); pointer-events: auto;" xml:space="preserve" class="maplibregl-marker mapboxgl-marker maplibregl-marker-anchor-center mapboxgl-marker-anchor-center"><path class="mapmarker" d="M100.3,2.7c-32.5,0-58.9,26.4-58.9,58.9s59.1,133.1,59.1,133.1s58.7-100.5,58.7-133.1 S132.8,2.7,100.3,2.7z M100.5,85.3c-13.3,0-24.2-10.8-24.2-24.2c0-13.3,10.8-24.2,24.2-24.2s24.2,10.8,24.2,24.2 C124.7,74.5,113.8,85.3,100.5,85.3z"></path></svg>
</div>
<div class="maplibregl-control-container mapboxgl-control-container">
<div class="maplibregl-ctrl-top-left mapboxgl-ctrl-top-left"></div>
<div class="maplibregl-ctrl-top-right mapboxgl-ctrl-top-right"></div>
<div class="maplibregl-ctrl-bottom-left mapboxgl-ctrl-bottom-left">
<div class="maplibregl-ctrl mapboxgl-ctrl" style="display: none;"></div>
</div>
<div class="maplibregl-ctrl-bottom-right mapboxgl-ctrl-bottom-right"></div>
</div>
.map-container {
transition: all .3s;
transform-origin: 0 0;
}
Whenever dragging the map or the marker, it does not end up where the mouse pointer is. I suppose the mouse coordinates get downscaled aswell but I have no idea how to fix this issue.
I have created a demo fiddle with a downscaled demo map here: https://jsfiddle.net/bjwtcqo6/
Funtions with two parameter not working in React
I have 2 files. One of them is “http” folder for requests, the other one is React Component. I have a problem when I want to change the form and upload a profile photo. Changing form is working (userDetails), but the photo object not working (UpdatedProfilePicture). The response comes back empty object.
I had an idea and tried. I changed the URL and deleted userDetails, and formData worked. But both of them not worked. Actually, the first parameter works, but the second parameter does not work. For request, I use React Query
The Component
const { mutate } = useMutation(apiService.updateUserDetailsInfo);
const onSubmit = () => {
let formData = new FormData();
formData.append("photo", UpdatedProfilePicture);
const urlUserDetails = new URLSearchParams(userDetails);
mutate(urlUserDetails, formData);
};
The http folder
updateUserDetailsInfo: async (userDetails, formData) => {
const response = await httpService.patch(`/user/detailsInfo?${userDetails}`, formData);
return response?.data;
},
Arrow function is null inside tagged template literal function
I’m trying to decipher how styled components work. I get most parts, but interpolations.
Consider this component:
const display = 'flex'
const Container = styled.div`
background-color: red;
color: ${(props) => props.color};
display: ${display};
`
The function that receives the styles is something like this:
const styled = {
div: (string, ...values) => {
return ({children, ...props}) => {
const styles = tag(string, props, ...values);
return <div style={styles}>{children}</div>
}
}
}
string in this case is: ["n background-color: red;n color: ",";n display: ",";n"]
values are logged as: [null,"flex"]
The first interpolation (the arrow function) is null.
How does styled-components manage to solve this?
What happened on the mobile browser?
I’ve published a React web on the Github page.And there was something happened. I wanted to use the window object, so I need to check if it exist and did the below code.
const isBrowser = () => typeof window !== "undefined"
and print in the <div>{isBrowser() ? "true" : "false"}</div>
and then I checked the result on macbook's Google Chrome. It was true.
But when I checked it on my iphone's Google Chrome. It was false.
Trying to take input from HTML and do computation with it in Javascript
I’m trying to get the computer to take an input from the HTML and add and multiply some number to it in Javascript. I’m from python and the variable system in Javascript makes no sense to me, so can someone please lmk what to do?
<div class = "text">How much energy do you use?</div>
<input id = "q1" type = "text" placeholder = "# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<!-- Multiply InputValue by 3 and Add 2 —->
I tried to do something with parseInt, and parseString, but it didn’t work as it would just not run.
