How to change an object of objects into a different object? [closed]

How to change an object of objects into object of arrays of objects. As below. I have included the output and the result. I’m interested in every way to do this, but I’m particularly interested in exploring reduce method. Because I guess it’s possible in this case?

I know how convert an array to an object with array.reduce() but not this one.

So, how to change this one:

const sourceData = {
  0: {
    name: "Mario",
    game: {
      home: "Nintendo",
      console: "Nintendo Switch",
      playground: "Mario Kart",
    },
  },
  1: {
    name: "Yoshi",
    game: {
      home: "Nintendo",
      console: "Nintendo Switch",
      playground: "Mario Kart",
    },
  },
  2: {
    name: "Aya Brea",
    game: {
      home: "Sony",
      console: "PlayStation",
      playground: "Parasite Eve",
    },
  },
  3: {
    name: " Solid Snake",
    game: {
      home: "Sony",
      console: "PlayStation",
      playground: "Metal Gear",
    },
  },
};

into this one:

const resultingData = {
  Nintendo: [
    {
      name: "Mario",
      game: {
        home: "Nintendo",
        console: "Nintendo Switch",
        playground: "Mario Kart",
      },
    },
    {
      name: "Yoshi",
      game: {
        home: "Nintendo",
        console: "Nintendo Switch",
        playground: "Mario Kart",
      },
    },
  ],
  Sony: [
    {
      name: "Aya Brea",
      game: {
        home: "Sony",
        console: "PlayStation",
        playground: "Parasite Eve",
      },
    },
    {
      name: "Solid Snake",
      game: {
        home: "Sony",
        console: "PlayStation",
        playground: "Metal Gear",
      },
    },
  ],
};

Javascript Timer Counter start again for every page reload

I build a timer to count Daily working time of employee. It is completely working fine until i refresh the page. I have three button clock in, stop, clock out. It should counting the time until I press the clock out button. What should I do in this case? I am not good with javascript so if anyone would love to help me, it would be great.

                       <form method="post" id="work-hour" action=""> 
                                {% csrf_token %}
                                <div class="card" id="holidays">
                                    <div class="card-header">
                                        <h5>Work Timer and Weekly Work History</h5>
                                        <div id="timeDiv"></div> 
                                        <br>
                                        <button id="startBtn" class="btn btn-outline-success Btn">Clock In</button>
                                        <!-- <button id="" class="Btn btn btn-outline-primary">Take a break</button> -->
                                        <button id="stopBtn" class="btn btn-outline-warning Btn">Stop</button>   
                                        <input type="text" hidden id="total_time_hour"  />
                                        <input type="text" hidden id="total_time_minute" />
                                        <input value="Clock Out" type="submit" id="submit" />                                    </div>
                                    
                                     </div>
                                
                       </form>

javascript

