snackbar position below another

How can I put my snackbars so that they are displayed one below the other?

I hope that the page shows my error messages one below the other, I would just like to know about their position in a .ts file

Node js fluent-ffmpeg silencedetect info to CSV

I am trying get timestamps of in and out points of silent parts of an audio file. The duration of the silent part is 5-7sec, sometimes the part have some random single noises.
Ideally as a final result I want get JSON or csv file with all info

I am new to nodeJS and I am not sure how to access the outputs of the ffmpeg ‘silencedetect’ filter. I have been trying to console.log output of the code below but it didn’t work

var ffmpeg = require('fluent-ffmpeg');
ffmpeg(audioPath)
  .audioFilters('silencedetect=n=-50dB:d=5');

Audio wave example

Why doesn’t the flipping work with my notecards?

I am making a text to notecard program in html-js-css, and I wanted to add a button where you could flip all flashcards over. As it is right now, it only works flipping from the back face to the front:
https://www.dropbox.com/s/ze28yfdzy439lpi/Notes2Cards%20-%20Google%20Chrome%202023-03-07%2013-46-17.mp4?dl=0
(video of issue)

Repository with code: https://github.com/Subwaey/Notes2Cards

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>Notes2Cards</title>
    <script>
        function flipAll() {
            const cards = document.querySelectorAll('.card');

            cards.forEach(card => {
            card.addEventListener('click', () => {
            card.classList.toggle('flipped');
            });
            });
        }
    </script>
</head>
<body onload="storeValue()">
    <div class="custom-shape-divider-bottom-1678203398">
        <svg data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 120" preserveAspectRatio="none">
            <path d="M0,0V46.29c47.79,22.2,103.59,32.17,158,28,70.36-5.37,136.33-33.31,206.8-37.5C438.64,32.43,512.34,53.67,583,72.05c69.27,18,138.3,24.88,209.4,13.08,36.15-6,69.85-17.84,104.45-29.34C989.49,25,1113-14.29,1200,52.47V0Z" opacity=".25" class="shape-fill"></path>
            <path d="M0,0V15.81C13,36.92,27.64,56.86,47.69,72.05,99.41,111.27,165,111,224.58,91.58c31.15-10.15,60.09-26.07,89.67-39.8,40.92-19,84.73-46,130.83-49.67,36.26-2.85,70.9,9.42,98.6,31.56,31.77,25.39,62.32,62,103.63,73,40.44,10.79,81.35-6.69,119.13-24.28s75.16-39,116.92-43.05c59.73-5.85,113.28,22.88,168.9,38.84,30.2,8.66,59,6.17,87.09-7.5,22.43-10.89,48-26.93,60.65-49.24V0Z" opacity=".5" class="shape-fill"></path>
            <path d="M0,0V5.63C149.93,59,314.09,71.32,475.83,42.57c43-7.64,84.23-20.12,127.61-26.46,59-8.63,112.48,12.24,165.56,35.4C827.93,77.22,886,95.24,951.2,90c86.53-7,172.46-45.71,248.8-84.81V0Z" class="shape-fill"></path>
        </svg>
    </div>
    <script src="script.js"></script>
    <form onsubmit="storeValue(); return false;">
        <label for="input">Enter notes:</label>
        <textarea id="input" name="input" rows="10" cols="78" placeholder="[list of terms and definitions]">
Note 1 - Definition 1
Note 2 - Definition 2
Note 3 - Definition 3</textarea>
<input type="text" id="symbol" value="-" placeholder="[symbol seperating terms and definitions]">
        <button type="submit">Generate</button>
        <button onclick="flipAll()">Flip All</button>
      </form>
      <div class="grid" id="flashcards"></div>
</body>
</html>

js:

function storeValue() {
    var inp = document.getElementById("input").value.toString();
    const terms = []
    const definitions = []
    const defobj = {}

    let symbol = document.getElementById("symbol").value.toString();
    const regex = new RegExp(`\s*${symbol}\s*(.*)`);
    inp.split('n').forEach(line => {
      if (line.includes(symbol)) {
        [term, definition, _] = line.split(regex)
        terms.push(term)
        definitions.push(definition)
        defobj[term] = definition
      }
    })
    

    console.log(inp)
    console.log(terms)
    console.log(definitions)
    console.log(defobj)

    const flashcards = document.getElementById("flashcards");
    flashcards.innerHTML = "";
        
        for (let i = 0; i < terms.length; i++) {
            const card = document.createElement("div");
            card.classList.add("card");
            
            const cardInner = document.createElement("div");
            cardInner.classList.add("card-inner");
            card.appendChild(cardInner);
            
            const cardFront = document.createElement("div");
            cardFront.classList.add("card-front");
            cardFront.innerHTML = `<h2>${terms[i]}</h2>`;
            cardInner.appendChild(cardFront);
            
            const cardBack = document.createElement("div");
            cardBack.classList.add("card-back");
            cardBack.innerHTML = `<p>${definitions[i]}</p>`;
            cardInner.appendChild(cardBack);
            
            card.addEventListener("click", function() {
                card.classList.toggle("flipped");
            });
            
            flashcards.appendChild(card);
        }
  }

css:

body {
  background-color: #222;
  color: #fff;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  font-size: 16px;
  overflow-x: hidden;
}

textarea::-webkit-resizer {
  background-color: #222;
  border: 1px solid #444;
  border-radius: 10px;
  width: 2px;
  height: 2px;
}

::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background-color: #222;
}

::-webkit-scrollbar-thumb {
  background-color: #555;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
  background-color: #888;
}


.custom-shape-divider-bottom-1678203398 {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  overflow: hidden;
  line-height: 0;
  transform: rotate(180deg);
}

.custom-shape-divider-bottom-1678203398 svg {
  position: relative;
  display: block;
  width: calc(181% + 1.3px);
  height: 421px;
  transform: rotateY(180deg);
}

.custom-shape-divider-bottom-1678203398 .shape-fill {
  fill: #2E2E2E;
}

form {
  background-color: #444;
  border-radius: 10px;
  padding: 30px;
  margin: 50px auto;
  max-width: 800px;
}

label {
  display: block;
  margin-bottom: 20px;
}

textarea, input[type="text"] {
  width: 100%;
  border: none;
  border-radius: 10px;
  background-color: #252525;
  color: #fff;
  padding: 15px;
  margin-bottom: 20px;
  font-size: 18px;
  box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.2);
  resize: none;
  box-sizing: border-box;
}

textarea::placeholder, input[type="text"]::placeholder {
  color: #A0A0A0;
  font-size: 18px;
}

button {
  background-color: #007bff;
  border: none;
  border-radius: 10px;
  color: #fff;
  cursor: pointer;
  font-size: 18px;
  margin-top: 20px;
  padding: 15px 30px;
  width: 100%;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #0056b3;
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  grid-gap: 50px;
  margin: 50px auto;
  max-width: 1200px;
  padding: 30px;
}

.card {
  width: 400px;
  height: 250px;
  background-color: #252525;
  border-radius: 10px;
  box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.2);
  transition: transform 0.3s;
  margin: 50px auto;
  position: relative;
}

.card:hover {
  transform: scale(1.05);
  background-color: #2e2e2e;
}

.card .card-inner {
  position: absolute;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.3s;
  transform-style: preserve-3d;
  backface-visibility: hidden;
}

.card .card-front,
.card .card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.card .card-front {
  transform: rotateY(0deg);
}

.card .card-back {
  transform: rotateY(180deg);
}

.card .card-back p {
  transform: rotateY(180deg);
}

.card.flipped .card-inner {
  transform: rotateY(180deg);
}

.card.flipped {
  transform: rotateY(180deg);
}

.card.flipped .card-front {
  transform: rotateY(0deg);
}
  

insertBefore: The child to insert before is not a child of this node

