Script inside Template won’t execute on Import

I am learning about templates, custom elements, shadow DOM, etc. Here, I like to utilize Swiper lib to create custom element that i can compose as i wish in the future. It works when everything is one file as follows:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <title>Swiper demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" />

  <template id="TmplCoverflowSwiper">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css" />
    <style>
      html,
      body {
        position: relative;
        height: 100%;
      }

      body {
        background: #eee;
        font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
        font-size: 14px;
        color: #000;
        margin: 0;
        padding: 0;
      }

      .swiper {
        width: 100%;
        padding-top: 50px;
        padding-bottom: 50px;
      }

      .swiper-slide {
        background-position: center;
        background-size: cover;
        width: 300px;
        height: 300px;
      }

      .swiper-slide img {
        display: block;
        width: 100%;
      }
    </style>
    <div class="swiper mySwiper">
      <div class="swiper-wrapper">
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-1.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-2.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-3.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-4.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-5.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-6.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-7.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-8.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-9.jpg" />
        </div>
      </div>
      <div class="swiper-pagination"></div>
    </div>
    <script>
       (async () => {
          // <!-- Swiper JS -->
          const { Swiper } = await import("https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.mjs");
          console.log('swiper-bundle imported...')

          // <!-- Initialize Swiper -->
          var swiper = new Swiper(".mySwiper", {
            effect: "coverflow",
            grabCursor: true,
            centeredSlides: true,
            slidesPerView: "auto",
            coverflowEffect: {
              rotate: 50,
              stretch: 0,
              depth: 100,
              modifier: 1,
              slideShadows: true,
            },
            pagination: {
              el: ".swiper-pagination",
            },
          });

          console.log('swiper initiated...');
        }
        )();
    </script>
  </template>

  <script>
    class CoverflowSwiper extends HTMLElement {
      constructor() {
        super(); // always call super() first
      }

      /** Custom Component Reactions **/
      connectedCallback() {
        console.log("Coverflow-Swiper  connected to page");

        //set initial state of visiable
        this.visible = this.hasAttribute('visible');

        //make deep copy of the template and import into the current document
        let tmpl = document.querySelector("#TmplCoverflowSwiper");
        let newNode = document.importNode(tmpl.content, true);

        // document.getElementById("PCCoverflowSwiper").appendChild(newNode);
        this.appendChild(newNode);
      }
    }

    //link custom element w/ JS class
    customElements.define("pc-coverflow-swiper", CoverflowSwiper);
 
  </script>

</head>

<body>
  <h1>Making Swiper Web Component</h1>
  <pc-coverflow-swiper id="PCCoverflowSwiper">
  </pc-coverflow-swiper>
</body>
</html>

However, i like to keep things separate and when i move out all the code pertained to my custom element into a separate file that is imported in the main file, suddenly the JS script part of the template scope won’t execute and i cann’t seem to understand why it is so, just by removing into separate file?

The main file containing custom element tag while stripped out the rest into file tmpl-swiper.html and imported here in the head here:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <title>Swiper demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" />

    <!-- include the polyfill for web components. This must precede imports -->
    <script src="../polyfills/webcomponents-lite.js"></script>

    <!-- import our template from an external file -->
    <link rel="import" href="tmpl-swiper.html" id="tmplCoverflow">
</head>

<body>
  <h1>Making Swiper Web Component</h1>
  <pc-coverflow-swiper id="PCCoverflowSwiper">
  </pc-coverflow-swiper>
</body>
</html>

Here is the imported template file taken out from the main file into separate file all pertained to the custom element with name tmpl-swiper.html:

html,
body {
position: relative;
height: 100%;
}

  body {
    background: #eee;
    font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
    font-size: 14px;
    color: #000;
    margin: 0;
    padding: 0;
  }

  .swiper {
    width: 100%;
    padding-top: 50px;
    padding-bottom: 50px;
  }

  .swiper-slide {
    background-position: center;
    background-size: cover;
    width: 300px;
    height: 300px;
  }

  .swiper-slide img {
    display: block;
    width: 100%;
  }
</style>
<div class="swiper mySwiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-1.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-2.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-3.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-4.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-5.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-6.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-7.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-8.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-9.jpg" />
    </div>
  </div>
  <div class="swiper-pagination"></div>