</script>
const csrftoken = getCookie('csrftoken');

    
        // include "are you sure" before reset

            var timeNow = {
            h: 0,
            m: 0,
            s: 0
            };

           
            function startTimer() {
            // start the timer

            counting = true;
            $('#stopBtn').prop("disabled", "");
            $('#startBtn').prop("disabled", "true");
            $('#resetBtn').prop("disabled", "true");
            $('#submit').prop("disabled", "true");
        
            
            countInterval = setInterval(count, 1000);
            }

            function stopTimer() {
            // stop the timer, but ask to confirm first
            if (!(areYouSure())) { return; }
            clearInterval(countInterval);
            var total_time = timeNow;
            console.log(total_time);
            $('#total_time_hour').val(timeNow.h)
            $('#total_time_minute').val(timeNow.m)


            //timeNow.h = 0;
            //timeNow.m = 0;
            //timeNow.s = 0;
            
            showTime();
            $('#startBtn').prop("disabled", "");
            $('#stopBtn').prop("disabled", "true");
            $('#resetBtn').prop("disabled", "");
            $('#submit').prop("disabled", "");
            
            }

            function areYouSure() {
            // let user confirm before stopping timer
            var sure = confirm("Are you sure you want to take a break?");
            return sure;
            }

            function showTime() {
            // put h/m/s together for display
            var hr, min, sec;
            if (timeNow.h < 1) {
            hr = "";
            }
            else {
            hr = "" + timeNow.h + ":";
            }
            if (timeNow.m < 1) {
            min = "00:";
            }
            else {
            if (timeNow.m < 10) {
            min = "" + "0" + timeNow.m + ":";
            }
            else {
            min = timeNow.m + ":";
            }
            }
            if (timeNow.s < 10) {
            sec = "" + "0" + timeNow.s;
            }
            else {
            sec = timeNow.s;
            }
            $('#timeDiv').html(hr + min + sec);
            }

            function count(){
            // increment the timer by 1s
            timeNow.s++;
            if (timeNow.s > 59) {
            timeNow.m++;
            timeNow.s = 0;
            }
            if (timeNow.m > 59) {
            timeNow.h++;
            timeNow.m = 0;
            }
            showTime();

            }

           

            function resetTimer() {
            // reset timer back to 0 after confirming
            if (!(areYouSure())) { return; }
            var total_time = timeNow;
            $('#total_time_hour').val(timeNow.h)
            $('#total_time_minute').val(timeNow.m)

            timeNow.h = 0;
            timeNow.m = 0;
            timeNow.s = 0;
            $('#resetBtn').prop("disabled", "true");
            $('#submit').prop("disabled", "true");
            showTime();
        }



        function submitTimer() {
            // reset timer back to 0 after confirming
            timeNow.h = 0;
            timeNow.m = 0;
            timeNow.s = 0;
            showTime();
            
        }

            $(document).ready(function() {
            showTime();
            $('#startBtn').click(function() { startTimer(); });
            $('#stopBtn').click(function() { stopTimer(); });
            $('#resetBtn').click(function() { resetTimer(); });
            $('#submit').click(function() { submitTimer(); });
            $('#stopBtn').prop("disabled", "true");
            $('#submit').prop("disabled", "true");
            $('#resetBtn').prop("disabled", "true");
            });

// add days?


        $(document).on('submit', '#work-hour', function(e){
            e.preventDefault();
            $.ajax({
                type:'POST',
                headers: {"X-CSRFToken": csrftoken},
                url: '/account/work/created/',
                data:{
                    total_time_hour: $('#total_time_hour').val(),
                    total_time_minute: $('#total_time_minute').val(),
                },
                success:function(){
                }
            });
        })

    </script>

Is there a tool for debugging/emulating Pointer Events?

I’d like to support multi touch and pen/stylus input for my application using Pointer Events.

Is there a tool available, browser extension or otherwise, that allows me emulate touch/pen input? I would like to debug several situations, like hovering with a pen without touching, or multitouch gestures. I prefer not to buy an expensive iPad or Surface Tablet just to debug pointer events.

How to use client.on in a JavaScript function?

I am currently using discord.js to develop a discord bot. I wanted to create a function to send a message based on user input.

The code I have is as follows:

function myFunction(keyWord) {
   client.on("messageCreate", myMessage => {
   if (myMessage.content.bot) {
      return
   }
   myMessage.channel.send(keyWord)
   )}
}

When I run this function in my code, the code seems to stop at the client.on section. It does not throw an error, it simply does not send the message or run any code beyond the client.on.

I appreciate any help!

Una petición fetch de javascript me da un error “ERR_HTTP2_PROTOCOL_ERROR” [closed]

días o noches, tengo una web que hice con vue 3 en la parte de frontend, en la parte del backend uso php y bases de datos MYSQL, en php hice una especie de api para mandar los datos que se piden desde el frontend, la petición del fronted la hago mediante fetch he ahí el problema al tratar de guardar, borrar o actualizar un registro me da el error ERR_HTTP2_PROTOCOL_ERROR pero lo extraño es que al cargar la página(se ejecuta una petición fetch a la api para que me consulte todos los registros y los devuelva) me trae todos los registro y no causa ningún error, la parte del frontend la tengo subida en github y la ejecuto mediante github pages, el backend esta en el hosting 000webhost cabe resaltar que ambos tiene SSL activo y funcionando, error generado: enter image description here, código fetch que lo genera enter image description here, header que estan en la api: enter image description here, código en la api que procesa la petición fetch:enter image description here, agradezco cualquier ayuda cabe mencionar que en local funciona correctamente.

I’m trying to script 6 identical tables/calculators with one easy code

I’m creating some calculators for a mobile game that I play. I’m going to have 6 of the same type of calculator on the same page. Each one should look and operate like so:

const speedupInputs = document.querySelectorAll('input');
const results = document.getElementById('results');
const submit = document.getElementById('submit');



