sort objects from API

I’ve got this object
I want to show it in apexchart
and need to be sort from lables

 [
        {
            "lable": "(0, 2)",
            "value": 0
        },
        {
            "lable": "(15, 20)",
            "value": 9.090909090909092
        },
        
        {
            "lable": "(4, 6)",
            "value": 9.090909090909092
        },
        
        {
            "lable": "(8, 12)",
            "value": 9.090909090909092
        }
    ]

How to open/save multiple pdf pages with jspdf and html2canvas package?

I’m struggling to save/open in a new tab a pdf document with more than one page. It works fine with only one page, but with more than one, it doens’t work. I did it with for loop but somehow in the pdf document always appears just the first page. I use this package: https://www.npmjs.com/package/jspdf-html2canvas?activeTab=readme

Can you tell me why doesn’t work with the for loop? It doesn’t matter how much page I have, for example in the success function defined action is called only once and only one function. If I remove the comment by the window.open(pdf.output('bloburl')), then the addPage() function isn’t called. Also the addPage just add empty pages to the jsPD object, also 4 pages instead of 3.

Thanks in advance!

Here is the code:

const btn = document.getElementById('btn');
const pages = document.querySelectorAll('.page');
btn.addEventListener('click', async () => {
    let jsPD = new jsPDF();

    // one page
    // html2PDF(pages, {
    //     jsPDF: {
    //         format: 'a4',
    //         dpi: 400,
    //     },
    //     imageType: 'image/jpeg',
    //     output: 'my.pdf',
    //     html2canvas: {
    //         scrollX: 0,
    //         scrollY: -window.scrollY,
    //         scale: 5,
    //         dpi: 400,
    //         quality: 4,
    //     }, margin: {
    //         top: 24,
    //         right: 24,
    //         bottom: 24,
    //         left: 24,
    //     },
    //     success: function (pdf) {
    //         // pdf.save(this.output)
    //         window.open(pdf.output('bloburl'))
    //     }
    // });


    // more page version
    for await (const page of pages) {
        console.log(page)
        const pdf = await html2PDF(page, {
            jsPDF: {
                format: 'a4',
                dpi: 400,
            },
            imageType: 'image/jpeg',
            output: 'my.pdf',
            html2canvas: {
                scrollX: 0,
                scrollY: -window.scrollY,
                scale: 5,
                dpi: 400,
                quality: 4,
            }, margin: {
                top: 24,
                right: 24,
                bottom: 24,
                left: 24,
            },
            success: function (pdf) {
                // pdf.save(this.output)
                // window.open(pdf.output('bloburl'))
                jsPD.addPage(pdf.output())
            }
        });
    }

    window.open(jsPD.output('bloburl'))

});
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<button id="btn">Generate</button>
<div class="page" style="width: 210mm;color: black;background: white; margin: 0 auto">
    <div class="">
        <h3 style="margin: 0">PDF for Test</h3>
        <img src="assets/img2.jpg" style="max-width: 100%" alt="">
        <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam cupiditate dolores est,
            pariatur perferendis
            quia quis quos recusandae similique veritatis Ad delectus doloremque est fugit id molestias nesciunt, qui
            tenetur?
        </div>
    </div>
    <div class="break-before">
        <p style="margin: 0">Here is some content for testing!!</p>
        <h3>PDF for Test</h3>
        <img src="assets/img2.jpg" style="max-width: 100%" alt="">
        <p style="margin: 0">Here is some content for testing!!</p>
        <h3 style="margin: 0">PDF for Test</h3>
    </div>
    <div class="break-before">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam cupiditate dolores est,
        pariatur perferendis
        quia quis quos recusandae similique veritatis! Ad delectus doloremque est fugit id molestias nesciunt, qui
        tenetur?
    </div>
</div>

