How can i update this command fully to v14? It’s giving me an error:

I currently have a say embed command that worked fine in v12 that im trying to update to v14, however im getting a very large error, and im wondering how i could fix the error/update the command if i havent completely fixed everything?

This is the code:

const { EmbedBuilder } = require("discord.js");

module.exports = {
  name: "embed",
  aliases: [" "],
  run: async (client, message, guild) => {
    let args = message.content.split(" | ");

    //    message.delete().catch(O_o => {});

    const embed = new EmbedBuilder()

      .setTitle(args[1])
      .setDescription(args[2])
      .setThumbnail(args[3])
      .setImage(args[4])
      .setColor(args[5]);

    message.channel.send({ embeds:  });
  },
};

this is the error im getting:

/home/runner/bear-bot-v14/node_modules/@sapphire/shapeshift/dist/index.js:1088
    return Result.err(new CombinedError(errors));
                      ^

CombinedError: Received one or more errors
    at UnionValidator.handle (/home/runner/bear-bot-v14/node_modules/@sapphire/shapeshift/dist/index.js:1088:23)
    at UnionValidator.parse (/home/runner/bear-bot-v14/node_modules/@sapphire/shapeshift/dist/index.js:201:88)
    at EmbedBuilder.setTitle (/home/runner/bear-bot-v14/node_modules/@discordjs/builders/dist/index.js:267:20)
    at Object.run (/home/runner/bear-bot-v14/commands/general/embed.js:13:8)
    at Client.<anonymous> (/home/runner/bear-bot-v14/index.js:90:24)
    at Client.emit (node:events:513:28)
    at Client.emit (node:domain:489:12)
    at MessageCreateAction.handle (/home/runner/bear-bot-v14/node_modules/discord.js/src/client/actions/MessageCreate.js:28:14)
    at module.exports [as MESSAGE_CREATE] (/home/runner/bear-bot-v14/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32) {
  errors: [
    ExpectedValidationError: Expected values to be equals
        at LiteralValidator.handle (/home/runner/bear-bot-v14/node_modules/@sapphire/shapeshift/dist/index.js:729:76)
        at LiteralValidator.run (/home/runner/bear-bot-v14/node_modules/@sapphire/shapeshift/dist/index.js:187:23)
        at UnionValidator.handle (/home/runner/bear-bot-v14/node_modules/@sapphire/shapeshift/dist/index.js:1083:32)
        at UnionValidator.parse (/home/runner/bear-bot-v14/node_modules/@sapphire/shapeshift/dist/index.js:201:88)
        at EmbedBuilder.setTitle (/home/runner/bear-bot-v14/node_modules/@discordjs/builders/dist/index.js:267:20)
        at Object.run (/home/runner/bear-bot-v14/commands/general/embed.js:13:8)
        at Client.<anonymous> (/home/runner/bear-bot-v14/index.js:90:24)
        at Client.emit (node:events:513:28)
        at Client.emit (node:domain:489:12) {
      validator: 's.literal(V)',
      given: undefined,
      expected: null
    },
    ValidationError: Expected a string primitive
        at StringValidator.handle (/home/runner/bear-bot-v14/node_modules/@sapphire/shapeshift/dist/index.js:1705:70)
        at StringValidator.run (/home/runner/bear-bot-v14/node_modules/@sapphire/shapeshift/dist/index.js:187:23)
        at UnionValidator.handle (/home/runner/bear-bot-v14/node_modules/@sapphire/shapeshift/dist/index.js:1083:32)
        at UnionValidator.parse (/home/runner/bear-bot-v14/node_modules/@sapphire/shapeshift/dist/index.js:201:88)
        at EmbedBuilder.setTitle (/home/runner/bear-bot-v14/node_modules/@discordjs/builders/dist/index.js:267:20)
        at Object.run (/home/runner/bear-bot-v14/commands/general/embed.js:13:8)
        at Client.<anonymous> (/home/runner/bear-bot-v14/index.js:90:24)
        at Client.emit (node:events:513:28)
        at Client.emit (node:domain:489:12) {
      validator: 's.string',
      given: undefined
    }
  ]
}

Disable font resizing after 2 clicks

I want the font resizer button to be disabled after two clicks for increasing and decreasing font.

As of now, the text size keeps increasing and decreasing and i want it to stopped after two clicks on both increase and decrease button.