submit.addEventListener('click', function() {
    let total = 0;
    results.textContent = '';
    speedupInputs.forEach((input) => {
        if(input.value != '') {
            if(input.classList.contains('minutes')) {
                total += input.value * input.name;
            } else if (input.classList.contains('hours')) {
                total += (input.value * input.name) * 60;
            } else if (input.classList.contains('days')) {
                total += (input.value * input.name) * 60 * 24;
            }
        }
    })   

    results.textContent = toTime(total * 60); 

});

function toTime(seconds) {
    const secsPerDay = 86400;
    const secsPerHour = 3600;
    const secsPerMinute = 60;

    var minus   = (this < 0) ? '-' : '';
    
    var days    = Math.floor(seconds / secsPerDay);
    seconds     = (seconds % secsPerDay);
    var hours   = Math.floor(seconds / secsPerHour);
    seconds     = (seconds % secsPerHour);
    var minutes = Math.floor(seconds / secsPerMinute);
    seconds     = (seconds % secsPerMinute);

    var sDays    = new String(days).padStart(1, '0');
    var sHours   = new String(hours).padStart(2, '0');
    var sMinutes = new String(minutes).padStart(2, '0');

    return `${minus}${sDays}d ${sHours}:${sMinutes}:00`;
}
table, tr, td {
    border: 1px solid black;
    border-collapse: collapse;
}

table {
    width: 100px;
    margin: 40px;
}

input {
    width: 90%;
    outline: 0;
    border: none;

}

td {
    text-align: center;
}
<table>
  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>
<thead>
  <th colspan="2">
    Speed-Ups
  </th>
</thead>
<tbody>
  <tr>
    <td>
      1m
    </td>
    <td>
      <input type="number" class="minutes" id="1m" name="1" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3m
    </td>
    <td>
      <input type="number" class="minutes" id="3m" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      5m
    </td>
    <td>
      <input type="text" class="minutes" id="5m" name="5" min="0">
    </td>
  </tr>
  <tr>
    <td>
      10m
    </td>
    <td>
      <input type="number" class="minutes" id="10m" name="10" min="0">
    </td>
  </tr>
  <tr>
    <td>
      15m
    </td>
    <td>
      <input type="number" class="minutes" id="15m" name="15" min="0">
    </td>
  </tr>
  <tr>
    <td>
      30m
    </td>
    <td>
      <input type="number" class="minutes" id="30m" name="30" min="0">
    </td>
  </tr>
  <tr>
    <td>
      45m
    </td>
    <td>
      <input type="number" class="minutes" id="45m" name="45" min="0">
    </td>
  </tr>
  <tr>
    <td>
      60m
    </td>
    <td>
      <input type="number" class="minutes" id="60m" name="60" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3h
    </td>
    <td>
      <input type="number" class="hours" id="3h" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      8h
    </td>
    <td>
      <input type="number" class="hours" id="8h" name="8" min="0">
    </td>
  </tr>
  <tr>
    <td>
      15h
    </td>
    <td>
      <input type="number" class="hours" id="15h" name="15" min="0">
    </td>
  </tr>
  <tr>
    <td>
      24h
    </td>
    <td>
      <input type="number" class="hours" id="24h" name="24" min="0">
    </td>
  </tr>
  <tr>
    <td>
      3d
    </td>
    <td>
      <input type="number" id="3d" class="days" name="3" min="0">
    </td>
  </tr>
  <tr>
    <td>
      7d
    </td>
    <td>
      <input type="number" id="7d" class="days" name="7" min="0">
    </td>
  </tr>
  <tr>
    <td>
      30d
    </td>
    <td>
      <input type="number" id="30d" class="days" name="30" min="0">
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <button id="submit" class="submitbtn">Submit</button>
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <p id="results" class="resultarea"></p>
    </td>
  </tr>
</tbody>
</table>

Because there are 6 and because I’m trying to follow the DRY way of coding, I’m trying to create the least amount of code to do the job of scripting all 6 calculators. I mean, they’re all identical si this shouldn’t be hard, right?

This is the code that I thought would work. I don’t know what the problem is because it isn’t throwing any errors in the console. In a nutshell, the code is pretty similar to the first, except I tried to reference all tables via a .forEach function. Also, I read that one way to reference children of an element is to give all of the children a class name and then use parentName.querySelectorAll('className') (hence me trying to use it with table as the “parentName”).