<div class="page" style="width: 210mm;color: black;background: white; margin: 0 auto">
    <div class="">
        <h3 style="margin: 0">PDF for Test</h3>
        <img src="assets/img2.jpg" style="max-width: 100%" alt="">
        <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam cupiditate dolores est,
            pariatur perferendis
            quia quis quos recusandae similique veritatis Ad delectus doloremque est fugit id molestias nesciunt, qui
            tenetur?
        </div>
    </div>
    <div class="break-before">
        <p style="margin: 0">Here is some content for testing!!</p>
        <h3>PDF for Test</h3>
        <img src="assets/img2.jpg" style="max-width: 100%" alt="">
        <p style="margin: 0">Here is some content for testing!!</p>
        <h3 style="margin: 0">PDF for Test</h3>
    </div>
    <div class="break-before">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam cupiditate dolores est,
        pariatur perferendis
        quia quis quos recusandae similique veritatis! Ad delectus doloremque est fugit id molestias nesciunt, qui
        tenetur?
    </div>
</div>

<div class="page" style="width: 210mm;color: black;background: white; margin: 0 auto">
    <div class="">
        <h3 style="margin: 0">PDF for Test</h3>
        <img src="assets/img2.jpg" style="max-width: 100%" alt="">
        <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam cupiditate dolores est,
            pariatur perferendis
            quia quis quos recusandae similique veritatis Ad delectus doloremque est fugit id molestias nesciunt, qui
            tenetur?
        </div>
    </div>
    <div class="break-before">
        <p style="margin: 0">Here is some content for testing!!</p>
        <h3>PDF for Test</h3>
        <img src="assets/img2.jpg" style="max-width: 100%" alt="">
        <p style="margin: 0">Here is some content for testing!!</p>
        <h3 style="margin: 0">PDF for Test</h3>
    </div>
    <div class="break-before">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam cupiditate dolores est,
        pariatur perferendis
        quia quis quos recusandae similique veritatis! Ad delectus doloremque est fugit id molestias nesciunt, qui
        tenetur?
    </div>
</div>
</body>
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/html2canvas.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jspdf-html2canvas@latest/dist/jspdf-html2canvas.min.js"></script>

<!--pure jspdf-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.debug.js"></script>

<script src="main.js"></script>
</html>

CORS error only when I use endpoint with basic auth

I have a server on which cors is configured. I can access regular endpoints calmly without any errors, but I have problems with basic auth endpoints. I make the following request to the server:

axios.post(process.env.REACT_APP_BE_URL + "/api/admin",{}, {
      headers: {
        Authorization: 'Basic ' + btoa(`${login}:${password}`)
      }
})

As a result I get this error:
Access to XMLHttpRequest at ‘http://localhost:8080/api/admin’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
Once again I repeat that with the rest of the endpoint I do not get such an error.

I tried using a proxy in my package.json file that solved the problem but not as much as I would like in the future it will cause other problems and I would like to do without the proxy.

npm init -y do not create package.json file

I am trying to create a package.json file following a tutorial and they say to create a file in vs code and then write npm init -y (just to add default values to get to know npm-s) and this should create a package.json file but I only receive the package.json values in the terminal and there is no file in the explorer window where it should be.

I search this problem but have no success so far.
Does anyone had the same problem or know what I should do to fix that?

Role of JavaScript in web development and other relevant technologies

As I begin my journey into web develpoment, I’m curious to understand the role of JavaScript in building websites. While I understand that HTML provides the structure of a web page and CSS used for styling, I’m unsure of what specific purposes Javascript serves.

What is the purpose of JavaScript in web development?
Are there any specific use cases or scenarios where JavaScript is required for building a website alongside HTML and CSS, or can website be built only with HTML and CSS?

I would appreciate any examples that can help me better understand it.
Thank you!

Validation de Status [closed]

Estoy tratando de hacer una validación de estado con nodejs y mongodb, si el estado es “no verificado” no debería poder acceder, sin embargo, si el estado es “verificado” me permite acceder a la cuenta. nota: El estado se guarda en la base de datos

Mi código de verificación es este (controlador)

