Display & Hide a Navbar submenu

I’m trying to make a navbar with a submenu for each link. The easiest way to do this that I found is to write some Javascript that when the link is clicked changes the classes of the submenu (from display none to display block). I tried to write the script but it doesn’t work at all. I can’t find out where the problem is.

const SM_prossimieventi = () => {
  const sottomenu = document.querySelector('.prossimieventi_items');
  const linkpe = document.querySelector('.prossimieventi_a');
  linkpe.addEventListener('click', () => {
    sottomenu.classList.toggle('.pe-active');
  });
};

SM_prossimieventi();
        <nav class="main-nav">
            <ul class="main-nav_items">
                <li class="main-nav_item"> <a href="" class="main-nav_item_a home_a">HOME</a></li>
                <li class="main-nav_item"> <a href="" class="main-nav_item_a prossimieventi_a">PROSSIMI EVENTI</a></a>
                    <ul class="prossimieventi_items">
                        <li class="prossimieventi_item"><a href="">GIORNATA ECOLOGICA</a></li>
                        <li class="prossimieventi_item"><a href="">CONCORSO FOTOGRAFICO</a></li>
                        <li class="prossimieventi_item"><a href="">LOTTERIA</a></li>
                        <li class="prossimieventi_item"><a href="">FESTA ASSUNTA</a></li>
                    </ul>
                </li>

                <li class="main-nav_item"> <a href="" class="main-nav_item_a mappainterattiva_a">MAPPA INTERATTIVA</a>
                    <ul class="mappainterattiva_items">
                        <li class="mappainterattiva_item"><a href="">COSA VISITARE</a></li>
                        <li class="mappainterattiva_item"><a href="">DOVE MANGIARE</a></li>
                        <li class="mappainterattiva_item"><a href="">DOVE DORMIRE</a></li>
                    </ul>
                </li>
                <li class="main-nav_item"> <a href="" class="main-nav_item_a attivitàsulterritorio_a">ATTIVITA' SUL
                        TERRITORIO</a> </a>
                    <ul class="attivitàsulterritorio_items">
                        <li class="attivitàsulterritorio_item"><a href="">FERRAGOSTO</a></li>
                        <li class="attivitàsulterritorio_item"><a href="">IL NATALE</a></li>
                        <li class="attivitàsulterritorio_item"><a href="">PROGETTO AIUOLE</a></li>
                        <li class="attivitàsulterritorio_item"><a href="">BLOG</a></li>
                        <li class="attivitàsulterritorio_item"><a href="">DONAZIONI</a></li>
                    </ul>
                </li>
                <li class="main-nav_item"><a href="" class="main-nav_item_a chisiamo_a">CHI SIAMO</a></a>
                    <ul class="chisiamo_items">
                        <li class="chisiamo_item"><a href="">LA STORIA</a></li>
                        <li class="chisiamo_item"><a href="">CONTATTACI</a></li>
                        <li class="chisiamo_item"><a href="">BILANCIO</a></li>
                    </ul>
                </li>
            </ul>
        </nav>
.mappainterattiva_items,
.prossimieventi_items,
.attivitàsulterritorio_items,
.chisiamo_items {
  position: absolute;
  list-style: none;
  padding: 1rem;
  margin: 1rem 0rem 0rem 1rem;
  background: #1679a7;
  font-size: 14px;
  line-height: 25px;
  letter-spacing: 0.1em;
  font-weight: 275;
  width: max-content;
  display: none;
}
.main-nav_item {
  position: relative;
}
.mappainterattiva_item a,
.prossimieventi_item a,
.attivitàsulterritorio_item a,
.chisiamo_item a {
  text-decoration: none;
}
.mappainterattiva_item a:hover,
.prossimieventi_item a:hover,
.attivitàsulterritorio_item a:hover,
.chisiamo_item a:hover {
  text-decoration: none;
  color: #cccc32;
}

.pe-active{
  display: block;
}

Keep parent loading whilst react query in child component is loading

I have a parent component in my react app that makes a call to our api, and the page has a loader whilst its waiting for response. On response, I loop through the data, and I pass each iteration into a child component, that then makes another request based on that data.

Is there a way to keep the parent spinner going, until the child data is loaded?

Currently, it displays the parent, then a split second later, some data attached to the child pops in and its not great for the user.

I am using reactQuery for my api calls.

Multiply specific object in array

I have an array of objects. I want to multiply GDPAnn by 10**6.