</div>
<script>
   (async () => {
      // <!-- Swiper JS -->
      const { Swiper } = await import("https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.mjs");
      console.log('swiper-bundle imported...')

      // <!-- Initialize Swiper -->
      var swiper = new Swiper(".mySwiper", {
        effect: "coverflow",
        grabCursor: true,
        centeredSlides: true,
        slidesPerView: "auto",
        coverflowEffect: {
          rotate: 50,
          stretch: 0,
          depth: 100,
          modifier: 1,
          slideShadows: true,
        },
        pagination: {
          el: ".swiper-pagination",
        },
      });

      console.log('swiper initiated...');
    }
    )();
</script>

(function() {
class CoverflowSwiper extends HTMLElement {
constructor() {
super(); // always call super() first
}

  /** Custom Component Reactions **/
  connectedCallback() {
    console.log("Coverflow-Swiper  connected to page");

    //set initial state of visiable
    this.visible = this.hasAttribute('visible');

    //make deep copy of the template and import into the current document
    let tmpl = document.querySelector("#TmplCoverflowSwiper");
    let newNode = document.importNode(tmpl.content, true);

    // document.getElementById("PCCoverflowSwiper").appendChild(newNode);
    this.appendChild(newNode);
  }
}

//link custom element w/ JS class
customElements.define("pc-coverflow-swiper", CoverflowSwiper);

// automatically add the template 
//  to the document that is importing this file so it can be used.

// ownerDocument references this component document being imported
var thisImportDoc = document.currentScript.ownerDocument;

// Get the template from this file, clone it,
// and append it to the importing document.
var tmplNode = thisImportDoc.querySelector('#TmplCoverflowSwiper');

// the "document" keyword here references the "main" document
// (the one that's importing this HTML file)
document.body.appendChild(tmplNode.cloneNode(true));

})();

It imports the file, attaches the template, etc, however. the JS code within the Template tag isn’t executed and i can’t seem to understand the reason. Any help much appriciated. thank you

Why JS don’t show the last message in Telegram? [duplicate]

I am writing a chrome extension. I want to know the user’s last message in a telegram conversation. Here is my code:

js:

function getLastMessage() {
    const messages = document.querySelectorAll('.Message'); 

    if (messages.length > 0) {
        const lastMessage = messages[messages.length - 1];
        const messageText = lastMessage.querySelector('.text')?.innerText || "Нет текста";
        
        alert("Last message:", messageText);
 
    } else {
        alert("There are no messages");
    }
}
document.getElementById('myButton').addEventListener('click', function() {
    getLastMessage();
});

json:

{
    "manifest_version": 3,
    "name": "My Simple Button Extension",
    "version": "1.0",
    "description": "An extension with a single button.",
    "action": {
      "default_popup": "popup.html",
      "default_icon": "icon.webp"
    },
    "permissions": []
  }

This code alert “There are no messages” always but there are messages in chat.
Please, help me.

I can’t find anything in web

A way via functions to reverse the order of an array, using .sort() (need help explaining solution) [duplicate]

I’m new to javascript – I just had a problem that asked me to find a way via functions to reverse the order of an array of years, using .sort(). After flailing for a bit, I checked the answer and received the one below:

const sortYears = arr => arr.sort((x, y) => y - x);

I have no idea how someone would get this, or where the x and y come from.

I tried using sort() and nesting Collections.reverseOrder() as suggested in another answer to a similar question, but kept receiving errors.

Input type file – filelist, is always empty in partial view that is inside a partial view

I was able to get the filelist when the element was in the view > partialview1. But i had to change the interface a little bit so, it got moved to, View > partialview1 > partialview2. After this change, the filelist is always 0. What am i doing wrong? can anyone explain why this behaviour? I also tried setting timeout to the attachmentpartial js but it made no difference. Kindly guide.