(function($) {
  var jQueryaffectedElements = jQuery("body, p, h1, h2, h3, h4, h5, h6, div, a, span, html, ul, li, ol, audio, br, hr, form, section, font, head, header, i, input, img, label, table,ul.footer-list li a");

  jQueryaffectedElements.each(function() {
    var jQuerythis = jQuery(this);
    jQuerythis.data("orig-size", jQuerythis.css("font-size"));
  });

  jQuery("#btn-increase_wp_font_rp").click(function() {

    changeFontSize(2);
  })

  jQuery("#btn-decrease_wp_font_rp").click(function() {
    changeFontSize(-2);
  })

  jQuery("#btn-orig_wp_font_rp").click(function() {
    jQueryaffectedElements.each(function() {
      var jQuerythis = jQuery(this);
      jQuerythis.css("font-size", jQuerythis.data("orig-size"));
    });
  })

  function changeFontSize(direction) {
    jQueryaffectedElements.each(function() {
      var jQuerythis = jQuery(this);

      jQuerythis.css("font-size", parseInt(jQuerythis.css("font-size")) + direction);

    });

  }

})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Click to increase and decrease fontsizes</h1>
<button id="btn-decrease_wp_font_rp">Decrease</button>
<button id="btn-orig_wp_font_rp">Reset</button>
<button id="btn-increase_wp_font_rp">Increase</button>

Difficult situation with some assignments [closed]

I have a situation from which I can’t see a way out without it being to my detriment.

I will briefly describe my situation.

  • I entered the IT academy 2 years ago, majoring in Java development,

  • moved to Azerbaijan and turned to another profession that has nothing to do with programming.

  • due to work, neither the conditions nor the time to follow that IT academy…

  • now I have a deadline to finish everything by March 10

Since I never studied and learned how to write these codes and programs, I cannot pass it.

Now I feel some kind of guilt or a pang of conscience because I will probably not succeed in passing and getting that diploma which will be a memory of the 2000 euros I gave them.

A diploma is worthless if there is no knowledge to back it up, but I have no choice but to ask someone for help so that the 2,000 euros don’t go to waste, at least have some paper as a souvenir.

That’s why I’m addressing you this way, to ask if anyone is in the situation and willing to help me.

Those assignments are probably simple for someone who has the experience and has been doing this for a while, for me it’s impossible…

If anyone is willing, feel free to leave a message/comment and I will send the tasks, so whatever happens, happens.

Many thanks for considering my request.

Obviously not much. 🙁

Main Activity Using onStart, onStop, onResume Not Showing the Appropriate XML/Interface