const submitBtns = document.querySelectorAll('.subitbtn'); 
const tables = document.querySelectorAll('table');
const speedupInputs = document.querySelectorAll('.tableinput');

submitBtns.forEach((btn) => {
    btn.addEventListener('click', myFunction);
});

function myFunction() {
    tables.forEach((table) => {
        const results = table.querySelector('.resultsarea');
        let total = 0;
        results.textContent = '';

        speedupInputs.forEach((input) => {
            if(input.value != '') {
                if(input.classList.contains('minutes')) {
                    total += input.value * input.name;
                } else if (input.classList.contains('hours')) {
                    total += (input.value * input.name) * 60;
                } else if (input.classList.contains('days')) {
                    total += (input.value * input.name) * 60 * 24;
                }
            }
        });
    results.textContent = toTime(total * 60);
    });
};

function toTime(seconds) {
    const secsPerDay = 86400;
    const secsPerHour = 3600;
    const secsPerMinute = 60;

    var minus   = (this < 0) ? '-' : '';
    
    var days    = Math.floor(seconds / secsPerDay);
    seconds     = (seconds % secsPerDay);
    var hours   = Math.floor(seconds / secsPerHour);
    seconds     = (seconds % secsPerHour);
    var minutes = Math.floor(seconds / secsPerMinute);
    seconds     = (seconds % secsPerMinute);

    var sDays    = new String(days).padStart(1, '0');
    var sHours   = new String(hours).padStart(2, '0');
    var sMinutes = new String(minutes).padStart(2, '0');

    return `${minus}${sDays}d ${sHours}:${sMinutes}:00`;
}

So yeah. To reiterate: I want 6 identical versions of these tables/calculators on a page, and I want one simple, easy code to script all 6 of them since they’re identical. Thank you.

Why dragstart event is still triggered when draggable attribute is set to false?

I have this sketch application, which allows user to draw some pictures by pressing and moving the mouse.

/* create grids in canvas */
const initCanvas = function() {
    const canvas = document.querySelector('.canvas');
    /* clear old canvas if any */
    canvas.innerHTML = '';
    /* create new canvas */
    let row = parseInt(document.querySelector('textarea.canvasRow').value);
    let column = parseInt(document.querySelector('textarea.canvasColumn').value);
    if (!row || !column) return;
    canvas.style['grid-template-columns'] = `repeat(${column}, 1fr)`;
    canvas.style['grid-template-rows'] = `repeat(${row}, 1fr)`;
    for (let i = 0; i < (row * column); i++) {
        let cell = document.createElement('div');
        cell.classList.add('cell');
        cell.draggable = false; // prevent cell from being dragged
        cell.addEventListener('mousedown', draw, false);
        cell.addEventListener('mouseenter', draw, false); // mouseenter is better than mouseover
        cell.addEventListener('dragstart', () => {}, false);
        canvas.appendChild(cell);
    }
}

/* mousedown event handler on canvas */
const toDraw = function(e) {
    // e.preventDefault(); // !IMPORTANT: inhibit some browser's default drag & drop behaviors
    isDrawing = true;
}

/* mouseenter event handler on each cell */
const draw = function(e) {
    // e.preventDefault(); // !IMPORTANT: inhibit some browser's default drag & drop behaviors
    if (isDrawing) {
        this.style['background-color'] = color;
    }
}

/* mouseup event handler on whole document */
const stopDrawing = function(e) {
    isDrawing = false;
    e.stopPropagation();
}

/* variables */
let color = 'black';
let isDrawing = false;
/* canvas init */
const initCanvasBtn = document.querySelector('.initCanvas');
initCanvasBtn.addEventListener('click', initCanvas);
/* draw */
const canvas = document.querySelector('.canvas');
canvas.draggable = false; // prevent canvas from being dragged
canvas.addEventListener('dragstart', () => {}, true);
canvas.addEventListener('mousedown', toDraw, true); // capture must be true. canvas must turn on "isDrawing" before cell capture the mousedown event.
document.addEventListener('mouseup', stopDrawing, true); // document element handle this. no need to notify children.
textarea.canvasRow,
textarea.canvasColumn {
    width: 4rem;
    height: 1rem;
}

.initCanvas {
    width: 4rem;
    height: 2rem;
    border: 1px solid black;
}

