Accessing specific values in a nested object

I have a nested object which looks like the below

{
    "Place One": {
        primary: "#000000",
        secondary: "#97233f",
        coordinates: {
            lat: 49.5013,
            lon: 87.0622
        }
    },
    "Place Two": {
        primary: "#000000",
        secondary: "#a71930",
        coordinates: {
            lat: 40.6013,
            lon: 81.0622
        }
    },
    "Place Three": {
        primary: "#9e7c0c",
        secondary: "#241773",
        coordinates: {
            lat: 40.5033,
            lon: 84.0622
        }
    }
}

I am trying to get access to each of the lat /lon variables to pass to a Leaflet React component

 <Marker
          key={park.properties.PARK_ID}
          position={[
            ***the lat***,
            ***the lon***
          ]}
        
        />

I’ve tried the below:

Object.fromEntries(
                Object.entries(teams).map(([key, { coordinates }]) => <Marker
                    position={[
                        coordinates.lat,
                        coordinates.lon
                    ]} />
                )

but cannot access the values.

can anyone please advise the best way to do this?

Styling background with ChartJs and React

I want to create a Line chart in React by using the chartJS library (‘react-chartjs-2’)

This is what I want to achieve, like background with some opacity belowe the line:

enter image description here

Code:

import React from 'react';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';
import { Line } from 'react-chartjs-2';
import faker from 'faker';

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);

export const options = {
  responsive: true,
  plugins: {
    legend: {
      position: 'top' as const,
    },
    title: {
      display: true,
      text: 'Chart.js Line Chart',
    },
  },
};

const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];

export const data = {
  labels,
  datasets: [
    {
      label: 'Dataset 1',
      data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
      borderColor: 'rgb(255, 99, 132)',
      backgroundColor: '#000000',
      fill: {
        target: 'origin',
        above: 'rgb(255, 0, 0)',   // Area will be red above the origin
        below: '#000000'    // And blue below the origin
      }
    },
    {
      label: 'Dataset 2',
      data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
      borderColor: 'rgb(53, 162, 235)',
      backgroundColor: 'rgba(53, 162, 235, 0.5)',
    },
  ],
};

export function App() {
  return <Line options={options} data={data} />;
}



Is it possible that this library doesn’t support it?

Maybe is there something that I should change?

Thanks a lot for any help

Best!

Animate box-shadow with JQuery

BoxShadow not working

$(document).ready(function () {
let r, g, b, rBorder, gBorder, bBorder, top, left;

setInterval(function () {
    r = Math.round(Math.random() * 255);
    g = Math.round(Math.random() * 255);
    b = Math.round(Math.random() * 255);
    rBorder = Math.round(Math.random() * 255);
    gBorder = Math.round(Math.random() * 255);
    bBorder = Math.round(Math.random() * 255);
    top = Math.round(Math.random() * window.innerHeight);
    left = Math.round(Math.random() * window.innerWidth);

    $('.element')
        .css({
            border: '0px solid #fff',
            boxShadow: `0px  green`
        })
        .animate({
            backgroundColor: `rgb(${r}, ${g}, ${b})`,
            borderWidth: '2px',
            borderColor: `rgb(${rBorder}, ${gBorder}, ${bBorder})`,
            boxShadow: `0px 0px 30px 0px rgb(${r}, ${g}, ${b})`,
            top: top,
            left: left
        }, 2000, 'linear');
});

});

Regex for appending special characters to an array

I am having tough time converting this scenario using regex “[“a”, “b”]” to [“a”, “b”] and [“a”, “b”] to “[“a”, “b”]”

I am able to achieve adding a double Quote before and after the brackets but couldn’t achieve the complete expectation scenario.
Any help and suggestion is much appreciated

Is it possible to use something returns from python on Node JS

I need to use JS and also i have a python script that i have to use. With print statement JavaScript can use the python output but my python function returns list and integer so print format not useful for this case. For example i wrote a python script which contains function. But this JS code work with print function.

Python Code

import sys
def function(a,b):
    variable = a+b
    return variable

function(sys.argv[1],sys.argv[2])

JS Code