I am rewriting a jquery dragable script to plain javascript. At the insertBefore (https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore) point I get this error message:
NotFoundError: Node.insertBefore: Child to insert before is not a child of this node.

This error occurs when I want to move a lower list element to the top.

Here is my code.

let items = document.querySelectorAll("#items-list > li");

items.forEach((item) => {
  item.setAttribute("draggable", true);
  item.addEventListener("dragstart", dragStart);
  item.addEventListener("drop", dropped);
  item.addEventListener("dragenter", cancelDefault);
  item.addEventListener("dragover", cancelDefault);
});

const getNodeIndex = elm => [...elm.parentNode.children].indexOf(elm)

function dragStart(e) {
  const index = getNodeIndex(e.target);  
  e.dataTransfer.setData("text/plain", index);
}

function dropped(e) {
  cancelDefault(e);

  // get new and old index
  let oldIndex = e.dataTransfer.getData("text/plain");
  let target = e.target;
  let newIndex = getNodeIndex(e.target);

  let droppedElement = e.currentTarget.parentNode.children[oldIndex];
  droppedElement.remove();
  
  // insert the dropped items at new place
  if (newIndex < oldIndex) {
    //---> this is the problematic line <---
    target.insertBefore(droppedElement, e.currentTarget.parentNode);
  } else {
    target.after(droppedElement);
  }
}

function cancelDefault(e) {
  e.preventDefault();
  e.stopPropagation();
  return false;
}
<div class="container">
  <ul id="items-list" class="moveable">
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
      <li>Four</li>
  </ul>
  
</div>

full calender not displaying the events on the timeGridWeek,timeGridDay,listMonth

I’m using FullCalendar in my web application, and I’m having trouble getting events to show up on the timeGridWeek and timeGridDay views. The events show up fine on the dayGridMonth view, but when I switch to the timeGridWeek or timeGridDay view, the events disappear.

I’ve checked that the events have valid start and end times, and that the views are properly configured to display the timeGridWeek and timeGridDay views. I’m using FullCalendar version 6.1.4, and I’ve included the timeGridPlugin script in my HTML file.

var calendarEl = document.getElementById("calender");
var calendar = new FullCalendar.Calendar(calendarEl, {
    theme: true,
slotMinutes: 10,
allDaySlot: false,
    headerToolbar: {
        left: "prev,next today",
        center: "title",
        right: "dayGridMonth,timeGridWeek,timeGridDay,listMonth"
    },

    height: 800,
    contentHeight: 780,
    aspectRatio: 3,  

    nowIndicator: true,
    now: new Date(),

    views: {
        dayGridMonth: { buttonText: "month" },
        timeGridWeek: { buttonText: "week" },
        timeGridDay: { buttonText: "day" }
    },
    droppable: true,
    initialView: "dayGridMonth",
    initialDate: new Date(),
    eventDisplay: 'auto',
    editable: true,
    dayMaxEvents: true, // allow "more" link when too many events
    navLinks: true,
    eventDrop: function(info) {
        // Handle the event drop
        console.log(info.event.title + " was dropped on " + info.event.start.toISOString());
      },
      locale: 'fr',
      allDayDefault: false,
      events: [ // Add some events to the calendar
        {
            id:20,
          title: 'Event 1',
          start: new Date()
        },
        {
            id:522,
          title: 'Event 2',
          "start"  : "2023-03-11 12:00",
                "end" : "2023-03-11 15:00",
                allDay: false
        }
      ], 
   



    
});

calendar.render();

Javascript:JSON: group by an element

I have an array of JSON objects and am trying to group it by an element. I followed the sample code from :
Convert JSON format (Group by)

My Code:

  const groupBy = prop => data => {
    return data.reduce((dict, item) => {
    const { [prop]: _, ...rest } = item;
    dict[item[prop]] = [...(dict[item[prop]] || []), rest];
    return dict;
  }, {});
};