var Annual = [{"Date":1998,"Value":4.5,"GDPAnn":9062800},{"Date":1999,"Value":4.8,"GDPAnn":9631200},{"Date":2000,"Value":4.1,"GDPAnn":10251000},{"Date":2001,"Value":1,"GDPAnn":10581900}]

The code below returns only transformed GDPAnn. I want the similar array as above within transformed values of GDPAnn.

Annual.map((o) => o.GDPAnn * 10**6)

Laravel 8 and Vue 3 dropdown toggle not toggling or working, is there a way to fix?

I have a toggle to show a dropdown list to logout, unfortunately the toggle does not let me to show the dropdown list.

I have already npm install && npm run dev but nothing works, tried using CDN still getting the same problem. Is there a way to fix this?

Package also included alpinejs in the app.js file

        <!-- Settings Dropdown -->
        <div class="hidden sm:flex sm:items-center sm:ml-6">
            <x-dropdown align="right" width="48">
                <x-slot name="trigger">
                    <button class="flex items-center text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300 focus:outline-none focus:text-gray-700 focus:border-gray-300 transition duration-150 ease-in-out">
                        <div>{{ Auth::user()->name }}</div>

                        <div class="ml-1">
                            <svg class="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                            </svg>
                        </div>
                    </button>
                </x-slot>

                <x-slot name="content">
                    <!-- Authentication -->
                    <form method="POST" action="{{ route('logout') }}">
                        @csrf

                        <x-dropdown-link :href="route('logout')"
                                onclick="event.preventDefault();
                                            this.closest('form').submit();">
                            {{ __('Log Out') }}
                        </x-dropdown-link>
                    </form>
                </x-slot>
            </x-dropdown>
        </div>

Why when i have || condition i do not need to include 1 and -1 numbers in sorting? [duplicate]

i have this array

var arr = [
    {
        name:'Andrej',
        price:5
    },
    {
        name:'Andrej',
        price: 12
    },
    {
        name:'Don',
        price: 12
    },
    {
        name:'Andrej',
        price: 2
    },
    {
        name:'Cilia',
        price: 40
    },
    {
        name:'Andrej',
        price: 10
    },
]

so if i want to sort this array by name i will do


var sorted = arr.sort((a,b) => {
    return a.name > b.name ? 1 : -1;
})


and now i have th e array sorted by name

if i try


var sorted = arr.sort((a,b) => {
    return a.name > b.name;
})

it will not work. It needs 1 and -1 as numbers so the sort function will know how to swap the values.

If i need to sort the array by name and price and i try

var sorted = arr.sort((a,b) => {
    return a.name > b.name  || a.price - b.price;
})

now my array is sorted by name and price
Why in this case the shortcut works a.name > b.name but in previous case
when i had just the name it does not work

LeafletJS Custom properties in feature collection

I am using Angular and Leaflet and I am adding a marker to a map every click:

Extract of relevant code:

  this.map = L.map('map', {
  crs: L.CRS.Simple,
  maxZoom: 3,
  minZoom: -1
})

L.imageOverlay(img, [[50, 50], [h, w]]).addTo(this.map);

this.map.fitBounds([[50, 50], [h, w]]);

this.drawnItems = L.featureGroup().addTo(this.map);

const onMapClick = (e: any) => {
  const marker = L.marker(e.latlng, {
    icon: this.markerStyle
  });
  
  marker.bindPopup(this.popupService.makeFormPopup(), {
    keepInView: true,
    closeButton: false,
    minWidth: 300
  })
marker.addTo(this.drawnItems).openPopup();

The marker collection (this.drawnItems) is later turned to geoJSON using:

const data = this.drawnItems.toGeoJSON();

in data it looks like:

{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"properties":{},"geometry":{"type":"Point","coordinates":[796,910.126465]}}}]}

I would like to populate the properties object with a value from the popup box, I can get the value fine but how would I set it inside that specific marker?
I have tried:

    if (!e.target.feature) {
      e.target.feature = [];
      e.target.feature.properties = {};// add blank property to marker then add key/pair
    }

But this code adds the properties to the geometry rather than the properties and makes the geoJSON invalid.

thanks

D3.js numbers spirally outwards from inner wheel

I worked in the d3 library and created nested wheels. I have no idea how to add texts into the wheel, spirally from inside out. The number starting point doesn’t matter, and numbers must spirally outwards according the previous position.

Codes

let allAxis = (data.map(function(i, j) {
    return i.name
  })),
  total = allAxis.length,
  radius = Math.min(options.width / 2, options.height / 2),
  angleSlice = Math.PI * 2 / total,
  Format = d3.format('');