const express = require('express')
const {spawn} = require('child_process');
const app = express()
const port = 3000
app.get('/', (req, res) => {
 
 var dataToSend;
 // spawn new child process to call the python script
 const python = spawn('python', ['script2.py','num' ,'python']);
 // collect data from script
 python.stdout.on('data', function (data) {
  console.log('Pipe data from python script ...');
  dataToSend = data.toString();
  console.log(dataToSend)
 });
 // in close event we are sure that stream from child process is closed
 python.on('close', (code) => {
 // send data to browser
 res.send(dataToSend)
 });
 
})
app.listen(port, () => console.log(`Example app listening on port 
${port}!`))

Is there a way that use the python function returns use on JS as arg1,arg2,arg3

how to refresh the html elements with javascript without adding the element repeatedly

I have this code

<input type="button" value="refresh" onclick="refresh()">

<div id="parent-id">
</div>

<script>
function refresh(){
 let h1 = document.createElemet("h1")
 h1.textContent = "Testing..."
 document.querySelector("#parent-id").appendChild(h1);
}
</script>

each time I click on refresh the a new h1 will be added
How can I refresh, without adding a new h1?
I have not only this element, I have a big code of 200 lines but with the same idea.
How can I refresh them without adding them again to the page ?

Component rerendering only after double click

I have a parent component that is passing products down into a subcomponent as state along with the product’s filters. For some reason I have to double click the “filters” in order for the parent component to rerender with the filtered products. I understand because it is running asynchronously it is not updating the state immediately, but how can I force the update and rerender to run as soon as I add a filter without using forceUpdate? Is this where redux would come in to play?

Parent component

    const [products, setProducts] = React.useState(data.pageContext.data);

    const handleCount = () => {
        setCount(count + 24);
    }

    return (
        <div style={{width: "100%"}}> 
        <Header/>
        <div style={{display: "flex", flexDirection: "row", justifyContent: "center"}}>
            <Sidebar 
            products={products}
            setProducts={setProducts}
            baseProducts={data.pageContext.data}
            />
            <div style={{display: "flex", flexDirection: "column"}}>
            <h1 style={{width: "50%"}}>Cast vinyl</h1>
            <h3>Product Count: {products.length}</h3>
            <ProductList>
            {products.slice(0, count).map(product => {
                return (
                    <a href={`/vinyl/${product.data.sku}`}><div>
                        {product.data.field_product_image.length > 0  ? 
                            <ProductImage images={data.data.allFiles} sku={`${product.data.sku}`}/> :
                            <StaticImage src="http://stagingsupply.htm-mbs.com/sites/default/files/default_images/drupalcommerce.png" width={250} alt=""/>}
                             <h3>{product.data.title}</h3>
                                <h5>{product.data.sku}</h5>
                    </div></a>
                    ) 
            })}
            </ProductList>
            <h3 onClick={handleCount}>Load more</h3>
            </div>
        </div>
        </div>
    )

Child Component