Index controller

    public class ProjectDashboardController : Controller
    {
        public IActionResult Index()
        {
            try
            {
                ProjectListModel resultSet = _context.tblProjects.where(x => x.appid == 1).ToList();
                return View(resultSet);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        

        
        //get project list
        public IActionResult GetProjDetails(int projectid)
        {
            ProjecDetModel resultSet = _context.tblProjDetails.where(x => x.projectid == projectid).ToList();
            return View("~/Views/ProjectDashboard/_projDetails.cshtml", resultSet); //return partial view with object
        }
        
        public IActionResult GetAttachments(int pid){
            ProjAtt att = _context.tblProjAttachments.where(x => x.projectid = pid).ToList();
            return View("~/Views/ProjectDashboard/_AttachmentPartial.cshtml", att); //return partial view with object
            
        }
        
    }

Index page/view

    @model ProjectListModel

    <div class="form-group" style="display:flex;">
        <partial name="~/Views/Projs/_projList.cshtml" model="@Model" /> @* project list table *@
    </div>

_projList.cshtml

    @model ProjectListModel
    
    @foreach(var item in Model)
    {
        <a asp-controller="ProjectDashboard" asp-action="GetProjDetails" asp-route-projectid="@item.ProjectID">
            <i class="bi bi-search" title="View project details" onclick="showLoadingSpinner();"></i> @* project details page *@
            @item.ProjectName
        </a>
    }

_projDetails.cshtml

    @model ProjecDetModel
    //other code
    <div class="partialContent" id="AttachmentsContainerDiv" data-url="/APP/ProjectDashboard/GetAttachments?pid=1">
    </div>

_AttachmentPartial.cshtml

    @model ProjAtt

    <label class="bi bi-paperclip" onchange="fileAttached(@Model.ProjectID);">
        <input type="file" id="uploadFile" style="display: none;" multiple>
    </label>
    @foreach(var item in Model)
    {
        @item.attName
    }

site.js

    function fileAttached(pjid) {
        var files = document.getElementById('uploadFile').files; //get the attached files                        
        //THIS IS NOT WORKING
        console.log(files);
    }

BUT THIS IS WORKING

_projDetails.cshtml

    @model ProjecDetModel

    <label class="bi bi-paperclip" onchange="fileAttached(@Model.ProjectID);">
        <input type="file" id="uploadFile" style="display: none;" multiple>
    </label>
    
    
    //other code
    <div class="partialContent" id="AttachmentsContainerDiv" data-url="/APP/ProjectDashboard/GetAttachments?pid=1">
    </div>

_AttachmentPartial.cshtml

    @model ProjAtt

    @foreach(var item in Model)
    {
        @item.attName
    }

site.js

    
    $(document).on('change', '#uploadFile', function () {
        var file = $(this)[0]; // note the [0] to return the DOMElement from the jQuery object

        fileAttached(file.files);
        console.log(file.files[0]);
    });


    function fileAttached(files) {
        console.log(files); //THIS IS WORKING
    }

How to unify calendar timeslots in Javascript

I have a reservation calendar in my app that allows customers to make reservations in empty time slots. The calendar is also used by non-customer personnel who can make overlapping reservations in the calendar.

In order to avoid the customers from making overlapping reservations, I want to block out the overlaps in their view and only show single occurrances. The picture below shows what I am after:

calendar reservations

The left column shows the view of the personnel who can make overlapping reservations, the right view is what the customers should see. The customers are thus not allowed to make reservations in the smaller empty slots.

How can I achieve this with Javascript? I tried for loops which are comparing start and end times, but I ended up banging my head against the wall… And I am bound to solving this in the front-end, as I have no control over the back-end.

How to merge first column in html table using java script [closed]

I m using html table .I need to merge the row if rows have repeated values.
below is my code

function myFunction() {
  const previousRow = {};
  const colsChanged = {};
  let dark = false;

  Array.from(document.querySelectorAll('tbody tr')).forEach((tr, rowIdx) => {
    Array.from(tr.children).forEach((td, colIdx) => {
      if (rowIdx > 0 && previousRow[colIdx].text === td.innerText) {
        previousRow[colIdx].elem.setAttribute('rowspan', ++previousRow[colIdx].span);
        colsChanged[colIdx] = false;
        td.remove();

      } else {
        previousRow[colIdx] = {
          span: 1,
          text: td.innerText,
          elem: td,
          dark
        };
        colsChanged[colIdx] = true;
      }
    });
    const rowChanged = Object.values(colsChanged).every(Boolean);
    dark = rowChanged && rowIdx > 0 ? !dark : dark;
    if (dark) {
      // tr.classList.add('dark');
    }
  });
}
<body onload="myFunction()">
  <table class="table table-bordered" id="rejecteddetails" style="border-collapse: separate;empty-cells: hide;">
    <thead>
      <tr>
        <th class="text-center">
          S.No
        </th>
        <th class="text-center">Reason</th>
        <th class="text-center">Rejected By</th>
        <th style="white-space: nowrap;">Rejected Date</th>
        <th class="text-center">Response</th>
        <th class="text-center" style="white-space: nowrap;">Response Added By</th>
        <th class="text-center" style="white-space: nowrap;"> Response Added Date</th>
      </tr>
    </thead>
    <tbody id="rejected_reason_table">
      <tr>
        <td>1</td>
        <td>minimum thickness 25</td>
        <td>Testing</td>
        <td>2024-12-19 at 07:15 AM</td>
        <td>NA</td>
        <td>NA</td>
        <td>NA</td>
      </tr>
      <tr>
        <td>2</td>
        <td>wrong thickness value</td>
        <td>Test</td>
        <td>2024-12-18 at 11:12 PM</td>
        <td>corrected thickness. </td>
        <td>Test</td>
        <td>12-19-2024 at 12:53 AM</td>
      </tr>
      <tr>
        <td>3</td>
        <td>wrong thickness value</td>
        <td>Test</td>
        <td>2024-12-18 at 11:12 PM</td>
        <td>thickness value corrected and submitted . </td>
        <td>Test</td>
        <td>12-19-2024 at 02:02 AM</td>
      </tr>
      <tr>
        <td>4</td>
        <td>wrong thickness value</td>
        <td>Test</td>
        <td>2024-12-18 at 11:12 PM</td>
        <td>cannot update the value . value is static</td>
        <td>Test</td>
        <td>12-19-2024 at 06:59 AM</td>
      </tr>
    </tbody>
  </table>
</body>

Merging is working fine ,but I dont need to display 3, 4 in S.No column .I need to display only 2 because 2,3,4 are merged .

Javascript fetch return 403 on Apache Server

Struggling with this issue for a few days now so any help is greatly appreciated.

I managed to deploy my django project on a Linux server and it works fine apart from the model form submit. On the local development server it work fine and here is the workflow:

  1. User fills the form;
  2. User clicks submit;
  3. Javascript catches the submit event, submits a “POST” request and gets a response back;
  4. On the server side, the form is checked and if all is good an email is sent;
  5. HTML is updated to add the confirmation of form registration;

Here is my code:

home.html

    <div class="col-lg-8 offset-lg-2">
    <form method="POST" class="row mt-17" id="form" onsubmit="return false">
        {% csrf_token %}
        {% for field in form %}
        {% if field.name not in "message" %}
        <div class="col-12 col-sm-6">
            <div class=form-group>
                <label for={{field.name}} class="form-label">{{ field.label }}</label>
                {{ field }}
            </div>
        </div>
        {% else %}
        <div class="col-12">
            <div class=form-group>
                <label for={{field.name}} class="form-label">{{ field.label }}</label>
                {{ field }}
            </div>
        </div>
        {% endif %}
        {% endfor %}
        <div class="form-group mb-0">
            <button type="submit" class="btn btn-primary btn-lg">Submit</button>
        </div>
    </form>
</div>

main.js

const form = document.getElementById('form');
form.addEventListener("submit", submitHandler);
function submitHandler(e) {
    e.preventDefault();
    fetch("{% url 'messages-api' %}", {
        credentials: "include",
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new FormData(form)
    })
    .then(response => response.json())
    .then(data => {
        alert("Got your message")
        })

}

ssl.conf file

    <Directory /home/admin/pinpoint/templates>
            Require all granted
    </Directory>

    Alias /static /home/admin/pinpoint/static
    <Directory /home/admin/pinpoint/static>
            Require all granted
    </Directory>

    Alias /media /home/admin/pinpoint/media
    <Directory /home/admin/pinpoint/media>
            Require all granted
    </Directory>

    <Directory /home/admin/pinpoint/project>
            <Files wsgi.py>
                    Require all granted
            </Files>
    </Directory>

    WSGIScriptAlias / /home/admin/pinpoint/project/wsgi.py
    WSGIDaemonProcess pinpoint python-path=/home/admin/pinpoint python-home=/home/admin/pinpoint/venv
    WSGIProcessGroup pinpoint

On the development server, whenever you click submit, I get 403 (Forbidden) in the console.

Since the development version works fine, my guess would be it’s a permission issue. As such, I gave apache ownership and r+w rights in my templates folder. Still the issue persists.

If i remove the headers content in the fetch command, the form is registered in the database but after ~2 minutes I get Server Error(500).

Any help/suggestions are welcome.

API stops working on Express server side randomly

This is my server code:

import express from 'express';
import cors from 'cors';
import axios from 'axios';

const app = express()
const port = 3000;
app.use(cors());

app.get('/', async(req, res) => {
    await axios.get("<functional URL confirmed>")
        .then(response => {
            console.log(response.data);
        })
})

app.listen(port, () => {
    console.log(`App listening at http://localhost:${port}`);
});

The above code sometimes works perfectly and logs the data as expected. Most other times however, it outputs a very long error that looks something like this:

Error Screenshots:

enter image description here

enter image description here

Changed absolutely NOTHING in my code, just re-ran after a minute or so, and:

enter image description here

What I have already tried to solve this:

  • Checked my internet connection and speed. Everything is a-ok.
  • Checked my API quota. I am not violating it. I know because I can npm run dev my frontend which uses that api with the same url and output the same data with no errors even while I see this error on the backend
  • Checked the URL. I know it’s correct because of the same reason as above.
  • Tried waiting for a minute before re-running the same code. It worked. Then I ran it again. Didn’t work.
  • Assumed it was a time limit thing. Wrong. Waited for 15 minutes before re-running, still didn’t work.
  • Cut and pasted the same URL again just to change something. Data logged successfully.
  • Re-ran the code. Error again.

I don’t know what’s causing this erratic behaviour.

In case anyone wonders why I’m even using an Express server when the API can be called directly in my React frontend, it’s because this preliminary call isn’t causing issues but some other stuff on the same URL is giving me CORS errors. However the url I’m using here to test my server-side code is the same one that is definitely functional in the frontend.

Can someone please explain what is going on behind the scenes?

NPM Errors when trying to run scripts

Whenever I try to install an NPM module or run scripts I get several error messages

When I enter npm run dev I get this message:

npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /home/hc/northcoders/projects/exhibition-curation-platform/package.json
npm ERR! errno -2
npm ERR! enoent Could not read package.json: Error: ENOENT: no such file or directory, open '/home/hc/northcoders/projects/exhibition-curation-platform/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent 

npm ERR! A complete log of this run can be found in: /home/hc/.npm/_logs/2024-12-20T15_26_19_111Z-debug-0.log

here’s the log file:

0 verbose cli /home/hc/.nvm/versions/node/v21.6.2/bin/node /home/hc/.nvm/versions/node/v21.6.2/bin/npm
1 info using [email protected]
2 info using [email protected]
3 timing npm:load:whichnode Completed in 1ms
4 timing config:load:defaults Completed in 1ms
5 timing config:load:file:/home/hc/.nvm/versions/node/v21.6.2/lib/node_modules/npm/npmrc Completed in 1ms
6 timing config:load:builtin Completed in 1ms
7 timing config:load:cli Completed in 1ms
8 timing config:load:env Completed in 0ms
9 timing config:load:file:/home/hc/northcoders/projects/exhibition-curation-platform/.npmrc Completed in 0ms
10 timing config:load:project Completed in 1ms
11 timing config:load:file:/home/hc/.npmrc Completed in 0ms
12 timing config:load:user Completed in 0ms
13 timing config:load:file:/home/hc/.nvm/versions/node/v21.6.2/etc/npmrc Completed in 0ms
14 timing config:load:global Completed in 0ms
15 timing config:load:setEnvs Completed in 0ms
16 timing config:load Completed in 5ms
17 timing npm:load:configload Completed in 5ms
18 timing config:load:flatten Completed in 1ms
19 timing npm:load:mkdirpcache Completed in 0ms
20 timing npm:load:mkdirplogs Completed in 1ms
21 verbose title npm run dev
22 verbose argv "run" "dev"
23 timing npm:load:setTitle Completed in 1ms
24 timing npm:load:display Completed in 0ms
25 verbose logfile logs-max:10 dir:/home/hc/.npm/_logs/2024-12-20T15_26_19_111Z-
26 verbose logfile /home/hc/.npm/_logs/2024-12-20T15_26_19_111Z-debug-0.log
27 timing npm:load:logFile Completed in 17ms
28 timing npm:load:timers Completed in 0ms
29 timing npm:load:configScope Completed in 0ms
30 timing npm:load Completed in 35ms
31 timing command:run Completed in 1ms
32 verbose stack Error: Could not read package.json: Error: ENOENT: no such file or directory, open '/home/hc/northcoders/projects/exhibition-curation-platform/package.json'
32 verbose stack     at async open (node:internal/fs/promises:633:25)
32 verbose stack     at async readFile (node:internal/fs/promises:1242:14)
32 verbose stack     at async PackageJson.load (/home/hc/.nvm/versions/node/v21.6.2/lib/node_modules/npm/node_modules/@npmcli/package-json/lib/index.js:129:31)
32 verbose stack     at async PackageJson.normalize (/home/hc/.nvm/versions/node/v21.6.2/lib/node_modules/npm/node_modules/@npmcli/package-json/lib/index.js:115:5)
32 verbose stack     at async RunScript.run (/home/hc/.nvm/versions/node/v21.6.2/lib/node_modules/npm/lib/commands/run-script.js:72:27)
32 verbose stack     at async module.exports (/home/hc/.nvm/versions/node/v21.6.2/lib/node_modules/npm/lib/cli-entry.js:61:5)
33 verbose cwd /home/hc/northcoders/projects/exhibition-curation-platform
34 verbose Linux 6.8.0-49-generic
35 verbose node v21.6.2
36 verbose npm  v10.2.4
37 error code ENOENT
38 error syscall open
39 error path /home/hc/northcoders/projects/exhibition-curation-platform/package.json
40 error errno -2
41 error enoent Could not read package.json: Error: ENOENT: no such file or directory, open '/home/hc/northcoders/projects/exhibition-curation-platform/package.json'
42 error enoent This is related to npm not being able to find a file.
42 error enoent
43 verbose exit -2
44 timing npm Completed in 76ms
45 verbose code -2
46 error A complete log of this run can be found in: /home/hc/.npm/_logs/2024-12-20T15_26_19_111Z-debug-0.log

Fairly sure this only started happening after following some instructions online to fix a bluetooth problem on my laptop – had no idea what I was doing

running Node 10.2.4 on Ubuntu 22.04

Any help would be much appreciated,

Thanks

I am making a password checker for an admin login page it doesn’t when it should on paper [closed]

So I am making a login page for my website for admins and it has just one set password and it worked but when I tried to check if it would kick me out and it just sends me to the Admin page and not asking me for a password

this is my code:

</head>
    <body>
        <h1>This is Admin only</h1>
        <form id="password">
            <input type="password" name="Admin password" id="ADMIN_PASS">
        </form>
        <script>
            var password = "password"
            if (password = "ADMINPASS"){
                var password = 0
                location.href='ADMIN.html'
            }else{
                print('incorrect')
                location.href='Adminlogin.html'
            }
            

            
        </script>

MutationObserver() vs DOMNodeInserted [duplicate]

I’m having trouble wrapping my head around MutationObserver(). I have an old snippet using DOMNodeInserted which has been depreciated.

The following is a scaled down illustration.

Example

       var d = $(document);

       // DOM Injection/Addition
       d.on('DOMNodeInserted', '*', function (e) {
           $('.ct-cont'    , e.target).addClass('bg-light m-0 p-0 w-100')
           $('.fa-solid'   , e.target).addClass('fa-fw')
           $('.ct-input'   , e.target).css('font-family', 'Courier New');
           return false;
       });

Any assistance would be appreciated and rewarded.

js multistep onboarding fail b/c CSRF token

I purchased a well known nice admin UI for an app i’m building in Rails so that I can focus on building instead of UI which is not my strong suit. This app requires multistage onboarding. What I discovered is that everything is being thrown off by the CSRF token Rails inserts into forms, a hidden input tag and it just feels insane. While I am competent in many programming languages I have had bubonic avoidance for js. The UI team has decided I should disable CSRF for registration which seems stupid to me.

the CSRF token looks something like this:

<input type="hidden" name="authenticity_token" value="LilF6KgbBR7MBSruMcWFKyMOz_pnmcGzmiyxAm2aVDIvurHbA_uxcOqVNfB4NZbKPc7KzDoD8MGWpJAh7ErcDQ" autocomplete="off" />

The steps are wrapped by the form that roughly looks like the below and the js refreshes the UI to cycle through onboarding stages the view is roughly like this, trying my best to abbreviate it, mixing html and erb because this is a js issues:

<form class="my-auto pb-5" novalidate="novalidate" id="kt_create_account_form">
     <input type="hidden" name="authenticity_token" value="LilF6KgbBR7MBSruMcWFKyMOz_pnmcGzmiyxAm2aVDIvurHbA_uxcOqVNfB4NZbKPc7KzDoD8MGWpJAh7ErcDQ" autocomplete="off" />
     <%= render "reg_step1" %>
     <%= render "reg_step2" %>
     <%= render "reg_step3" %>
     <%= render "reg_step4" %>
     <%= render "reg_step5" %>
     <%= render "registration_actions" %>
</form>

The partials are basically divs wrapping the onboarding steps with a class marking the content for each step. That are queried by js in the following way:

var el = parent.querySelectorAll('[data-stepper-element="content"]');

and then the UI is refreshed based on the step.

I had hoped that I could filter out the one input tag so that it doesn’t break the the multistage registration, because even when I test this as just pure html and js, that one input tag messes everything up.

I tried to do the following:

[...parent.querySelectorAll(query)]
                    .filter(function(element) {
                        return element.name !== 'authenticity_token' && element.type !== 'hidden';
                    });

to no avail. Is there anything obvious from this so far? How on earth is this one CSRF input tag which is before the queries divs wreaking complete havoc like this? Help would be greatly appreciated.

WordPress Elementor Pro Gallery not loading images – Bundle webpack file versions are different?

In WordPress, Elementor Pro, I have a Gallery. The photos suddenly stopped showing.

From the JS Console it shows:

Uncaught (in promise) ChunkLoadError: Loading chunk gallery failed.

In the folder wp-content/plugins/elementor-pro/assets/js:

There is a file: gallery.805130d33e18cb04635f.bundle.js

But server is asking for gallery.b7d55bc976e04f751975.bundle.js

Is this a webpack issue? How do I resolve this please?

I tried clearing the cache, and Elementor Regenerate CSS and data, but no luck so far.

I did reinstall a plugin this morning: Powerpack Lite for Elementor

Any ideas on how to solve this?

Calling other script to post after other funcation

I want to call other script to start running every 1 second after the first one is called,

but am having a problem the above script doesn’t report any error in browser and its not working. it only do post call to first function.

but doesn’t call other one after is called

I want the first call to do post after then call other one to also do a post call, run every 1 second or call file2 every 1 second

and then when it reaches 5min do not do any post call on file2(stop calling)

<script>
            function Fun_1() {
                ("#MkB").click(function (event) {
                    Execute();
                });

                function Execute() {
                    .ajax({
                        type: "POST",
                        url: "file",
                        data: {
                            
                            textnum: ("input[name='textnum']").val(),
                           
                        },

                        beforeSend: function () {
                            if (("form input[name='textnum']").val() == "") {
                                ("#error").text("action needed.");
                                return false;
                            }
                            
                        },

                        complete: function () {
                            ("#error").hide();
                            
                        },

                        success: function (response) {
                            myVa = setTimeout(() => {
                                clearTimeout(myVar);
                            }, 300000);
                            setTimeout(Fun_2, 3000);
                        },
                        error: function () {
                            alert("Something has Happened");
                        },
                    });
                }
            }

            function Fun_2() {
                myVar = setTimeout(Fun_2, 1000);
                timeout: 300000,
                .ajax({
                    type: "POST",
                    url: "file2",                    
                    success: function (res) {
                         var Rmsg = res.msgEnd;
                        ("#FeMsg_1").html(res.msg);
                        
                        if (Rmsg == 'Complete') {
                         clearTimeout(myVar);
                         clearTimeout(myVa);
                    },
                });
            }

            (document).ready(function () {
                Fun_1();
            });
        </script>