let rScale = d3.scale.linear()
  .domain([0, options.circles.maxValue])
  .range([50, radius]);

let svg = d3.select("body").append("svg")
  .attr("width", options.width + options.margins.left + options.margins.right)
  .attr("height", options.height + options.margins.top + options.margins.bottom);

let g = svg.append("g")
  .attr("transform", "translate(" + (options.width / 2 + options.margins.left) + "," + (options.height / 2 + options.margins.top) + ")");

let axisGrid = g.append("g")
  .attr("class", "axisWraper");

let axis = axisGrid.selectAll(".axis")
  .data(allAxis)
  .enter()
  .append("g")
  .attr("class", "axis")

//append them lines
axis.append("line")
  .attr("x1", 0)
  .attr("y1", 0)
  .attr("x2", function(d, i) {
    let tempX2 = radius * Math.cos(angleSlice * i - Math.PI / 2);
    return tempX2;
  })
  .attr("y2", function(d, i) {

    let tempY = radius * Math.sin(angleSlice * i - Math.PI / 2);
    return tempY;
  })
  .attr("class", "line")
  .attr("stroke", "black")
  .attr("fill", "none");

//Draw background circles
axisGrid.selectAll(".levels")
  .data([12,11,10,9,8,7,6, 5, 4, 3, 2, 1])
  .enter()
  .append("circle")
  .attr("class", function(d, i) {
    return `gridCircle-${d}`
  })
  .attr("r", function(d, i) {
    return parseInt(radius / options.circles.levels * d, 10);
  })
  .attr("stroke", "black")
  .attr("fill-opacity", function(d, i) {
    return options.circles.opacity;
  });

axisGrid.select(".gridCircle-1").attr("fill-opacity", 1);
axisGrid.select(".gridCircle-2").attr("fill-opacity", 1);

Here’s the fiddle: https://jsfiddle.net/arcanabliss/8uy3nbet


Expected Result

Nested Spirally Number Wheel

web app on load Content Security Policy issue

I m facing this issue on load in my angular app

Refused to load the font ‘http://localhost:8100/Roboto-Regular.ttf’ because it violates the following Content Security Policy directive: “default-src ‘none'”. Note that ‘font-src’ was not explicitly set, so ‘default-src’ is used as a fallback.

localhost/:1 Failed to load resource: the server responded with a status of 404 (Not Found)enter image description here

Discord.js V13 Set Button Cooldown

I recently made my ticket bot, but I need to add a cooldown to the “close ticket” button to prevent someone from flooding the button and sending multiple messages, I haven’t found any possible way to do that. how would i add a cooldown on a specific button?

My button code:

      const row = new client.discord.MessageActionRow()
        .addComponents(
          new client.discord.MessageButton()
          .setCustomId('confirm-close')
          .setLabel('Fechar o Ticket')
          .setStyle('DANGER'),
          new client.discord.MessageButton()
          .setCustomId('no')
          .setLabel('Cancelar Fechamento')
          .setStyle('SECONDARY'),
        );

        const verif = await interaction.reply({
          content: 'Tem certeza de que deseja fechar o ticket?',
          components: [row]
        });

For user identification, I’m using interaction.user.id

How to change css property in react

I want to change css width property of my element on some condition

<div className="consoleLayoutRoot-sideMenu">
        <ConsoleSideMenu />
 </div>

css

.consoleLayoutRoot-sideMenu .ant-menu {
  padding-top: 30px;
  height: 100%;
  width: 50px;
  /* background-color: #191146 !important; */
}

I am doing this way..but nothing is happening

document.getElementsByClassName("consoleLayoutRoot-sideMenu.ant-menu ").style.width = "50px";

alternating .setFontSize() inside of an array

Im not really a programmer so please excuse the slightly crude description. This is an expression for a textlayer in Adobe After Effects (which uses Javascript)

I currently use this expression to generate an array of values (which is later used as customizable labels for the axes of a graph)

x = 0 //starting point (the first number in the list)
y= 20 //increments (the size of the steps)
z= 5 //the number of steps

Array.from(new Array(z)).map((_, i) => i * y + x + "km").join("n")

which outputs

0km
20km
40km
60km
80km

Then I thought it would also be good to have miles in there so I changed the code to this

Array.from(new Array(z)).map((_, i) => i * y + x + "km " + (i * y + x) * 0.6 +"mi").join("n")

I suppose its not beautiful but it does the job …

0km 0mi
20km 12mi
40km 24mi
60km 36mi
80km 48mi

I then tried to add a customizable fontsize. Thats how I did it.