I’m following a guide on coding by Easy Tuto, currently on part 7 at the end where the recycler_note_item.xml would show up on the interface. In the video, he fixed the problem by adding the onStart, onStop, onResume commands and adding `noteAdapter.startListening’ in between the lines as shown here: enter image description here In the video, it worked and showed the item however nothing showed up for me. I tried scouring the video trying to find what I did wrong. I’m pretty new to coding and I was using his video as a base to learn more about it. I added those lines myself but it diddn’t work for me it seems. Can someone please help me? It would be greatly appreciated. Here is my code for MainActivity.Java:

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageButton;

import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.firestore.Query;

public class MainActivity extends AppCompatActivity {

    FloatingActionButton addNoteBtn;
    RecyclerView recyclerView;
    ImageButton menuBtn;
    NoteAdapter noteAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addNoteBtn = findViewById(R.id.add_note_btn);
        recyclerView = findViewById(R.id.recyler_view);
        menuBtn = findViewById(R.id.menu_btn);

        addNoteBtn.setOnClickListener((v)-> startActivity(new Intent(MainActivity.this,NoteDetailsActivity.class)) );
        menuBtn.setOnClickListener((v)->showMenu());
        setupRecyclerView();
    }

    void showMenu(){
        //TODO Display menu
    }

    void setupRecyclerView(){
        Query query = Utility.getCollectionReferenceForNotes().orderBy("timestamp",Query.Direction.DESCENDING);
        FirestoreRecyclerOptions<Note> options = new FirestoreRecyclerOptions.Builder<Note>()
                .setQuery(query,Note.class).build();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        noteAdapter = new NoteAdapter(options,this);
        recyclerView.setAdapter(noteAdapter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        noteAdapter.startListening();
    }

    @Override
    protected void onStop() {
        super.onStop();
        noteAdapter.stopListening();
    }

    @Override
    protected void onResume() {
        super.onResume();
        noteAdapter.notifyDataSetChanged();
    }
}

I think the other relevant codes is my NoteAdapter which is this:

package com.example.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;



import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;

import io.grpc.okhttp.internal.Util;

public class NoteAdapter extends FirestoreRecyclerAdapter<Note, NoteAdapter.NoteViewHolder>{
    Context context;

    public NoteAdapter(@NonNull FirestoreRecyclerOptions<Note> options, Context context) {
        super(options);
        this.context = context;
    }

    @Override
    protected void onBindViewHolder(@NonNull NoteViewHolder holder, int position, @NonNull Note note) {
        holder.titleTextView.setText(note.title);
        holder.contentTextView.setText(note.content);
        holder.timestampTextView.setText(Utility.timestamptoString(note.timeStamp));
    }

    @NonNull
    @Override
    public NoteViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_note_item,parent,true);
        return new NoteViewHolder(view);
    }

    class NoteViewHolder extends RecyclerView.ViewHolder{

        TextView titleTextView,contentTextView,timestampTextView;

        public NoteViewHolder(@NonNull View itemView) {
            super(itemView);
            titleTextView = itemView.findViewById(R.id.note_title_text_view);
            contentTextView = itemView.findViewById(R.id.note_content_text_view);
            timestampTextView = itemView.findViewById(R.id.note_timestamp_text_view);
        }
    }
}

Please tell me if there are any other relevant codes I can give to help give more context on my problem. Thanks for helping me out if anyone!

PHP/JS form validation

I’ve been creating full-stack app .
Using PHP for backend .
I’ve been added to the “welcome.php” file a HTML form redirecting user to a home page
But I’ve been currently stuck with form validation process .
Every time I press submit “ENTER” button it redirects me to another page automatically .
I’ve been tryed to set Alert() function in JS file if current input condition’s aren’t met .
Conditions are = if input length is less then 5 or greather than 13 it cannot be submitted .
Do anyone of more expirienced programmers got answer for me what to do here ?
My code :

enter image description here

Form Validation process PHP / JS need help

return a for loop in React functional component

I’m building my own invoice/estimate generator with React.

I want to have a number of lines “product” equivalent to my state.

I wanted to do a loop and return my JSX. But I have no error, but my line product appears once only, and my state is set to 2.

Here is my try :

export default function ProductInformations(props: TProductInformations) {
    const [numberOfProducts, setNumberOfProducts] = useState<number>(2);

    const handleNumberOfProducts = (type: string) => {
        if (type === "add") return setNumberOfProducts(numberOfProducts + 1);
        if (type === "remove") return setNumberOfProducts(numberOfProducts - 1);
    };

    for (let i = 0; i <= numberOfProducts; i++) {
        return (
            // here is <p> with "price", "quantity", "name of the product"...
        );
    }
}

As the JSX is a bit long, I don’t want to do a function that returns html and call the function in JSX.

Any idea why ?

Does using “Node.replaceChildren()” method for a HTMLElement will remove all the event listeners on the childern?

A div in which the HTML elements are cleared and added frequently. Approximately 2000 – 20000 elements are in the div and currently they are cleared by div.innerHTML = ”. I know it leaves all the event listeners. So I am searching for a safe alternative.

Also, I would be happy if you can suggest a blog or tutorial or book to know more about this DOM manipulation in deep.

Can’t add Loop to Drag Scroll Slider without breaking the dragging functionality

I’ve just followed this tutorial on Youtube to add a drag scroll to any scroll elements (https://www.youtube.com/watch?v=C9EWifQ5xqA&t=115s&ab_channel=WesBos) It worked and was extremely helpful. My only issue is I would like to apply this to multiple sliders on one page. I believe I have to create some form of ‘For Loop’ but I’m struggling to get anything working. Whenever I seem to add a For Loop it breaks the functionality and stops working.

Heres the JS I currently have which works.

var scrollSlider = document.querySelector(".scroll-slider1, .scroll-slider2");
let isDown = false;
let startX;
let scrollLeft;
 
scrollSlider.addEventListener('mousedown', (e) => {
    e.preventDefault();
    isDown = true;
    scrollSlider.classList.add('active');
    startX = e.pageX;
    scrollLeft = scrollSlider.scrollLeft;
});

scrollSlider.addEventListener('mouseleave', () => {
    isDown = false;
    scrollSlider.classList.remove('active');
});

scrollSlider.addEventListener('mouseup', () => {
    isDown = false;
    scrollSlider.classList.remove('active');
});

scrollSlider.addEventListener('mousemove', (e) => {
    e.preventDefault();
    if(!isDown) return;
    const x = e.pageX;
    const scroll = x - startX;
    scrollSlider.scrollLeft = scrollLeft - scroll;
});

Could anyone help me add some form of loop to this, so it gets applied to every drag slider on the page rather than just the first slider? Thanks.

Prevent two fixed components from overlapping

I have been struggling to make an element that I prepend to a page not overlap with the fixed component already existant on the page.

For example, you can execute the following in console on Stackoverflow :

const rootElement = document.createElement("div");
rootElement.id = "chrome-bar";


document.getElementsByTagName("body")[0].style["paddingTop"] = "40px";
document.getElementsByTagName("body")[0].style["position"] = "relative";

document.body.prepend(rootElement); rootElement.innerHTML="Hello World";rootElement.style="position:fixed;z-index:99999;top:0;background-color:black;width:100vw;color:white;"

As you can see, the black bar overrides the header tag, because of its position : fixed style. How could I have both of these bars (the one I create & the SO navbar) fixed and not overlap ? i.e. the behaviour that happens when you insert the same snippert on github (whose nav is not fixed)

Thanks a lot !

How to fix javascript onclick function

So, i have a login and register model. The login model has a close button that closes the model but it is not working for some reason.

Here is my html code

  <!DOCTYPE html>
  <html lang="en">
  <head>
    <link rel="shortcut icon" type="image/x-icon" href="/static/img/AdiAvi.png" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet">
      <link rel="stylesheet" href="/static/css/dashboard.css">
      <link rel="stylesheet" href="/static/css/base.css">
      <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>{{ title }}</title>
      {% if name %}
      <style>
        .trigger {
          display: none !important;
        }
        #loginButton {
          display: none !important;
        }
      </style>
      {% endif %}
  </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-dark fixed-top" style="background-color: rgb(0, 0, 0);">
      <a class="navbar-brand" href="/">
        <img class="ms-3" src="/static/img/AdiAvi.png" width="30" height="30" class="d-inline-block align-top" alt="">
        AdiAvi
      </a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav ms-auto mb-2 mb-lg-0 align-items-start align-items-lg-center">
          <li class="nav-item">
            <a {% if homePage %} class="nav-link active" {% endif %} {% if dashboardPage %} class="nav-link active" {% endif %} class="nav-link"  href="/">Home</a>
          </li>
          <li class="nav-item">
            <a  {% if support %} class="nav-link active" {% endif %} class="nav-link" href="/support">Support</a>
          </li>
          <li class="nav-item">
            <a {% if contactPage %} class="nav-link active" {% endif %} class="nav-link" href="/contact">Contact</a>
          </li>
          {% if baseTemplate %}
          <button type="button" id="loginButton" class="ms-2 btn btn-danger navbar-btn">
            Login
        </button>
          {% endif %}
          {% if baseTemplate %}
          <button type="button" id="registerTrigger" class="ms-2 me-2 btn btn-primary navbar-btn">
              Register
          </button>
          {% endif %}
          {% if name %}
          <li class="nav-item dropdown mb-0 otherDropdown ">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              <img src="/static/profilePictures/A.png" width="48" height="48" class="rounded-circle mt-8 mb-0">
            </a>
            <div style="background-color: #333;" class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdownMenuLink">
              <a style="color: white;" class="dropdown-item" href="/dashboard">Dashboard</a>
              <a style="color: white;" class="dropdown-item" href="/account">Edit Profile</a>
              {% if admin %}
              <a style="color: white;" class="dropdown-item" href="/admin">Admin</a>
              {% endif %}
              <a style="color: white;" class="dropdown-item" href="/logout">Log Out</a>
            </div>
          </li>
          {% endif %}   
        </ul>
      </div>
    </nav>
    <div class="modal" id="loginModel">
      <div class="loginModelContent">
        <span id="loginSpan" class="loginClose">&times;</span>
        <div style="position: relative; bottom: -10pc;" class="container-fluid">
      <div class="row no-gutter">
          <!-- The image half -->
          <div style="position: relative;" class="col-md-6 d-none d-md-flex bg-image">
            <h1 style="    position: fixed;
            bottom: 14pc;
            left: 22pc;
            font-size: 1.3pc;
            color: white;
        " >Start creating tasks today!</h1>
            <p style="    position: fixed;
            bottom: 12pc;
            left: 17pc;
            color: white;" >Create a task by clicking the + Button on your dashboard</p>
          </div>


          <!-- The content half -->
          <div class="col-md-6" style="background-color: #333;" >
              <div class="login d-flex align-items-center py-5">

                  <!-- Demo content-->
                  <div class="container">
                      <div class="row">
                          <div style="position: relative;  top: 1pc;" class="col-lg-10 col-xl-7 mx-auto">
                            <img class="adiavilogin" style="border-radius: 60px;" width="150" height="150" src="/static/img/AdiAvi.png">
                              <h3  style="color: #ffff;" class="display-4">Login</h3>
                              <p class="text-muted mb-4">Enter your user credentials to login</p>
                              <form method="POST" action="{{ url_for('login') }}">
                                  <div class="form-group mb-3">
                                      <label  style="color: white;" for="inputUsername">Username</label>
                                      <input style=" background-color: black; color: white;" id="inputUsername" name="username" type="text" placeholder="Username" required="" autofocus="" class="form-control rounded-pill border-0 shadow-sm px-4">
                                  </div>
                                  <div class="form-group mb-3">
                                    <label style="color: white;" for="inputPassword">Password</label>
                                      <input style="background-color: black; color: white;" id="inputPassword" name="password"  type="password" placeholder="Password" required="" class="form-control rounded-pill border-0 shadow-sm px-4">
                                  </div>
                                  <input type="submit" value="Sign In" class="btn btn-primary btn-block text-uppercase mb-2 rounded-pill shadow-sm buttonSizeInput form-control">
                                  <a  class="form-control" style="color:    #3366CC; background-color: transparent; border: none;" id="logintoRegister"><u>Don't have a account? Register!</u></a>
                              </form>
                          </div>
                      </div>
                  </div><!-- End -->

              </div>
          </div><!-- End -->

      </div>
  </div>-
      </div>
    </div>
    <div class="modal" id="registerModel">
      <div class="registerModelContent">
        <span class="registerClose">&times;</span>
        <div style="position: relative; bottom: -10pc;" class="container-fluid">
          <div class="row no-gutter">
              <!-- The image half -->
              <div style="position: relative;" class="col-md-6 d-none d-md-flex bg-image">
                <h1 style="    position: fixed;
                bottom: 14pc;
                left: 22pc;
                font-size: 1.3pc;
                color: white;
            " >Start creating tasks today!</h1>
                <p style="    position: fixed;
                bottom: 12pc;
                left: 17pc;
                color: white;" >Crete a task by clicking the + Button on your dashboard</p>
              </div>
      
      
              <!-- The content half -->
              <div class="col-md-6" style="background-color: #333;" >
                  <div class="login d-flex align-items-center py-5">
      
                      <!-- Demo content-->
                      <div class="container">
                          <div class="row">
                              <div style="position: relative;  top: 1pc;" class="col-lg-10 col-xl-7 mx-auto">
                                <img class="adiavilogin" style="border-radius: 60px;" width="150" height="150" src="/static/img/AdiAvi.png">
                                  <h3  style="color: #ffff;" class="display-4">Register</h3>
                                  <p class="text-muted mb-4">Create your account today!</p>
                                  <form method="POST" action="{{ url_for('register') }}">
                                    <div class="form-group mb-3">
                                      <label  style="color: white;" for="inputEmail">Email</label>
                                      <input style=" background-color: black; color: white;" id="inputEmail" name="email" type="text" placeholder="Email" required="" autofocus="" class="form-control rounded-pill border-0 shadow-sm px-4">
                                  </div>
                                      <div class="form-group mb-3">
                                          <label  style="color: white;" for="inputUsername">Username</label>
                                          <input style=" background-color: black; color: white;" id="inputUsername" name="username" type="text" placeholder="Username" required="" autofocus="" class="form-control rounded-pill border-0 shadow-sm px-4">
                                      </div>
                                      <div class="form-group mb-3">
                                        <label style="color: white;" for="inputPassword">Password</label>
                                          <input style="background-color: black; color: white;" id="inputPassword" name="password"  type="password" placeholder="Password" required="" class="form-control rounded-pill border-0 shadow-sm px-4">
                                      </div>
                                      <input type="submit" value="Sign In" class="btn btn-primary btn-block text-uppercase mb-2 rounded-pill shadow-sm buttonSizeInput form-control">
                                      <a  class="form-control" style="color:    #3366CC; background-color: transparent; border: none;" id="registerTrigger"><u>Already have an account? Login!</u></a>
                                  </form>
                              </div>
                          </div>
                      </div><!-- End -->
      
                  </div>
              </div><!-- End -->
      
          </div>
      </div>
      </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
  <script src="/static/js/base.js" defer></script>
  {% block main %}
  {% endblock %}

Lets go take a look where it shows span with the id=loginSpan in the login model section.
I made a simple onclick javascript function when that X is cicked(also this is a external javascript file and it file linking thing is shown at the end of the code. The file is called base.js.

Here is my simple js code:

var loginSpan = document.getElementById("loginSpan");
var loginModel = document.getElementById("loginModel");

loginSpan.onclick = function() {
  loginModel.style.display = "none";
}

For some reason whenever i click the X nothing is happening.

I tried going on console.log and doing it there and it was working fine, so i first thought that the items where not getting called. So when i linked the script i putted defer at the end.

I thought that this would work, but instead nothing happend.

How to subtract two values on a get request in MongoDB and check the result against another number?

On a get request, I am trying to go to the Mongo database, access two existing keys (todaysDateMs and lastClickedMs) and subtract the two values of each key. Once I have that value I want to check if it is gte to 172800000 and then set the streak key to have a value of 0 if that evaluates to true.

The below code is what I currently have (and works) without any addition of the logic I am trying to implement.

app.get('/', (req, res) => {
         let todaysDate = new Date().toString().split(' ').slice(0, 4).join(' ')
         let todaysDateMs = new Date(todaysDate + ', 00:00:00').getTime()

         habitsCollection.updateMany({}, {
            $set: {
               todaysDate,
               todaysDateMs
            }
         }).then(res => {
            habitsCollection.updateMany({ lastClicked: { $ne: todaysDate } }, {
               $set: {
                  clicked: 'false'
               }

         habitsCollection.find().toArray()
            .then(results => {
               let filtered = results.filter(result => result.clicked === 'false')
               habitsLeft = filtered.length
               res.render('index.ejs', { habits: results, dayVar: 'days', habitsLeft })
            })
      })

I have been trying to play around with something like this (I know the syntax isn’t correct), adding another .then with another updateMany. I think I also need to use another operator in front of $subtract but not sure what.

.then(res => {
habitsCollection.updateMany({ $subtract:["$todaysDateMs", "$lastClickedMs"] } { $gte: 172800000 }, {
                   $set: {
                      streak: 0
                   }
                })}

how do i map a 2d array in to a matrix of card componants in react js and mui componants

i am given a 2d array of objects and i need to create form it a matrix of cards every card will have some text which is taken from the object and i used the .map fuction but the result for the following array

[[obj1,obj2,obj3],[obj4,obj5,obj6],[obj7,obj8,obj9]]
is

this is my code

export defult function Content() {
     return(
       <Grid>
       {DUMMY_DATA.map((obj) => {
         return (
          <Grid item sm={4} sx={{m:1}}>
           <assetCard
           key={obj.id}
           id={obj.id}
           name={obj.text}
          />
         </Grid>
      )
    })}
  </Grid>
 );
}

how to use forEach() on nested objects in an array

I’m working on a browser quiz project. I have made an array of objects that has the question choices nested in a further object. I’m struggling to figure out how to compare the users choice of the 4 options to the correct answer in the answers array. I’m stuck because I don’t know how to use for each on nested objects inside an array.
I could use some advice or a better way to accomplish the same goal

`var list = document.createElement("ol");
var li1 = document.createElement("li");
var li2 = document.createElement("li");
var li3 = document.createElement("li");
var li4 = document.createElement("li");