exports.usuario_verify = function (req, res) { 
  let usuario = req.body.username;
  let pass = req.body.password;
  let datos = "Usuario: " + usuario + " Pass: " + pass;
  if (usuario && pass) {
    //Hay datos en usuario y password
    User.find({ Username: usuario, Password: pass }, function (error, results) {
      if (error) {
        let data = {
          title: "Ingreso al sistema",
          message: "Hubo un error contacte a soporte",
        };
        res.render("login", data);
      }

      if (results.length > 0) {
        let roles;
        results.forEach((element) => {
          roles = element.Roles;
        });
        req.session.usuario = usuario;
        req.session.role = roles;
        if (roles === "admin") {
          res.render("admin_home");
        } else if (roles === "user") {
          res.render("coleccion"); //next();
        }
      } else {
        let data = {
          title: "Ingreso al sistema",
          message: "Usuario o contraseña no son correctos",
        };
        res.render("login", data);
      }
    });
  } else {
    let data = {
      title: "Ingreso al sistema",
      message: "Usuario o contraseña no son correctos",
    };
    res.render("login", data);
   
    
}};

exports.usuario_add = function (req, res) {
  res.send("Ruta controlada");
};

Estoy tratando de hacer una validación de estado con nodejs y mongodb, si el estado es “no verificado” no debería poder acceder, sin embargo, si el estado es “verificado” me permite acceder a la cuenta. nota: El estado se guarda en la base de datos

Comment button functionality only appears on latest post and not all