.canvas {
    height: 50vw;
    width: 50vw;
    border: 1px solid black;
    display: grid;
}

.cell {
    background-color: #F5F5F5;
    border: 1px solid #EBEBEB;
}
<textarea class="canvasRow">16</textarea>
<textarea class="canvasColumn">16</textarea>
<div class="initCanvas">Create canvas</div>
<div class="canvas"></div>

According to MDN Web Docs: draggable, to prevent element from being dragged, I set the draggable attribute of both canvas and cell to false.

cell.draggable = false;
canvas.draggable = false;

But when I test it, in 1/20 or 1/30 of cases, a no-drop cursor icon appears, and my mouseup event will be swollen.

enter image description here

After check MDN Web Docs: HTML Drag and Drop API I find another suspicious event: dragstart. So I add a listener on dragstart event. Then debugger’s dragstart Event Listener Breakpoint approved that dragstart event was fired when bug occured.
enter image description here

In another previous question: Will “mousedown” and “mousemove” change the cursor icon and how to prevent it?, @skmail suggested me to add preventDefault() on mousedown event.

It works! dragstart event is no longer fired. But I still want to know: why dragstart event can still be triggered when elements are configured as draggable=false? Did I mess something up in my code? According to MDN Web Docs: Drag Operations, user CANNOT drag an element if it is NOT draggable.

When a user begins to drag, the dragstart event is fired.

It would be very nice if you can further explain why preventDefault() can solve this problem? Thanks everyone.

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component wehn trying to change data

i am learning React, in an app i am trying to change description and amount and add a note, but every time i try i get an error:
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)

  2. You might be breaking the Rules of Hooks

  3. You might have more than one copy of React in the same app

    enter code here

my code:

import React from "react";
import { useParams } from "react-router-dom";
import { connect } from 'react-redux'
import ExpenseForm from "./ExpenseForm";
import { editExpense } from "../actions/expenses";
import { useNavigate } from "react-router-dom";

const EditExpensePage = (props) => {

const navigate = useNavigate();

  return (
   <div>
    <ExpenseForm 
      expense ={props.expense}
       onSubmit={(expense) => {
        props.dispatch(editExpense(props.expense.id, expense))
          navigate('/')
         }}
       />
      </div>
  )
}

const mapStateToProps = (state) => {
  const params = useParams()
  return {
     expense: state.expenses.find((expense) => expense.id === params.id)
  }
}

export default connect(mapStateToProps)(EditExpensePage)

thank you.

Getting an error saying matrix is undefined when I already initialized it [closed]

Getting an error saying

this.boardMatrix[i][j] = 1;
                       ^
TypeError: Cannot set properties of undefined (setting '2')

When I already have a private method that initializes the matrix to zeros when the constructor is called. This is a simplified version of the class:

class gameBoard {
constructor() {
    this.boardMatrix = this.#_initializeBoard;
  }
#_initializeBoard() {
    let board = [];
    for (let i = 0; i < 10; i++) {
      board.push([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
    }
    return board;
  }
  placeShip(i, j, axis) {
      // some code
      this.boardMatrix[i][j] = 1;
  }
}

And here’s how I triggered the error:

console.log(gameboard.boardMatrix());

verify azure active directory token using SubtleCrypto

I am trying to verify azure active directory ID and access tokens using the described flow in the ms docs. I am doing this in the browser. I know it’s pointless to do it on the frontend. I still want to know how to do it. Just out of curiosity.

There is something similar on https://jwt.io/. It’s meant to debug tokens. It can tell if a signature is valid or not.

In my code, the verification always fails. I am unsure If I am using SubtleCrypto correctly in this context. I am also unsure if I am choosing the right parameter for its functions, like the algorithm.

The header of the access token looks always something like this, using RS256.

{
  "typ": "JWT",
  "nonce": "<redacted>",
  "alg": "RS256",
  "x5t": "<redacted>",
  "kid": "<redacted>"
}

The matched JWK looks like this.

{
  "kty": "RSA",
  "use": "sig",
  "kid": "<redacted>",
  "x5t": "<redacted>",
  "n": "<redacted>",
  "e": "<redacted>",
  "x5c": ["<redacted>"]
}

I have created this function to get the JWK using the issuer URL in the claims and kid property in the header, and eventually validate the signature. crypto.subtle.verify returns always false.

async function verifyToken(rawToken) {
  // parse the token into parts
  const [encodedHeaders, encodedClaims, signature] = rawToken.split(".");
  const header = JSON.parse(atob(encodedHeaders));
  const claims = JSON.parse(atob(encodedClaims));

  // get the openid config using the issuer url
  const issuer_url = claims.iss.endsWith("/") ? claims.iss : claims.iss + "/";
  const openIdConfiguration = await (
    await fetch(`${issuer_url}.well-known/openid-configuration`)
  ).json();

  // get the jwk list
  const jwkList = await (
    await fetch(openIdConfiguration.jwks_uri)
  ).json();

  // find the jwk for the kid in the token header
  const matchedKey = jwkList.keys.find(k => k.kid === header.kid)

  // return early if no jwk is found
  if (!matchedKey) return {
    rawToken,
    header,
    claims,
    signature,
    openIdConfiguration,
    jwkList,
  };
 
  // import the jwk into a a crypto key
  const pubkey = await crypto.subtle.importKey(
    "jwk",
    matchedKey,
    { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } },
    true,
    ["verify"],
  );