const Sidebar = ({ setProducts, baseProducts }) => {
    const [filters, setFilters] = React.useState([]);
    const [click, setClick] = React.useState(false);

    const handleClick = () => {
        setClick(!click);
    }

    const onChange = (e) => {
        if (!filters.includes(e)) {
            setFilters([...filters, e])
        }
        if (filters.length > 0) {
        const filteredProducts = baseProducts.filter(product => filters.includes(product.data.field_product_roll_size));
        setProducts(filteredProducts);
        }
    }

    const clearFilters = () => {
        setFilters([]);
        setProducts(baseProducts);
        setClick(false);
    }

    const rollSize = [...new Set(baseProducts.map(fields => fields.data.field_product_roll_size))]

    return (
        <SidebarContainer>
            <h3>Mbs Sign Supply</h3>
                <ul>Sub Categories</ul>
                    <a href="/vinyls/calendered_vinyl"><li>Calendered Vinyl</li></a>
                    <li>Cast Vinyl</li>
            <h3>Filters</h3>
            {filters.length > 0 ? <button onClick={clearFilters}>Clear Filters</button> : null}
            <li onClick={() => handleClick()}>Roll Size</li>
                {/*map through roll size array*/}
                {/*each size has an onclick function that filters the products array*/}
                {click ? rollSize.sort().map(size => {
                    return (
                        <span style={{display: "flex", flexDirection: "row", alignItems: "center", height: "30px"}}>
                        <Checkbox onClick={() => {onChange(size)}} />
                        <p >{size}</p>
                        </span>
                    )
                }) : null}
            <li>Width</li>

Thanks in advance

Why do I get wrong pw and username error in Expo Facebook login connected to Firebase?

I am trying to connect my Expo Facebook Login app to my Firebase profile. I managed to get Facebook login working, moreover added the config to Firebase and enabled the OAuth URL redirect.

However…
When I try to SignInWithCredentials with my token from FacebookAuthProvider, my app says that the credentials I try to log in is incorrect. I that function is checking if username and password is correct, right? Do I have to use another method?

const facebook_login = async() => {
    try {
        await Facebook.initializeAsync({
          appId: FBAPPID,
        });
        const { type, token, expirationDate, permissions, declinedPermissions } =
          await Facebook.logInWithReadPermissionsAsync({
            permissions: ['public_profile', 'email'],
          });
        if (type === 'success') {
          const credential = FacebookAuthProvider.credential(token)

          //ERROR HERE, GIVING USERNAME PW WRONG DIALOG
          const {result} = await signInWithCredentials(credential)
        } else {
          // type === 'cancel'
        }
      } catch ({ message }) {
        Alert.alert(`Hiba a Facebook bejelentkezés közben: ${message}`);
      }
}

JavaScript best way to handle/manipulate DOM elements

I have a local website which has loads of elements triggered by different actions and I was wondering if am I doing it right.

So for instance there is a button that has a function called open() and a completely empty element with an id such as “foo”.

The open() function does the following: It gets the element of id “foo” and sets its innerHTML to a bunch of elements for example creates a with few input fields in it and so on. So it relativey writes a large amount of elements in it.

Honestly I don’t think that this is the proper way to create elements inside an element and manipulate them or add custom attributes or whatever.

I also tried to create a new .html file which has the elements that I wanted to write inside the element with the id “foo” and then on the open() function it would just simply loads the .html file into the “foo” element but I’ve dropped this idea because of the various security risks.

My question is the following:
Is there any optimized and/or more professional way to create/manipulate elements without the INNERHTML or the .HTML() method?

The basics of the code that I tried to explain:

const element = document.getElementById(‘foo’);

function open() {
   element.innerHTML = ‘a bunch of html elements that I dont want to list here’;
}

The second method that I tried:

const element = document.getElementById(‘foo’);

function open(){
   element.html(htmlelements.html);
}

The htmlelements.html contains a bunch of DOM elements.

Mongoose text search is not returning the correct result

I’m making a recipe blog website using mongoose, nodejs and express. I am making a search form, but the text search not giving the correct output.

In Recipe.js schema I added the following parameters, that in which values I want to search, I’m added the following ones: recipeSchema.index({ name: 'text', description: 'text', ingredients: 'text', categoryByNationality: 'text', categoryByServing: 'text'});

When I started this project, i had only recipeSchema.index({ name: 'text', description: 'text',}); and it’s worked, but after a few months later I added the ingredients, categoryByNationality and categoryByServing and when I search for category, not finding any recipe. If I search for name and description, its working fine. When I delete all this recipeSchema.index({.......}) code, working with the name and with description again.

What is causing this problem, any idea?

Controller.js

exports.searchRecipe = async(req, res) => {

    //searchTerm
    try {
        let searchTerm = req.body.searchTerm;
        let recipe = await Recipe.find({ $text: { $search: searchTerm, $diacriticSensitive: true } });
        res.render('search', { title: 'Cooking Blog - Search', recipe });
    } catch (error) {
        res.status(500).send({message: error.message || "Error Occured"});
    }
}

Recipe schema

const mongoose = require('mongoose');

const recipeSchema = new mongoose.Schema({
    name: {
        type: String,
        required: 'This field is required.'
    },
    description: {
        type: String,
        required: 'This field is required.'
    },
    servings: {
        type: Number,
        required: 'This field is required.'
    },
    quantity: {
        type: Array,
        required: 'This field is required.'
    },
    ingredients: {
        type: Array,
        required: 'This field is required.'
    },
    categoryByServing: {
        type: String,
        enum: ['Reggeli', 'Ebéd', 'Vacsora', 'Desszert', 'Levesek', 'Egyéb'],
        required: 'This field is required.'
    },
    categoryByNationality: {
        type: String,
        enum: ['Thai', 'Kínai', 'Indiai', 'Olasz', 'Angol', 'Magyar', 'Egyéb'],
        required: 'This field is required.'
    },
    image: {
        type: Array,
        required: 'This field is required.'
    },
    comments: [
        {
            username: String,           
            comment: String,          
            date: {
                type: Date,
                default: Date.now
            },           
            rating: Number,
        },{
            timestamps: true
        }
    ],
    count: {
        type: Number
    },
    likes: {
        type: Number
    },
    ratingAvg: {
        type: Number
    },
    recipe_id: {
        type: String
    }

});

recipeSchema.index({ name: 'text', description: 'text', ingredients: 'text', categoryByNationality: 'text', categoryByServing: 'text'});


module.exports = mongoose.model('Recipe', recipeSchema);

search.ejs

<h1 class="pb-4">Search result</h1>

<div class="row row-cols-2 row-cols-lg-5 g-2 g-lg-3">
    <% if(typeof recipe !== 'undefined' && recipe.length > 0) { %>
      <% recipe.forEach(function(recipe, index){ %>
      <a href="/recipe/<%= recipe._id %>" class="col text-center category_link">
        <div class="category_img category__img--large shadow">
          <img src="/uploads/<%= recipe.image %>" alt="<%= recipe.name %>" loading="lazy">
        </div>
        <div class="pt-1"><%= recipe.name %></div>
      </a>
      <% }) %>
    <% } else { %>
      <p>Cant find any recipe</p>
    <% } %>
</div>

Sample data for Recipe database

{
    "_id": {
        "$oid": "6228ce14b72c51796e00b8ce"
    },
    "name": "Test recipe",
    "description": "test test test",
    "servings": {
        "$numberInt": "6"
    },
    "quantity": ["12", "20", "2"],
    "ingredients": ["l water", "g salt", "l milk"],
    "categoryByServing": "Ebéd",
    "categoryByNationality": "Indiai",
    "image": ["1646744388278274327802_7801262463232661_4968108751943235625_n.jpg"],
    "comments": [{
        "username": "First username",
        "comment": "First comment",
        "rating": {
            "$numberInt": "5"
        },
        "_id": {
            "$oid": "622753706aff227ef4b4460a"
        },
        "date": {
            "$date": {
                "$numberLong": "1646744433049"
            }
        }
    }, {
        "username": "Second username",
        "comment": "Second comment",
        "rating": {
            "$numberInt": "4"
        },
        "_id": {
            "$oid": "6227537e6aff227ef4b44615"
        },
        "date": {
            "$date": {
                "$numberLong": "1646744446326"
            }
        }
    }, {
        "username": "Third username",
        "comment": "Third comment",
        "rating": {
            "$numberInt": "3"
        },
        "_id": {
            "$oid": "622753896aff227ef4b44622"
        },
        "date": {
            "$date": {
                "$numberLong": "1646744458103"
            }
        }
    }, {
        "username": "Fourth username",
        "comment": "Fourth comment",
        "rating": {
            "$numberInt": "2"
        },
        "_id": {
            "$oid": "6227539e6aff227ef4b44631"
        },
        "date": {
            "$date": {
                "$numberLong": "1646744478781"
            }
        }
    }, {
        "username": "Fifth username",
        "comment": "Fifth comment",
        "rating": {
            "$numberInt": "1"
        },
        "_id": {
            "$oid": "622753a86aff227ef4b44642"
        },
        "date": {
            "$date": {
                "$numberLong": "1646744489088"
            }
        }
    }, {
        "username": "25",
        "comment": "gasss",
        "rating": {
            "$numberInt": "3"
        },
        "_id": {
            "$oid": "622796829f8062416492dcfd"
        },
        "date": {
            "$date": {
                "$numberLong": "1646761603076"
            }
        }
    }],
    "count": {
        "$numberInt": "120"
    },
    "likes": {
        "$numberInt": "0"
    },
    "ratingAvg": {
        "$numberDouble": "3.0"
    },
    "__v": {
        "$numberInt": "6"
    }
}

i want to upload an image and display it on my html page with js

i want to load a picture form input type image and desplay it on my html page or at least get the path of that image

 <script>
function AddImg()
        {   
            const img = document.getElementById("image").value;
            console.log(text);
            var myImage = new Image(100, 200);
            myImage.src =img ;
            document.body.appendChild(myImage);
        }
</script>
<input type="file" accept="image/*" value="Add Images" style="margin-top: 30px;" id="image">
            <button onclick="AddImg();">Add image</button>