let choices = document.querySelector(".choices")

choices.appendChild(list)
list.appendChild(li1)
list.appendChild(li2)
list.appendChild(li3)
list.appendChild(li4)

let possibleAnswers = ["1", "2", "3", "4", "5", "6", "7"]

let questionPool = [
    {
        questionOne:
    {
            answers: 
        {
            answerOne:li1,
            answerTwo:li2,
            answerThree:li3,
        answerFour:li4
        }
} 
},
{
    questionTwo:
    {
        answers: 
        {
        answerOne:li1,
        answerTwo:li2,
        answerThree:li3,
        answerFour:li4
        }
} 
},
{
    questionThree:
    {
        answers: 
        {
        answerOne:li1,
        answerTwo:li2,
        answerThree:li3,
        answerFour:li4
        }
} 
},
{
    questionFour:
    {
        answers: 
        {
        answerOne:li1,
        answerTwo:li2,
        answerThree:li3,
        answerFour:li4
        }
} 
},
{
    questionFive:
    {
        answers: 
        {
        answerOne:li1,
        answerTwo:li2,
        answerThree:li3,
        answerFour:li4
        }
} 
},
{
    questionSix:
    {
        answers: 
        {
        answerOne:li1,
        answerTwo:li2,
        answerThree:li3,
        answerFour:li4
        }
} 
},
{
    questionSeven:
    {
        answers: 
        {
        answerOne:li1,
        answerTwo:li2,
        answerThree:li3,
        answerFour:li4
        }
} 
} ]`

Change the value of checkbox using text input in React JS

I have a form with a group of checkboxes and a text input, the text input allows the user to change the last checkbox value that displays the input. This is done because the last checkbox original value shouldn’t appear in the response, there should be the value from the checkbox.

import "./styles.css";
import {
  Controller,
  useFormContext,
  FormProvider,
  useForm
} from "react-hook-form";
import { useState } from "react";

export const Component = ({ name, ITEMS }) => {
  const { control, getValues, setValue, watch } = useFormContext();
  const [state, setState] = useState(false);
  const [value, setV] = useState("");
  const allValues = watch(name) || [];

  console.log(allValues);
  // setValue(`${name}[6]`, allValues.group)
  const handleCheck = (val) => {
    const { [name]: ids } = getValues();

    const response = ids?.includes(val)
      ? ids?.filter((id) => id !== val)
      : [...(ids ?? []), val];

    return response;
  };

  // useEffect(() => {
  //   const a = document.getElementsByName('test')[0]
  //   a.value = 'demo';
  //   console.log(a)
  // },[])

  return (
    <Controller
      name={name}
      control={control}
      render={({ field, formState }) => {
        return (
          <>
            {ITEMS.map((item, index) => {
              return (
                <>
                  <label>
                    {item.id}
                    <input
                      type="checkbox"
                      name={`${name}[${index}]`}
                      onChange={(e) => {
                        field.onChange(handleCheck(e.target.value));
                        if (index === ITEMS.length - 1) {
                          setState(e.target.checked);
                        }
                      }}
                      value={index === ITEMS.length - 1 ? value : item.value}
                    />
                  </label>
                  {state && index === ITEMS.length - 1 && (
                    <input
                      onChange={(e) => {
                        const a = document.getElementsByName(
                          `${name}[${ITEMS.length - 1}]`
                        )[0];
                        a.value = e.target.value;
                        setV(e.target.value);
                      }}
                      type="text"
                    />
                  )}
                </>
              );
            })}
          </>
        );
      }}
    />
  );
};

Here:

 <input
                      onChange={(e) => {
                        const a = document.getElementsByName(
                          `${name}[${ITEMS.length - 1}]`
                        )[0];
                        a.value = e.target.value;
                        setV(e.target.value);
                      }}
                      type="text"
                    />

… i change the last checkbox value, also i used this approach but this does not help: value={index === ITEMS.length - 1 ? value : item.value}.
Question: How to fix the issue and to display the value of the text input as the last checkbox value?
demo: https://codesandbox.io/s/brave-kowalevski-etpe3w?file=/src/Component.js

Reactjs app crashes when changing value using a slider

I’m trying to update a value that is using in the useEffect() method using a slider that uses UseState.

When I move the slider though this error is thrown:

react-dom.development.js:22839 Uncaught DOMException: Failed to execute 'createMediaElementSource' on 'AudioContext': HTMLMediaElement already connected previously to a different MediaElementSourceNode.
    at /static/js/bundle.js:119:33
    at commitHookEffectListMount (/static/js/bundle.js:27763:30)
    at commitPassiveMountOnFiber (/static/js/bundle.js:29256:17)
    at commitPassiveMountEffects_complete (/static/js/bundle.js:29228:13)
    at commitPassiveMountEffects_begin (/static/js/bundle.js:29218:11)
    at commitPassiveMountEffects (/static/js/bundle.js:29208:7)
    at flushPassiveEffectsImpl (/static/js/bundle.js:31093:7)
    at flushPassiveEffects (/static/js/bundle.js:31045:18)
    at commitRootImpl (/static/js/bundle.js:31004:9)
    at commitRoot (/static/js/bundle.js:30787:9)

react-dom.development.js:18687 The above error occurred in the <AudioManipulator> component:
    at AudioManipulator (/static/js/bundle.js:92:5)
    at div
    at VideoPlayer (/static/js/bundle.js:683:65)
    at App
Consider adding an error boundary to your tree to customize error handling behavior.
Visit * to learn more about error boundaries.

react-dom.development.js:12056 Uncaught DOMException: Failed to execute 'createMediaElementSource' on 'AudioContext': HTMLMediaElement already connected previously to a different MediaElementSourceNode.
    at /static/js/bundle.js:119:33
    at commitHookEffectListMount (/static/js/bundle.js:27763:30)
    at commitPassiveMountOnFiber (/static/js/bundle.js:29256:17)
    at commitPassiveMountEffects_complete (/static/js/bundle.js:29228:13)
    at commitPassiveMountEffects_begin (/static/js/bundle.js:29218:11)
    at commitPassiveMountEffects (/static/js/bundle.js:29208:7)
    at flushPassiveEffectsImpl (/static/js/bundle.js:31093:7)
    at flushPassiveEffects (/static/js/bundle.js:31045:18)
    at commitRootImpl (/static/js/bundle.js:31004:9)
    at commitRoot (static/js/bundle.js:30787:9)

CanvasManipulator.jsx:39 Uncaught TypeError: Cannot read properties of null (reading 'getContext')
    at applyFilter (CanvasManipulator.jsx:39:1)

This is happening using latest Google Chrome. I suppose it’s creating a new media element and Chrome only allows for one, else it would just clone the sound. I tried using it in firefox and had no issues – but it kept duplicating the sound.

I don’t know how I can store the AudioContext and just re-use it; I’ve been sitting on this issue for almost one hour and cant think of a way to fix it (yes, I read the docs, but I didn’t understand much because I’m inexperienced :/ )

Can anyone please help me resolve this issue?
This is my code:

import { useEffect, useState } from 'react';

function AudioManipulator({ videoRef }) {
    var [_bitSamples, setBitSamples] = useState(7);
    const [_bitcrushNormFrequency, setBitcrushNormFrequency] = useState(0.2);
    const [_distortion, setDistortion] = useState(0);
    const [_bassBoost, setBassBoost] = useState(0);
    const [_gain, setGain] = useState(1);

    function handleResetClick() {
        setBitSamples(0);
        setBitcrushNormFrequency(1);
        setDistortion(0);
        setBassBoost(0);
        setGain(1);
    }

    const context = new AudioContext();

    function handlePlay() {
        context.resume();
    }

    useEffect(() => {
        const video = videoRef.current;
        video.onplay = handlePlay;
        return () => {
          video.onplay = null;
        }
      }, []);

    useEffect(() => {
        const videoElement = videoRef.current;
        const audioSource = context.createMediaElementSource(videoElement);

        //bitcrush
        var bufferSize = 4096;
        var bitcrush = (function () {
            var node = context.createScriptProcessor(bufferSize, 1, 1);
            node.bits = _bitSamples; // between 1 and 16
            node.normfreq = _bitcrushNormFrequency; // between 0.0 and 1.0
            var step = Math.pow(1 / 2, node.bits);
            var phaser = 0;
            var last = 0;
            node.onaudioprocess = function (e) {
                var input = e.inputBuffer.getChannelData(0);
                var output = e.outputBuffer.getChannelData(0);
                for (var i = 0; i < bufferSize; i++) {
                    phaser += node.normfreq;
                    if (phaser >= 1.0) {
                        phaser -= 1.0;
                        last = step * Math.floor(input[i] / step + 0.5);
                    }
                    output[i] = last;
                }
            };
            return node;
        })();

        // create distortion
        var dist = context.createWaveShaper();
        // 0 bis 100 funktioniert sehr gut, ist aber egal
        dist.curve = makeDistortionCurve(_distortion);

        // create filter
        var filter = context.createBiquadFilter();
        filter.type = "lowshelf";
        filter.frequency.value = 200;
        filter.gain.value = _bassBoost;

        // gain
        var gain = context.createGain();
        gain.gain.value = _gain;

        // chain effects - first effect in chain is actually last
        audioSource.connect(gain);
        gain.connect(dist);
        dist.connect(bitcrush);
        bitcrush.connect(filter);
        filter.connect(context.destination);

        function makeDistortionCurve(amount) {
            var k = typeof amount === 'number' ? amount : 0,
                n_samples = 44100,
                curve = new Float32Array(n_samples),
                deg = Math.PI / 180,
                i = 0,
                x;
            for (; i < n_samples; ++i) {
                x = i * 2 / n_samples - 1;
                curve[i] = (3 + k) * x * 40 * deg / (Math.PI + k * Math.abs(x));
            }
            return curve;
        };
    }, [_bassBoost, _bitSamples, _bitcrushNormFrequency, _distortion, _gain, context, videoRef]);

//TODO: implement user control for audio filters

    return (
        <div>
            <label>Bitcrush Bit-Reduction</label>
            <input type="range" min="0" max="16" step="1" value={_bitSamples} onChange={e => {setBitSamples(e.target.value)}}/>
            <label>Bitcrush Norm.-Frequency</label>
            <input type="range" min="0" max="1" step="0.01"/>
            <label>Distortion</label>
            <input type="range" min="0" max="100" step="0.1"/>
            <label>Bass Boost</label>
            <input type="range" min="0" max="100" step="1"/>
            <label>Gain</label>
            <input type="range" min="0" max="10" step="0.01"/>
            <label>Reset Sound FX</label>
            <input type="button" value="Reset" onClick={(handleResetClick)}></input>
        </div>
    );
}

export default AudioManipulator;

I tried checking if the audioSource already exists, and if it does to not inizialize it. Didn’t work.