var data = [
            {'PlazaID': 1, 'LaneID': 2, 'CamID': 3, 'CamDesc': 'Camera - 3'},
            {'PlazaID': 1, 'LaneID': 2, 'CamID': 4, 'CamDesc': 'Camera - 4'},
            {'PlazaID': 1, 'LaneID': 3, 'CamID': 3, 'CamDesc': 'Camera - 3'},
            {'PlazaID': 1, 'LaneID': 3, 'CamID': 4, 'CamDesc': 'Camera - 4'}
            ];
            
/*
I am trying to morph the above json into
[
    'LaneID': 2, Cameras: [{'CamID': 3, 'CamDesc': 'Camera - 3'}, {'CamID': 4, 'CamDesc': 'Camera - 4'}],
    'LaneID': 3, Cameras: [{'CamID': 3, 'CamDesc': 'Camera - 3'}, {'CamID': 4, 'CamDesc': 'Camera - 4'}]
]

*/
console.log(groupBy('LaneID')(data));
const result = Object.entries(groupBy('LaneID')(data))
  .map(([key, value]) => ({ LaneID: key, Cameras: JSON.stringify(value) }));

console.log(result);
console.log(result.Cameras);

I am able to get the data grouped by LaneID, but I can’t seem to get the Cameras grouped by.

How to filter filter data after extracted data in Json form

I’ve extracted data but having problem to filter some data that I would like to get only. Below is the code:

// 7. for each itemid, extract the metrics required (the list of metrics in section 2) //
      outdata.forEach(function (outJson) {
        var temp = []
        for (var j = 0; j < head.length; j++) {
          
          temp.push((outJson[head[j]]) ? outJson[head[j]] : "" ) // ? : works like an if statement (condition ? value if true : value if false) //

        }
        if(temp.length>=34){
            temp.pop() // remove the last empty column 
        }
 
        temp.push(counter)
        // console.log(temp)
        toPrint.push(temp)
        counter++
      })
    }

The condition that I want to filter is as below but not sure how to amend and incorporate into the above chunk to make it work:

temp= temp.filter(function (row) { return (row[24] ==1); })

Issue with async SQLite statement execution wrapper functions

I am having an issue executing an SQL statement immediately after creating and populating a table.

I think the record does not exist, because the creation query does not finish in time.

If I pass false for my clean flag (in createDatabaseFromSQL), after a few attempts,

I get the expected:

$ node ./setup.js 
CREATE database
Executing: DROP TABLE IF EXISTS `accounts`
Executing: CREATE TABLE IF NOT EXISTS `accounts` ( `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, `username` VARCHAR(50) NOT NULL, `password` VARCHAR(255) NOT NULL, `email` VARCHAR(100) NOT NULL )
Executing: INSERT INTO `accounts` (`username`, `password`, `email`) VALUES ('admin', 'admin', '[email protected]'), ('test', 'test', '[email protected]')
FETCH test account
Connected to the 'auth' database.
Connected to the 'auth' database.
true
Close the 'auth' database connection.
Close the 'auth' database connection.

If I force-clean, the selection fails, because the accounts table does not exist.

$ node ./setup.js 
CREATE database
Executing: DROP TABLE IF EXISTS `accounts`
Executing: CREATE TABLE IF NOT EXISTS `accounts` ( `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, `username` VARCHAR(50) NOT NULL, `password` VARCHAR(255) NOT NULL, `email` VARCHAR(100) NOT NULL )
Executing: INSERT INTO `accounts` (`username`, `password`, `email`) VALUES ('admin', 'admin', '[email protected]'), ('test', 'test', '[email protected]')
FETCH test account
Connected to the 'auth' database.
Connected to the 'auth' database.
node:internal/process/esm_loader:97
    internalBinding('errors').triggerUncaughtException(
                              ^

[Error: SQLITE_ERROR: no such table: accounts] {
  errno: 1,
  code: 'SQLITE_ERROR'
}

Node.js v18.14.0

Files

Here are the associated files.

setup.js

import { createDatabaseFromSql, executeQuery } from "./query-utils.js";

console.log("CREATE database");
await createDatabaseFromSql("auth", "./setup.sql", true);

console.log("FETCH test account");
const row = await executeQuery(
  "auth",
  "SELECT * FROM `accounts` where `username` = ?",
  ["test"]
);
console.log(row?.id === 2);

query-utils.js

import fs from "fs";
import sqlite3 from "sqlite3";

const SQL_DEBUG = true;

const loadSql = (filename, delimiter = ";") =>
  fs
    .readFileSync(filename)
    .toString()
    .replace(/(rn|n|r)/gm, " ")
    .replace(/s+/g, " ")
    .split(delimiter)
    .map((statement) => statement.trim())
    .filter((statement) => statement.length);

const executeSerializedQueries = async (databaseName, callback) => {
  let db;
  try {
    db = new sqlite3.Database(`./${databaseName}.db`, (err) => {
      if (err) console.error(err.message);
      console.log(`Connected to the '${databaseName}' database.`);
    });
    db.serialize(() => {
      callback(db);
    });
  } catch (e) {
    throw Error(e);
  } finally {
    if (db) {
      db.close((err) => {
        if (err) console.error(err.message);
        console.log(`Close the '${databaseName}' database connection.`);
      });
    }
  }
};

const createDatabaseFromSql = async (databaseName, sqlFilename, clean) =>
  new Promise((resolve, reject) => {
    if (clean) {
      fs.rmSync(`./${databaseName}.db`, { force: true }); // Remove existing
    }
    try {
      executeSerializedQueries(databaseName, (db) => {
        loadSql(sqlFilename).forEach((statement) => {
          if (SQL_DEBUG) {
            console.log("Executing:", statement);
          }
          db.run(statement);
        });
        resolve();
      });
    } catch (e) {
      reject(e);
    }
  });

const executeQuery = async (databaseName, query, params = []) =>
  new Promise((resolve, reject) => {
    try {
      executeSerializedQueries(databaseName, (db) => {
        db.get(query, params, (error, row) => {
          if (error) reject(error);
          else resolve(row);
        });
      });
    } catch (e) {
      reject(e);
    }
  });

const executeQueryAll = async (databaseName, query, params = []) =>
  new Promise((resolve, reject) => {
    try {
      executeSerializedQueries(databaseName, (db) => {
        db.all(query, params, (error, rows) => {
          if (error) reject(error);
          else resolve(rows);
        });
      });
    } catch (e) {
      reject(e);
    }
  });

export {
  createDatabaseFromSql,
  executeSerializedQueries,
  executeQuery,
  executeQueryAll,
  loadSql,
};

setup.sql

DROP TABLE IF EXISTS `accounts`;

CREATE TABLE IF NOT EXISTS `accounts` (
  `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  `username` VARCHAR(50) NOT NULL,
  `password` VARCHAR(255) NOT NULL,
  `email` VARCHAR(100) NOT NULL
);

INSERT INTO `accounts` (`username`, `password`, `email`)
  VALUES ('admin', 'admin', '[email protected]'),
    ('test', 'test', '[email protected]');

package.json

{
  "dependencies": {
    "sqlite3": "^5.1.4"
  }
}

npm tries to sign me up for private packages when publishing public packages

I have a package @myorg/somename that has private set to false. When publishing the package with npm publish I get the error:

npm notice Publishing to https://registry.npmjs.org/ with tag latest and default access
npm ERR! code E402
npm ERR! 402 Payment Required - PUT https://registry.npmjs.org/@myorg%2fsomename - You must sign up for private packages

The package is Open Source, and I explictly wish to publish the package publicly. How can I publish the package?

Why does when calling the reset() function, other functions that are onclick on the button stop working?

Trying to build my first “quizAPP”. The reset function, doesn’t let me click other buttons when clicked.
Here is my code: https://codepen.io/Leonyr/pen/eYLEEgq

function reset(){ num = 1; let img = document.querySelector('#img'); img.src = ${baseUrl}${num}.png nextBtn.disabled = false; nextBtn.style.color = '#555b6e' nextBtn.style.pointerEvents = 'auto'; spanNumber.innerText = num; for(let i=0;i<allBtn.length;i++){ // allBtn[i].classList.add('reset'); allBtn[i].classList.remove('chozen','dizabled') allBtn[i].style.pointerEvents='auto'; } }

I tried creating a function which removes the classes and resets the pointerEvents.

JavaScript – Youtube channel whitelist using Tampermonkey

TL;DR: I want a whitelist for YouTube channels and hide/block all others from search results and recommendations ?


I want to hide all channels from search results and from recommendations except from a whitelist of channels I approve of.

I understand I have to create a list of channels I like but it is better than doing the reverse and BlockTube does not have a whitelist, however it does have this listed in “Future work” in their GitHub but does not have a set date.

React Dynamic Checkbox list doesn’t marked when i checked

Please help with this matter:
I’m making a nested dynamic list of checkboxes to select companies and groups of this companies, investigating, i have the following result

  const [checkedGroups, setCheckedGroups] = useState([]);
  const handleChangeGroup = (event) => {
    const index = checkedGroups.indexOf(event.target.value);
    if (index === -1) {
      setCheckedGroups([...checkedGroups, event.target.value]);
    } else {
      setCheckedGroups(checkedGroups.filter((checkedGroup) => checkedGroup !== event.target.value));
    }
    console.log(checkedGroups,index,event.target.value,checkedGroups.includes(event.target.value));

  };
inside jsx ...

  <Grid item xs={12} md={12}>
    <Typography variant="h6">Empresas Activas </Typography>
    <Box>
      {companiesList.map((company) => (
        <Box key={company.id}>
          <FormControlLabel key={company.id} control={<Checkbox />} label={company.name} />
          {company.groups.map((group) => (
            <Box key={group.id} sx={{ display: 'flex', flexDirection: 'column', ml: 3 }}>
              <FormControlLabel control={<Checkbox checked={checkedGroups.includes(group.id)} value={group.id} onChange={handleChangeGroup} />} label={group.name} />
              {checkedGroups.includes(group.id)}
            </Box>
          ))}
        </Box>
      ))}
    </Box>
  </Grid>

almost result checkbox list

The checkoxes list displays as espected even the handling checks for groups, displays accurate data for procesesing and no errors in anytime, but the big problem is:
the checkboxes doesn’t change to checked or unchecked in any time, what i’m doing wrong?

as you can see the checked prop in the checbox components is determined by
checked={checkedGroups.includes(group.id)}
and when in check in console this value show true or false, at the moment the checked element is incorporated or eliminated front the list

How to display a Mapbox map behind a navbar without losing ability to move around map?

I have a React (Next.js) project using Mapbox. I want to display a map (Map component supplied by react-map-gl) behind an opaque/transparent navbar.

I can get the desired visual effect by setting the z-index of the map component to -1. However, I then lose the ability to move the map around. I made a screen recording illustration this here: https://streamable.com/t3ghld. You can see that when I remove the z-index and the map overlaps the navbar, I can then click and drag to move around.

Here is the associated code:

import Map from "react-map-gl";
import Navbar from "@/components/Navbar";

export default function MapMain() {
  console.log(process.env.NEXT_PUBLIC_MAP_KEY);
  return (
    <>
      <Navbar />
      <Map
        initialViewState={{
          longitude: -122.4,
          latitude: 37.8,
          zoom: 14,
        }}
        style={{
          zIndex: -1,
          width: "100vw",
          height: "100vh",
        }}
        mapStyle="mapbox://styles/mapbox/streets-v9"
        mapboxAccessToken={process.env.NEXT_PUBLIC_MAP_KEY}
      />
    </>
  );
}

I should also say that if I remove the position: fixed property from my navbar (as well as remove the z-index from the map since it isn’t necessary), then it works fine, as shown here: https://streamable.com/z9ub53. I guess that would suffice, but I really want that transparent look if possible.