I am creating a post system for a social media site, and there is a comment button. However, when I click the comment button, it is meant to dropdown an input and only does it for one post, and not all. How can I make it display across all posts functionally?

          <hr class="">
            <div class="mb-3">
      <!-- Comment section goes here -->
      <style>
        .comment-form {
          transition: all 0.3s ease-in-out;
          max-height: 0;
          overflow: hidden;
        }

        .comment-form.active {
          max-height: 500px;
        }
      </style>
      <a href="javascript:void(0)" class="comment-btn" data-post-id="<?php echo $row["post_id"]; ?>">
        <i class="fa fa-comments" style="color: black;"></i>
      </a>

      <hr>
      <form method="POST" action="" enctype="multipart/form-data" class="comment-form" id="comment-form-<?php echo $row["post_id"]; ?>">
        <div class="form-group">
          <textarea class="form-control rounded-0" id="comment_text" placeholder="Leave a comment here:" name="comment_text" rows="" style="margin-top: 10px;"></textarea>
          <?php if (isset($error) && !empty($error)): ?>
            <span class="text-danger">  <?php echo $error; ?></span>
          <?php endif; ?>
        </div>
        <div class="d-flex justify-content-end">
          <button type="submit" class="post-comment-btn">Post Comment</button>
        </div>
        <input type="hidden" name="post_id" value="<?php echo $row["post_id"]; ?>">
      </form>
    </div>

  <script>
    const commentBtns = document.querySelectorAll('.comment-btn');
    const commentForms = document.querySelectorAll('.comment-form');

    commentBtns.forEach((btn) => {
      const postId = btn.getAttribute('data-post-id');
      const form = document.querySelector(`#comment-form-${postId}`);

      btn.addEventListener('click', () => {
        form.classList.toggle('active');
      });
    });
  </script>

  <?php
  $post_id = $row["post_id"];
  $sql_comments = "SELECT comments.*, users.username, users.profile_picture_url, users.verified, users.display_name FROM comments INNER JOIN users ON comments.user_id = users.user_id WHERE comments.post_id = '$post_id' ORDER BY comments.created_date ASC";
  $result_comments = $conn->query($sql_comments);
  if ($result_comments->num_rows > 0) {
    while ($row_comments = $result_comments->fetch_assoc()) {
      $comment_username = "@" . $row_comments["username"];
      $comment_verified = $row_comments["verified"];
      $comment_profile_picture_url = $row_comments["profile_picture_url"];
      $comment_display_name = $row_comments["display_name"];
      $comment_date = $row_comments["created_date"];
      $comment_text = $row_comments["comment_text"];
  ?>```

How do I prevent textarea from replacing  ?

I use a textarea as a transfer field to store a HTML template of an external REST application, which unfortunately can only be read manually. This template must not be modified, otherwise the REST function will fail.

Unfortunately, the textarea changes the   to a real space. Is it possible to disable this behavior? I can’t escape the template before because as I said it is read manually and copied to the field.

And even if I somehow escaped it when inserting it with javascript, the template must not be changed and also contains already escaped sequences. If I remove those after saving, there are problems as well.

<!DOCTYPE html>
<html>
<body>
    <textarea>This&nbsp;is&nbsp;a&nbsp;test!</textarea>
</body>
</html>

Hide every element under a div

            <div class="Title">
              <div class="SubTitle">
                <p>Text</p>
                <h1>Text2</h1>
              </div>
            </div>
            <div class="Title">
              <div class="SubTitle">
                <p>Text</p>
                <h1>Text2</h1>
              </div>
            </div>
            <div class="Title">
              <div class="SubTitle">
                <p>Text</p> 
                <h1>Text2</h1>
              </div>
            </div>

I’m looking for a way I can hide each <p></p> and show <h1></h1> instead on click of a button (onclick="javascript hide <p> show <h1>), and vise versa. I could do it with unique id but I cannot assign the same id for each. Is there any way to do it? preferably without jquery.

Map over State or prevState in setState?

I have an array of objects which I want to loop through and reset the selected value for each item to false:

// Amount data state
const [amountData, setAmountData] = useState([
  {
    id: 30,
    amount: (30000).toLocaleString(),
    selected: true,
  },
  {
    id: 10,
    amount: (10000).toLocaleString(),
    selected: true,
  },
  {
    id: 70,
    amount: (70000).toLocaleString(),
    selected: true,
  },
  {
    id: 50,
    amount: (50000).toLocaleString(),
    selected: true,
  },
]);

What I was wondering is if the correct way of updating the state in setState is to loop through the current state directly (amountData) or loop through the prevState and if either way would have any benefit over the other method?

Using state directly:

// Reset selection
setAmountData(
  amountData.map(amount => {
    return {
      ...amount,
      selected: false,
    };
  }),
);

Using prevState:

// Reset selection
setAmountData(prevState =>
  prevState.map(amount => {
    return {
      ...amount,
      selected: false,
    };
  }),
);

How to render the component individually

Hi i am new to the react , on the below code when i click the increment button , it run the loop and increment the count with 10. As of known if state changes it render the component , when i click increment button i able to see render message in console for only one time , for efficiency react collect all the changes and render only one time . but i don’t want this , i need to see render message 10 times while clicking increment button. can you please help me on this.

import { Fragment, useReducer, useRef, useState,useMemo, useEffect } from "react"



export default function Sample()
{
   console.log("render")
   const [counter,setcount]=useState(0)
   const increment =()=>{
      for(let i=0;i<5;i++){
       setcount((prevcount)=>prevcount+1)
       setcount((prevcount)=>prevcount+1)
      }
   }
   return(
    <>
      <p>{counter}</p>
      <button onClick={increment}>increment</button>
   </>
   )
    
}

node-gyp error –(Unable to install the node Modules)

npm ERR! code 1
npm ERR! git dep preparation failed
npm ERR! command /Users/swrajkant/.nvm/versions/node/v18.12.1/bin/node /Users/swrajkant/.nvm/versions/node/v18.12.1/lib/node_modules/npm/bin/npm-cli.js install --force --cache=/Users/swrajkant/.npm --prefer-offline=false --prefer-online=false --offline=false --no-progress --no-save --no-audit --include=dev --include=peer --include=optional --no-package-lock-only --no-dry-run
npm ERR! npm WARN using --force Recommended protections disabled.
npm ERR! npm WARN deprecated [email protected]: Deprecated due to CVE-2021-21366 resolved in 0.5.0
npm ERR! npm WARN deprecated [email protected]: this library is no longer supported
npm ERR! npm WARN deprecated [email protected]: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm ERR! npm WARN deprecated [email protected]: request has been deprecated, see https://github.com/request/request/issues/3142
npm ERR! npm ERR! code 1
npm ERR! npm ERR! path /Users/swrajkant/.npm/_cacache/tmp/git-clonewdiwAS/node_modules/java
npm ERR! npm ERR! command failed
npm ERR! npm ERR! command sh -c -- node-gyp rebuild
npm ERR! npm ERR! gyp info it worked if it ends with ok
npm ERR! npm ERR! gyp info using [email protected]
npm ERR! npm ERR! gyp info using [email protected] | darwin | x64
npm ERR! npm ERR! gyp info find Python using Python version 3.6.15 found at "/Users/swrajkant/.pyenv/versions/3.6.15/bin/python3"
npm ERR! npm ERR! gyp WARN install got an error, rolling back install
npm ERR! npm ERR! gyp ERR! configure error 
npm ERR! npm ERR! gyp ERR! stack Error: ENOENT: no such file or directory, stat '/tmp/node-v16.13.2-headers.tar.gz'
npm ERR! npm ERR! gyp ERR! System Darwin 21.6.0
npm ERR! npm ERR! gyp ERR! command "/Users/swrajkant/.nvm/versions/node/v18.12.1/bin/node" "/Users/swrajkant/.nvm/versions/node/v18.12.1/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
npm ERR! npm ERR! gyp ERR! cwd /Users/swrajkant/.npm/_cacache/tmp/git-clonewdiwAS/node_modules/java
npm ERR! npm ERR! gyp ERR! node -v v18.12.1
npm ERR! npm ERR! gyp ERR! node-gyp -v v9.1.0
npm ERR! npm ERR! gyp ERR! not ok

I tried almost every way, by changing the version of node and the version of python and almost every solution present on the internet, but nothing worked.

How to target v-model for DOM manipulation?

I just started learning Vue and wanted to use it with Laravel and Bootstrap. I’m learning it by trying to create a simple CRUD. Right now I’m still stuck on the Bootstrap Validation part. I want to give “is-invalid” class to every input so that the invalid input field becomes red.

I can do that by using this code to catch each field that has the class “form-control” and name of the error field, and then give each of those field “is-invalid” class:

        methods: {
        async storeData() {
            const response = await this.form.post('/api/products-and-solutions')
                .then(() => {
                    console.log('Berhasil') // ignore this
                })
                .catch(error => {
                    let errors = error.response.data.errors;

                    for (error in errors) {
                        errors[error].forEach(element => {
                            document.querySelector(`.form-control[name="${error}"]`).classList.add('is-invalid')
                        });
                    }
                })
        }

This is my form:

                <form @submit.prevent="storeData" @keydown="form.onKeydown($event)">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="system" class="form-label">System</label>
                        <input type="text" class="form-control" name="system" v-model="form.system">
                        <HasError :form="form" field="system" />
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea class="form-control" name="description" v-model="form.description" rows="3"></textarea>
                        <HasError :form="form" field="description" />
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <Button :form="form" class="btn btn-primary">
                        Store Data
                    </Button>
                </div>
            </form>

This works great and all. But I don’t want to create a “name” attribute just for that purpose. I want to learn new thing and try to use what I already have, which is “v-model”. The problem is if I try to use:

        methods: {
        async storeData() {
            const response = await this.form.post('/api/products-and-solutions')
                .then(() => {
                    console.log('Berhasil') // ignore this
                })
                .catch(error => {
                    let errors = error.response.data.errors;

                    for (error in errors) {
                        errors[error].forEach(element => {
                            document.querySelector(`.form-control[v-model="form.${error}"]`).classList.add('is-invalid')
                        });
                    }
                })
        }
    }

It will throw and error:

Uncaught (in promise) TypeError: document.querySelector(…) is null

My question is, how can I target the v-model ?

Highcharts chart re-render

I am using Highcharts to display a series of data in a form of chart. I am displaying the data into three chart formats – Area chart, Line chart and Bar chart. Defaulty the page will load to Area chart, On button click I will load the line chart and Bar chart respectively. When I change my chart type with a button click, the chart width increases by 25px exactly.

Is there any method in highcharts to re-render the graph. I hope by re-rendering I can fix this Issue. Because I used timeout to clear and re-render the DOM. But timeout is not the good way to do that. So If there is any re-render method in highcharts, Kindly share.