text.sourceText.style.setText
(
Array.from(new Array(z)).map((_, i) => i * y + x + "km " + (i * y + x) * 0.6 +"mi").join("n")
)
.setFontSize(20)

This worked, but really I only want a different font size for the miles value and this is where I ran into trouble. I tried

Array.from(new Array(z)).map((_, i) => i * y + x + "km " + text.sourceText.style.setText((i * y + x) * 0.6 +"mi").setFontSize(10)).join("n")

but this somehow only outputs

0km [object Object]
20km [object Object]
40km [object Object]
60km [object Object]
80km [object Object]

any ideas? Thanks in advance

Array of Objects useState in React Typescript losing the first array element when triggering onChange on second array element

I have the following piece of code which is a snippet of the entire thing. Basically I am trying to have a form, with the option of creating multiple entries of the same form on a button click. The aim is to store the data in an array of objects where each object represents one form.

The problem is that, although I am managing to create the second entry in the state that is defined in the parent component, when I try to enter text in the 2nd entry with onChange, the 1st entry is removed.

My guess is that I am doing something wrong in the logic of how I am trying to save the key events, but I cannot pinpoint it.

Parent Component

export interface IExperience {
    position: string,
    location: string, 
    startDate: string,
    endDate: string,
    description: string
}

const Experience = () => {
    let [preview,setPreview] = useState(false)
    let [data,setData] = useState<IExperience[]>([{position: '', location: '', startDate: '', endDate: '', description: ''}]) // Default state is not undefined
    let [button,setButton] = useState('Edit')

    return (
        <div className={styles.visitorContainer}>
            <Nav />
            {preview ? <Message setPreview={setPreview} data={data} setData={setData} /> : <Preview setPreview={setPreview} data={data} setData={setData} button={button} setButton={setButton}/>}
            <Foot />
        </div>
    )
}
 
export default Experience

Ignore the preview part as it is redundant for the problem I am facing.

Child Component

import React from 'react'
import { ReactNode, useState } from 'react'
import { IExperience } from '.'
import { Preview } from './preview'

export const Message = ( { setPreview,data,setData }: {setPreview: any,data: IExperience[],setData: Dispatch<SetStateAction<IExperience[]>>} ) => {
    let [count,setCount] = useState(0)
    let formRows: ReactNode = []

    const formHandler = (i:number) => {
        console.log(data) //Console log here also shows data is undefined

        return formRows = [
             (<div key={`innerDiv${i}`}>
                <div><h2>Entry {i+1}</h2></div>
                <div>
                    <label>Position</label>
                    <input type="text" placeholder='Engineer' onChange={(e) => setData({...data,position: e.target.value})} value={data.position} /> //Error is here (data is undefined)
                </div>
            </div>)
         ]
    }

    const updateHandler = () => {
        setCount(prev => prev+1)
    }

    return (
        <div>
            <div>
                <div>
                </div>
                <form onSubmit={(e) => sendData(e)}>
                    {[...Array(count+1)].map((d,i) => (<div key={`outerDiv${i}`} >{formHandler(i)}</div>))}
                    <div>
                        <input type="button" value='+' onClick={() => updateHandler()} />
                    </div>
        
                </form>
            </div>
        </div>
    )
}

Again I am leaving out redundant stuff so that it stays focused on the problem.

I am not able to find a similar question to this, or a solution online

Hope this the code is clear 🙂

How to enter enter multiple entries in an array using onclick in HTML/PHP

I’m a junior developer and I wanted to know that how to enter text in multiple entries/fields/indexes in an array. Currently I’m doing a small project. So I am stuck in inputting the text repeatedly. Kindly help me in this regard. I can enter only one entry, i also tried to make use of classes but no luck.

                                    <!-- Tic Tac Toe Game -->

<html>
<head>
    <title>Tic Tac Toe</title>
    <style>
    body {
        background-color: whitesmoke;
        text-align: center;
    }

    #enteries{
        border-radius: 50px;
        border: 2px solid black;
        padding: 50px; 
        width: 200px;
        height: 15px;
        margin-bottom: 20px;
        margin-top: 20px;
        margin-right: 20px;
        font-size: 30px;
    }

    #done{
         
        border-radius: 10px;
        border: 2px solid black;
        padding: 50px; 
        width: 160px;
        height: 15px;
        margin-bottom: 20px;
        margin-top: 20px;
        margin-right: 20px;
        font-size: 15px;
    }
    </style>
</head>

<body>
    <h1>Welcome! X player</h1>

<form name = "ticktactoe" method = "post" action = "practice.php">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<?php