  // verify the signature
  const verified = await crypto.subtle.verify(
    { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } },
    pubkey,
    new TextEncoder().encode(signature),
    new TextEncoder().encode(encodedHeaders + "." + encodedClaims),
  );

  // return the results
  return {
    rawToken,
    header,
    claims,
    signature,
    openIdConfiguration,
    jwkList,
    matchedKey,
    verified
  };
};

How do I get a parent div to resize when the children do?

I’m running into this problem with a program I’m working on and I can’t figure out the solution. Basically I have a webapp, on initial render the entire page is height X. There is a background color, and that color covers the full height of the page.

Moments after the initial render, data is fetched asynchronously and added to the page. The data causes the total height of the page to get larger. Unfortunately, only the original height of the page shows the background color, below that the background becomes white.

On further investigation, I’ve discovered this is due to a parent div not resizing when the child div does. Basically, the div getting elements added to it by the asynchronous data loading grows in height, but the parent wrapping around it (and the one that has the background color) does not.

During my investigation, I have found a partial solution: set the “height” to “auto”. The problem with this solution is when the page initially loads, the background color is only applied to the part of the page with actual content, rather than filling the screen. So if I have the height at “auto”, the color is screwed up when the page first loads before correcting itself after the items are added, and if the height is “100%” then the color is screwed up after the items are added.

I’m hoping there’s a way to resolve this. To help, I’ve put together a barebones HTML file that re-creates the issue. Assistance is appreciated. Thanks.

<!DOCTYPE html>
<html>
<head>
    <title>Layout Test</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        html {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        body {
            margin: 0;
            padding: 0;
            height: 100%;
        }
        #root {
            background-color: cyan;
            height: 100%;
        }

        #root > h1 {
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="root">
        <h1>Layout Test</h1>
        <div id="container"></div>
    </div>
    <script>
        setTimeout(() => {
            const container = document.querySelector('#container');
            for (let i = 0; i < 100; i++) {
                const h1 = document.createElement('h1');
                h1.textContent = 'Hello';
                container.appendChild(h1);
            }
        }, 1000);
    </script>
</body>
</html>

Reset a cooldown for everyone, every hour (Discord.js)

I’m making a Mudae-like bot for my friends and I wanted to add the same cooldown system they use for the rolls (which resets after a specific time, and not according to the use of the command or not)

To put it clear :

It’s not “You can’t roll anything for 1 hour after your last roll command”

It’s more like “Every hour, everyone can roll again, and they can do it once until the next roll reset”

I’m not sure where to start, because for now I use a normal cooldown system (which depends on the user => “You can’t roll anything for 1 hour after your last roll command”) and it’s possible I have to start from scratch.

What should I do to start ?

TailwindCss’s mobile breakpoints doesn’t work

I am building a custom navbar in React using TailwindCss for styling. For reference I am following a tutorial on YouTube which’s code can be found here.

When I use the mobile breakpoints as prefix like in the example below only the div saying “mobile” works as it should be:

<nav>
  <div className={"flex"}>
    <div className={"hidden md:flex"}>desktop</div>
    <div className={"md:hidden"}>mobile</div>
  </div>
</nav>

The output “desktop” should be shown when the text “mobile” vanishes but for some reason it doesn’t. Am I doing something wrong or is there a problem with Tailwind?

enter image description here