$winner = 'tied';
$x = array('','','','','','','','','');
if (isset($_POST["gobtn"]))
    {
        $x[0] = $_POST["x0"];
        $x[1] = $_POST["x1"];
        $x[2] = $_POST["x2"];
        $x[3] = $_POST["x3"];
        $x[4] = $_POST["x4"];
        $x[5] = $_POST["x5"];
        $x[6] = $_POST["x6"];
        $x[7] = $_POST["x7"];
        $x[8] = $_POST["x8"];

        if(($x[0] == 'x' && $x[1] == 'x' && $x[2] == 'x')  || ($x[3] == 'x' && $x[4] == 'x' && $x[5] == 'x') || ($x[6] == 'x' && $x[7] == 'x' && $x[8] == 'x') || ($x[0] == 'x' && $x[3] == 'x' && $x[6] == 'x')  || ($x[1] == 'x' && $x[4] == 'x' && $x[7] == 'x') || ($x[2] == 'x' && $x[5] == 'x' && $x[8] == 'x') || ($x[0] == 'x' && $x[4] == 'x' && $x[8] == 'x') || ($x[2] == 'x' && $x[4] == 'x' && $x[6] == 'x') )
        {
            $winner = 'x';
            Print "<h1>X Wins!</h1>";
        }

        $blank = 0; //if the field is blank
        for ($i = 0; $i <= 8 ; $i++)
        {
            if($x[$i] == '')
            {
                $blank = 1;
            }
        }
        if($blank == 1) //if the field contains value
        {
            $i = rand() % 8;
            while($x[$i] != '')
            {
                $i = rand() % 8;
            }
            $x[$i] = 'o';
            if(($x[0] == 'o' && $x[1] == 'o' && $x[2] == 'o')  || ($x[3] == 'o' && $x[4] == 'o' && $x[5] == 'o') || ($x[6] == 'o' && $x[7] == 'o' && $x[8] == 'o') || ($x[0] == 'o' && $x[3] == 'o' && $x[6] == 'o')  || ($x[1] == 'o' && $x[4] == 'o' && $x[7] == 'o') || ($x[2] == 'o' && $x[5] == 'o' && $x[8] == 'o') || ($x[0] == 'o' && $x[4] == 'o' && $x[8] == 'o') || ($x[2] == 'o' && $x[4] == 'o' && $x[6] == 'o') )
            {
                $winner = 'o';
                Print "<h1>O Wins!</h1>";
            }
            
        }
        else if ($winner == 'tied')
        {
            $winner = 'draw';
            Print "<h1>Match is tied</h1>";
        }
    }

    
    for($i = 0; $i <=8; $i++)

            {
                printf('<input type="text" id = "enteries" name = "x%s" value = "%s">', $i, $x[$i]);
                printf('<input type="radio" name="x" id="choose" value="x">');
                printf('<button type="button" onclick="getvalue();">click</button>');
    
            if ($i == 2 || $i == 5 || $i == 8){
                print("<br>");
                }
            }

            if($winner == 'tied')
            {
                //submitting
                print('<input type = "submit" name = "gobtn" style="margin-left: 10px" value = "Enter" id = "done">');
                
            }
            else
            {
                //play again when the matched is finished
                print('<input type = "button" name = "newgamebtn" value = "Play Again" id = "done" onclick = "window.location.href='practice.php'">');
            }
    
        ?>

</form>

<script>
    function getvalue(){
            
            var values = document.getElementById("choose").value;
            
            document.getElementById("enteries").value="x";
        }
    
</script>

</body>
</html>

How cancel scheduled jobs using BreeJS

I have an express server that starts a reoccurring job upon client request for a specified amount of time, the issue I’m facing is: How can I stop and remove that specific job after completion.

The code that I have is

// do the request logic
// generate the job ID
// save the job ID with repetition amount in mongoose
bree.add({
    name: jobID,
    interval : "30s",
    path : "./jobs/example_job.js",
    worker: {
    workerData: {
        jobID: jobID,
        }},
    })
bree.start(jobID)

and for the example_job.js

const thread = require("worker_threads") // for the jobID

// performs some logic
// reduce repetition amount
if(module.repetitionAmout == 0)
{
// delete the mongoose module
// stop the function with name jobID
}

My issue is with // stop the function with name jobID.
how can I achieve that?
I’ve tried process.exit(0) but that only exits the thread and doesn’t stop it from repeating again
I’ve also tried exporting and importing the bree instance to the example_job.js and passing the jobID to cancel it there but that also did not work, anyone has any experience with canceling jobs?