I am working in wordpress issue with java script overlay

I am working in wordpress elemnetor. I have a requirement to achieve. On header i have a search button when click on it overlay open with search bar i am using ivory search in this
thats image of search option

[My html code for overlay thats code i have inside html widget](https://i.sstatic.net/7oqAy4eK.png)

code of java script

my requirement is when click on search bar overlay close and i got result on my web site but i am getting result inside overlay

please help me

How to use pdf.js locally

I have a locally running web app in which I would like to extract data from a pdf. pdf.js would work well for this, but it uses modules, which causes cross origin request errors for the file: protocol. Running a local web server gets around the CORS issue, but is too complicated of a task for my users. Is there a way to adjust the code for pdf.js to have it run locally?

locally-installed PDF.JS does not render asked the same question over five years ago, but the answer is two major versions out of date: loading a module as a regular js file doesn’t work because of the slightly differing syntax (export becomes a keyword).

Building PDF.js says that npx gulp generic-legacy will generate build/generic/build/pdf[.worker].js (possibly also npx gulp generic; “this” isn’t clear). This statement appears to be incorrect, as running those commands creates the .mjs files, not .js files.

I think this answer means that what I want can be accomplished using Webpack or Rollup, but the answer doesn’t specify how, and I haven’t been able to figure that out.

(I will be having my users <input> the file using the html widget, so the fact that the pdf is local isn’t a problem.)

A sample of working code is:

<!doctype html>
<html lang="en-US">
    <head>
        <meta charset="utf-8">
        <title>pdf.js test</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.9.155/pdf.min.mjs" type="module"></script>
<!-- works with all schemes, but pdf.js is remote -->
<!--<script src="pdf.js" type="module"></script>-->
<!-- local pdf.js doesn't work with file:// scheme -->
<!--<script src="pdf.js"></script>-->
<!-- Uncaught SyntaxError: Cannot use 'import.meta' outside a module -->
    </head>
    <body>
        <input id="fileUploader" type="file">
        <p>Number of pages: <span id="pageCount"></span></p>
    </body>
    <script>
        //const pdfjsLib = require('pdf.js');
        document.getElementById('fileUploader').addEventListener('change', ({target}) => {
            //pdfjsLib.GlobalWorkerOptions.workerSrc = 'pdf.worker.js';
            pdfjsLib.GlobalWorkerOptions.workerSrc =
                `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.mjs`;
            const reader = new FileReader();
            reader.addEventListener('load', async () => {
                const buffer = reader.result;
                const pdf = await pdfjsLib.getDocument({ data: new Uint8Array(buffer) }).promise;
                const numPages = pdf.numPages;
                document.getElementById('pageCount').textContent = numPages;
            });
            reader.readAsArrayBuffer(target.files[0]);
        });
    </script>
</html>

AgGrid – Filter is not getting applied if applied immediately after data update

I am using ag grid and every 5 seconds I am updating the data using async Transaction. I have configured the filter in such a way that, when user clicks on Apply, then only filter needs to be applied on the UI.
I am facing two problems.

Problem 1: (Refer to Figure 1) On the grid, already a filter exist on Portfolio column with value as Defensive. Now I am interacting with the filter popup, I have selected new filter value=Aggressive, but not clicked on the Apply button. But grid is getting updated with the new selected filter values when the data gets updated in the background which I don’t want. The filter should get applied only when user clicks on Apply button.

My solution: (Refer to Figure 2)To overcome this, I can store the grid filter model before the data update, and then reapply it after the transaction gets completed. But it introduces a new problem, i.e., on applying the existing filter, the Aggressive filter value gets automatically unselected after the data update (since it was not present on the filter model that I stored before the data update). This will definitely create a bad user experience.

Figure 1

enter image description here

Figure 2

enter image description here

Problem 2: (Refer to Figure 3) On the grid, already a filter exist on Portfolio column with value as Defensive. Now on the filter popup, I have selected a new filter value=Aggresive, and then if I click on Apply immediately after the transaction gets completed, the grid is not getting updated with the new filter, but the filter gets applied on the next data update. I am not able to find a solution for this.

Figure 3

enter image description here

You can check here if you want to see what I am facing: [Playground link][1]

Prisma / tRPC + MongoDB error in AWS Lambda

I have an app that uses a tRPC server, connected to MongoDB using Prisma as an ORM. It is deployed as an AWS Lambda function. When querying my ‘engagements’ collection, I was returned with this error:

[{
    "error": {
        "message": "nInvalid `prisma.engagement.findMany()` invocation:nnnInconsistent query result: Field provider is required to return data, got `null` instead.",
        "code": -32603,
        "data": {
            "code": "INTERNAL_SERVER_ERROR",
            "httpStatus": 500,
            "stack": "PrismaClientUnknownRequestError: nInvalid `prisma.engagement.findMany()` invocation:nnnInconsistent query result: Field provider is required to return data, got `null` instead.n    at ni.handleRequestError (/deps/7ff9aebb-6d47-4d1b-83c7-7897efd7b0b7/node_modules/@prisma/client/runtime/library.js:124:6989)n    at ni.handleAndLogRequestError (/deps/7ff9aebb-6d47-4d1b-83c7-7897efd7b0b7/node_modules/@prisma/client/runtime/library.js:124:6206)n    at ni.request (/deps/7ff9aebb-6d47-4d1b-83c7-7897efd7b0b7/node_modules/@prisma/client/runtime/library.js:124:5926)n    at u (/deps/7ff9aebb-6d47-4d1b-83c7-7897efd7b0b7/node_modules/@prisma/client/runtime/library.js:129:10023)n    at <anonymous> (/private/var/folders/dm/3qghyfj90ms6jkp3p4284c_r0000gn/T/tmpsehwqwof/trpc.ts:287:20)n    at u8.middlewares (/deps/7ff9aebb-6d47-4d1b-83c7-7897efd7b0b7/node_modules/@trpc/server/dist/index.mjs:420:30)n    at i (/deps/7ff9aebb-6d47-4d1b-83c7-7897efd7b0b7/node_modules/@trpc/server/dist/index.mjs:456:32)n    at i (/deps/7ff9aebb-6d47-4d1b-83c7-7897efd7b0b7/node_modules/@trpc/server/dist/index.mjs:456:32)n    at H (/deps/7ff9aebb-6d47-4d1b-83c7-7897efd7b0b7/node_modules/@trpc/server/dist/index.mjs:486:24)n    at O4H (/deps/7ff9aebb-6d47-4d1b-83c7-7897efd7b0b7/node_modules/@trpc/server/dist/resolveHTTPResponse-cd1a9112.mjs:46:22)",
            "path": "getPendingPreEngagements"
        }
    }
}]

Relevant chunk from my tRPC appRouter code:

  getPendingPreEngagements: privateProcedure.query(async ({ ctx }) => {
    console.log("getPendingPreEngagements");

    if (!ctx.isSuperUser) {
      throw new TRPCError({ message: "Unauthorized", code: "UNAUTHORIZED" });
    }
    const result = await ctx.prisma.engagement.findMany({
      where: {
        status: {
          in: [
            "PreEngagementFlaggedForReview",
            "ApplicationSubmitted",
            "PreEngagementRejected",
            "ReportStarted",
          ],
        },
      },
      orderBy: { preEngagement: { fields: { created_at: "desc" } } },
      include: {
        provider: {
          include: { org: true },
        },
      },
    });
    return result.filter((a) => !a.preEngagement.approval_type);
  }),

The output of ‘npm ls prisma’ locally:

[email protected] /Users/julien/Developer/elicensing-prisma
├─┬ @prisma/[email protected]
│ └── [email protected] deduped
└── [email protected]

npm ls ‘@prisma/client’:

[email protected] /Users/julien/Developer/elicensing-prisma
└── @prisma/[email protected]

And in the tRPC dir:

[email protected] /Users/julien/Developer/elicensing/trpc/api
├─┬ @prisma/[email protected]
│ └── [email protected] deduped
└── [email protected]
[email protected] /Users/julien/Developer/elicensing/trpc/api
└── @prisma/[email protected]

I am using node v18, prisma v5.6.0, and @trpc/server v10.43.3

I tried to replicate this locally using this code, separate from the tRPC function:

const { PrismaClient } = require('@prisma/client');
const fs = require('fs');

const prisma = new PrismaClient();

async function getPendingPreEngagements() {
  console.log("getPendingPreEngagements");

  try {
    const result = await prisma.engagement.findMany({
      where: {
        status: {
          in: [
            "PreEngagementFlaggedForReview",
            "ApplicationSubmitted",
            "PreEngagementRejected",
            "ReportStarted",
          ],
        },
      },
      orderBy: { preEngagement: { fields: { created_at: "desc" } } },
      include: {
        provider: {
          include: { org: true },
        },
      },
    });

    return result.filter((a) => !a.preEngagement.approval_type);
  } catch (error) {
    console.error("Error:", error);
  } finally {
    await prisma.$disconnect();
  }
}

async function main() {
  const filteredResult = await getPendingPreEngagements();
  fs.writeFileSync('pendingPreEngagements.json', JSON.stringify(filteredResult, null, 2));
}

main()

I encountered the same issue locally, until I downgraded both ‘prisma’ and ‘@prisma/client’ from 6.1.0 to 5.6.0. Since then, the issue disappeared and I could successfully pull engagements.

I tried to replicate this in the tRPC server by deleting the node_modules folder and changing the prisma and @prisma/client versions in package.json from “^5.6.0” to just “5.6.0” like I did with the separate function. I built and deployed the server using AWS SAM, but I am still encountering the same issue.

I checked the code from the AWS SAM build folder and it only refers to prisma version 5.6.0 as it should.

If anybody has any suggestions as to why the Lambda function is behaving like this then please let me know! Any help is greatly appreciated.

Thanks in advance!

How do I write a json file using the fs module after I have packaged my app using electron builder

I am working on a project which involves writing a json file in the app directory, in a file called
‘data’ and the name of the json file is ‘data.json’. Here is my code:


const { app, BrowserWindow, ipcMain, Menu} = require('electron');
const path = require('path')
const fs = require('fs');

const dataDir = path.join(__dirname, 'data');
const accountsFile = path.join(dataDir, 'data.json');

async function createDirectoryAndFile() {
    try {
        // Check if the directory exists
        const dirExists = await fs.promises.access(dataDir).then(() => true).catch(() => false);

        if (!dirExists) {
            // Directory doesn't exist, create it
            await fs.promises.mkdir(dataDir);
            
            // Create the file inside the directory
            await fs.promises.writeFile(accountsFile, '[]');
            
            console.log('Directory and file created successfully.');
        } else {
            console.log('Directory already exists.');
        }
    } catch (err) {
        console.error(`Error: ${err}`);
    }
}

// Call the function
createDirectoryAndFile();



Now this works perfectly fine during development, but after I package it using electron-builder
for windows, target nsis, it does not seem to work. Moreover, it gives I get this error when I run the Wizard setup:
enter image description here

How to see HTTP requests made by content script file, Firefox Addon Extension

I started developing a firefox extension.
In my extension I make requests with fetch.

But the requests don’t appear in the Network tab of developer tools.
I am opening the developing from within the page where the content script is loaded, like you would debug this page normally.
Console logs do show up though, it’s only the requests that do not appear.

If I log the request response, it does show up in the Logs tab.
The issue is that it does not appear in the Network tab.

Any ideas please ?

Why does the execution order differ in Promise chains with return literal and return Promise.resolve?

I have problem in understanding the execution order of the following code snippet in JavaScript:

Promise.resolve('A0') // promise A
  .then((value) => { // onFulfilled A1
    console.log("Value of first A-chain-then:", value);
    return Promise.resolve("A1");
  })
  .then((value) => { // onFulfilled A2
    console.log("Value of second A-chain-then", value);
    return "A2";
  })
  .then((value) => { // onFulfilled A3
    console.log("Value of third A-chain-then", value);
  });
Promise.resolve("B0") // promise B
  .then((value)=>{ // onFulfilled B1
    console.log("Value of first B-chain-then:", value);
    return "B1";
  })
  .then((value)=>{ // onFulfilled B2
    console.log("Value of second B-chain-then:", value);
    return "B2"
  })
  .then((value)=>{ // onFulfilled B3
    console.log("Value of third B-chain-then:", value);
  })

The observed execution order is:

Value of first A-chain-then: A0
Value of first B-chain-then: B0
Value of second B-chain-then: B1
Value of third B-chain-then: B2
Value of second A-chain-then A1
Value of third A-chain-then A2

Here’s my confusion:
The promise.then(onFulfilled, onRejected) method returns a new Promise. When the onFulfilled function passed to then returns a literal value (value), the returned Promise will be resolved with Promise.resolve(value).
Based on this behavior, I would expect the following sequence of operations:

  1. Excute Promise.resolve('A0') and add first then of promise A chain to the microtasks queue (current microtasks queue [onFulfilled A1])

  2. Excute Promise.resolve('B0') and add first then of promise B chain to the microtasks queue (current microtasks queue [onFulfilled A1, onFulfilled B1])

  3. Excute onFulfilled A1 , and its return value is a fulfilled promise. As a result, the second then of the Promise A chain is added to the microtasks queue (current microtasks queue [onFulfilled B1, onFulfilled A2])

  4. Excute onFulfilled B1 , and its return value is a fulfilled promise. As a result, the second then of the Promise B chain is added to the microtasks queue (current microtasks queue [onFulfilled A2, onFulfilled B2])

According to my understanding, the result should be A0 B0 A1 B1 A2 B2. Why isn’t it like this? Is there something I might have missed about the difference between return Promise.resolve(value) and return value? Could someone please explain this? I would greatly appreciate any clarification!

link validation not working and links are all returned as false

this is my current test.php code

<?php
$years = [2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023]; // Array of years to include
$sessions = [
    "MJ" => "May/June (S)",
    "FM" => "March (FM)",
    "ON" => "October/November (W)"
];
$qps = [11, 12, 13, 21, 22, 23, 31, 32, 33, 41, 42, 43, 51, 52, 53, 61, 62, 63]; // QP codes
$mss = [11, 12, 13, 21, 22, 23, 31, 32, 33, 41, 42, 43, 51, 52, 53, 61, 62, 63]; // MS codes for May/June and October/November
$mss_march = [12, 22, 32, 42, 52, 62]; // MS codes for March

$cache_file = 'cache.json';
$cache_duration = 3600; // Cache duration in seconds (1 hour)

function generateLinks($year, $session, $codes, $type, $vertical = false) {
    global $cache_file, $cache_duration;
    $year_suffix = substr($year, -2);
    $session_prefix = strtolower($session) === "mj" ? "s" : (strtolower($session) === "fm" ? "m" : "w");
    $links = "";
    $cache = loadCache($cache_file);

    if ($vertical) {
        foreach ($codes as $code) {
            $url = "https://pp.great-site.net/0610/{$year}/{$session}/0610_{$session_prefix}{$year_suffix}_{$type}_{$code}.pdf";
            if (urlExists($url, $cache)) {
                $links .= "<div><a href="{$url}" target="_blank">{$code}</a></div>";
            } else {
                $links .= "<div><span style='color:red;'>{$code} (Not Available)</span></div>";
            }
        }
    } else {
        foreach (array_chunk($codes, 3) as $chunk) {
            $link_block = "";
            foreach ($chunk as $code) {
                $url = "https://pp.great-site.net/0610/{$year}/{$session}/0610_{$session_prefix}{$year_suffix}_{$type}_{$code}.pdf";
                if (urlExists($url, $cache)) {
                    $link_block .= "<a href="{$url}" target="_blank">{$code}</a> ";
                } else {
                    $link_block .= "<span style='color:red;'>{$code} (Not Available)</span> ";
                }
            }
            $links .= "<div>{$link_block}</div>";
        }
    }
    saveCache($cache_file, $cache);
    return $links;
}

function urlExists($url, &$cache) {
    global $cache_duration;
    if (isset($cache[$url]) && (time() - $cache[$url]['timestamp'] < $cache_duration)) {
        return $cache[$url]['exists'];
    }

    $context = stream_context_create(['http' => ['method' => 'GET', 'timeout' => 10]]);
    $headers = @file_get_contents($url, false, $context);
    $http_code = $headers ? '200' : '404';

    // Debugging information
    error_log("Checking URL: $url - HTTP Code: $http_code");

    $exists = $http_code == '200';
    $cache[$url] = ['exists' => $exists, 'timestamp' => time()];
    return $exists;
}

function loadCache($cache_file) {
    if (file_exists($cache_file)) {
        $cache = json_decode(file_get_contents($cache_file), true);
        if (is_array($cache)) {
            return $cache;
        }
    }
    return [];
}

function saveCache($cache_file, $cache) {
    file_put_contents($cache_file, json_encode($cache));
}

function generateTableRows($years, $sessions, $qps, $mss, $mss_march) {
    foreach ($years as $year) {
        foreach ($sessions as $session_key => $session_value) {
            echo "<tr>";
            echo "<td>{$year}</td>";
            echo "<td>{$session_value}</td>";
            echo "<td>" . generateLinks($year, $session_key, $qps, 'qp') . "</td>";
            echo "<td>" . generateLinks($year, $session_key, $session_key === 'FM' ? $mss_march : $mss, 'ms') . "</td>";
            echo "</tr>";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../../Styles/Bootstrap.css">
    <link rel="stylesheet" href="../../Styles/General.css">
    <link rel="stylesheet" href="../../Styles/Background.css">
    <link rel="stylesheet" href="../../Styles/Tables.css">
    <link rel="icon" href ="../../favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="../../favicon.ico" type="image/x-icon" />
    
    <title>Chemistry (0620)</title>
    <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-NHCZKLG8F3"></script>
    <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', 'G-NHCZKLG8F3');
    </script>
</head>
<body class="Grey">
    <a href="javascript:window.history.back();" class="btn btn-dark">Back</a>
    <h1 class="Center">Chemistry (0620)</h1>
    <div class="container table-responsive">
        <table class="table table-dark table-bordered">
            <thead>
                <tr>
                    <td>Year</td>
                    <td>Session</td>
                    <td>Question Paper</td>
                    <td>Mark Scheme</td>
                </tr>
            </thead>
            <tbody>
                <?php generateTableRows($years, $sessions, $qps, $mss, $mss_march); ?>
            </tbody>
        </table>
    </div>
</body>
</html>

i have been trying many different methods to validate the links as where if the link is not available for example for QP 63 it wont appear however all the links are returned as not available with all the different approaches tried image

while this is how it is supposed to be normally original but just without the 63 link that is not available for example

i am new to this but i have been trying many different approaches and even checked chatgpt for help however it kept taking me into loops of using different methods such as get_headers and curl and GET and HEAD however i keep getting the same results, i am currently using infinityfree free hosting service i am using 2 servers one for these files and codes etc. and the other one is solely for the pdf files which i am trying to make links to

the log file generated shows this,log

the website containing the pdf files is

https://pp.great-site.net/9700/2023/MJ/9700_s23_ms_42.pdf

this is an example of one of the pdf links since the whole server is just pdf files

Edit: this page is made so that there is a table to show “past paper exams of each year for ig students” every year there are 3 sessions February FM summer S winter (ON) in each session there are papers with different variants for example 63 means paper 6 variant 3 these links should lead to the pdf file with that exam stored on another server/website which i provided the link to so since not all exams are always available i want to carry automated checking if the file exists on the server show the link if it doesnt then delete/hide the link however using the code above it returns all the links as not available although they are valid so my question is what am i doing wrong here that returns all links as not available instead of only the invalid/not available links, the links are created with the help of php automatically as shown in the code above creating a loop for each year i write in the $years. The php code also contains a not working try to make the automatic link validation thing im trying to achieve

Any help would be appreciated, thanks in advance!

Trigger alert message when browesr tab shows unread messages

I have a WP site where I need to add code snippet to trigger an alert message,

Similar to – alert ("You have a new message"); however I need it to only trigger when the tab in question title changes from the page name to show a new message or messages – for example: Tab title goes from ‘inbox’ and changes to ‘(1) New Message’ or (2) New Message and so on, this is when it triggers an alert message.

I can get it to show alert message on load and after a set time just only.

To add I am running ten tablets in kiosk mode with notifications disabled but webview alert messages work.

Browser Tab picture

Getting Error While implementing jquery datatables in angular

I want to implement jquery datatbles in angular so that’s why i added these packages: npm install angular-datatables,npm install jquery,npm install datatables.net, npm install datatables.net-dt But getting error like this

Error:
node_modules/angular-datatables/src/angular-datatables.directive.d.ts:31:25

  • error TS2503: Cannot find namespace ‘DataTables’.

31 dtInstance: Promise<DataTables.Api>;
~~~~~~~~~~

Error: node_modules/angular-datatables/src/models/settings.d.ts:3:38 –
error TS2503: Cannot find namespace ‘DataTables’.

3 export interface ADTSettings extends DataTables.Settings {
~~~~~~~~~~

Error: node_modules/angular-datatables/src/models/settings.d.ts:6:37 –
error TS2503: Cannot find namespace ‘DataTables’.

6 export interface ADTColumns extends DataTables.ColumnSettings {
~~~~~~~~~~

× Failed to compile.

This is my component.html code:

<section class="content">
    <div class="content-block">
      <div class="block-header" *ngFor="let breadscrum of breadscrums">
        <!-- breadcrumb -->
        <app-breadcrumb [title]="breadscrum.title" [items]="breadscrum.items" [active_item]="breadscrum.active">
        </app-breadcrumb>
      </div>
      <div class="row clearfix">
        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
          <div class="card">
            <div class="header">
              <h2>Angular Data Tables</h2>
            </div>
            <div class="body">
                
              <!-- Add content here -->
              <table>
                <thead>
                    <th>Code</th>
                    <th>Product</th>
                    <th>Amount</th>
                    <th>Type</th>
                    <th>IsActive</th>
                </thead>
                <tbody>
                    @for(item of productlist;track item){
                        <tr>
                            <td>{{item.code}}</td>
                            <td>{{item.product}}</td>
                            <td>{{item.amount}}</td>
                            <td>{{item.type}}</td>
                            <td>{{item.isActive}}</td>
                        </tr>
                    }
                </tbody>
              </table>

            </div>
          </div>
        </div>
      </div>
    </div>
  </section>



  

This is my typescriptcode:

import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs';
import { products} from '../../core/models/products'
import { MasterService } from '../../core/service/master.service';
import { DataTablesModule } from 'angular-datatables';
import { Config } from 'datatables.net';

@Component({
  selector: 'app-angular-datatables',
  templateUrl: './angular-datatables.component.html',
  styleUrls: ['./angular-datatables.component.sass'],
  //imports: [DataTablesModule]
})
export class AngularDatatablesComponent implements OnInit {
  breadscrums = [
    {
      title: 'Tables',
      items: ['Extra'],
      active: 'Datatables',
    },
  ];

  productlist! : products[]
  //dtoptions: Config={}
  dtoptions: Config = {};
  dttrigger:Subject<any>=new Subject<any>();

  constructor(private service: MasterService) {}
  ngOnInit() {
    this.loadproducts();
  }

  loadproducts(){
    this.service.Loadproducts().subscribe(item=>{
      this.productlist=item;
      this.dttrigger.next(null);
    })
  }

}

This is my angulat.json:

"assets": ["src/favicon.ico", "src/assets"],
            "styles": [
              "./node_modules/bootstrap/dist/css/bootstrap.min.css",
              "./node_modules/@swimlane/ngx-datatable/index.css",
              "./node_modules/@swimlane/ngx-datatable/themes/material.css",
              "./node_modules/@swimlane/ngx-datatable/assets/icons.css",
              "src/assets/scss/style.scss",
              "src/assets/scss/theme/all-themes.scss",
              "src/styles.scss",
              "./node_modules/datatables.net-dt/css/dataTables.dataTables.min.css",
              "./node_modules/datatables.net-dt/css/dataTables.dataTables.css"
            ],
            "scripts": [
              "./node_modules/moment/min/moment.min.js",
              "./node_modules/chart.js/dist/Chart.bundle.js",
              "./node_modules/apexcharts/dist/apexcharts.min.js",
              "./node_modules/jquery/dist/jquery.min.js",
              "./node_modules/datatables.net/js/dataTables.min.js"
            ],

Even I re install all the packages but not able to fix the issue

Why can WebAudio’s gain node mix multiple inputs when it only has one input?

I was trying to find a way to mix audio streams with WebAudio and record them with a MediaRecorder. I have been following the approach outlined here:

Record multi audio tracks available in a stream with MediaRecorder

It seems that a gain node (in their example, the destination node) can perform mixing on multiple streams, as shown by my experiment below. In the example you can hear both the Caribbean Pirates theme and Universal Studios theme playing when you hit the record button.

However, on MDN it says that the gain node (as well as the destination node) has an input count of 1.

Number of inputs = 1
enter image description here

Intuitively, something with a single input cannot perform mixing! Am I missing anything here?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Web Audio Track Recorder</title>
</head>
<body>
  <h1>Web Audio Track Recorder</h1>
  <button id="recordButton">Start Recording</button>
  <script src="script.js"></script>
</body>
</html>

script.js

// URLs of the audio tracks:
const track1Url = 'https://archive.org/download/tvtunes_13046/Pirates%20of%20the%20Caribbean%20-%20Hes%20a%20Pirate.mp3';
const track2Url = 'https://archive.org/download/tvtunes_7590/Universal%20Studios.mp3';

// Initialize variables
let audioContext;
let source1, source2;
let mediaRecorder;
let audioChunks = [];
let isRecording = false;

// Function to start the audio context and load tracks
async function startAudio() {
  audioContext = new (window.AudioContext || window.webkitAudioContext)();

  // Load and decode the audio tracks
  const track1Data = await fetch(track1Url).then(response => response.arrayBuffer());
  const track2Data = await fetch(track2Url).then(response => response.arrayBuffer());

  const track1Buffer = await audioContext.decodeAudioData(track1Data);
  const track2Buffer = await audioContext.decodeAudioData(track2Data);

  // Create buffer sources
  source1 = audioContext.createBufferSource();
  source2 = audioContext.createBufferSource();

  source1.buffer = track1Buffer;
  source2.buffer = track2Buffer;

  // Create a gain node to control the volume
  const gainNode = audioContext.createGain();
  gainNode.gain.setValueAtTime(0.25, audioContext.currentTime);

  // Connect sources to the gain node
  source1.connect(gainNode);
  source2.connect(gainNode);

  // Connect gain node to the destination (speakers)
  gainNode.connect(audioContext.destination);

  // Create a MediaStream from the audio context
  const destination = audioContext.createMediaStreamDestination();
  gainNode.connect(destination);

  // Initialize MediaRecorder with the audio stream
  mediaRecorder = new MediaRecorder(destination.stream);

  // Event handler for when data is available
  mediaRecorder.ondataavailable = event => {
    audioChunks.push(event.data);
  };

  // Event handler for when recording stops
  mediaRecorder.onstop = () => {
    const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
    const audioUrl = URL.createObjectURL(audioBlob);
    const downloadLink = document.createElement('a');
    downloadLink.href = audioUrl;
    downloadLink.download = 'recording.webm';
    downloadLink.click();
    audioChunks = [];
  };

  // Start the sources
  source1.start();
  source2.start();
}

// Function to toggle recording
function toggleRecording() {
  if (!isRecording) {
    if (!audioContext) {
      startAudio().then(() => {
        mediaRecorder.start();
        document.getElementById('recordButton').textContent = 'Stop Recording';
      });
    } else {
      mediaRecorder.start();
      document.getElementById('recordButton').textContent = 'Stop Recording';
    }
  } else {
    mediaRecorder.stop();
    document.getElementById('recordButton').textContent = 'Start Recording';
  }
  isRecording = !isRecording;
}

// Add event listener to the record button
document.getElementById('recordButton').addEventListener('click', toggleRecording);

You can also try it here: https://jsfiddle.net/10ms7pyd/8/

Authorization is getting failed with correct token with jsonwebtoken

I am working on a project where I have created the registration and login routes. The problem is coming with the profile route, specifically, authorization. What I want is that if the user wants to access the profile route, he should be logged in, for which the provided token should be correct. Please have a look at the code –
auth.middleware.js

import jwt from 'jsonwebtoken';



export const authuser = async (req,res,next) => {
    try {
        const token = req.cookies.token || req.headers.authorization.split(' ')[1];

        if(!token){
            return res.status(401).send({error: "Please login to see the profile"});
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        req.user = decoded;
        next();
    } catch (error) {
        console.log(error

        )
        res.status(401).send({error: 'Unauthorized User'})
    }
}

user.route.js –

import { Router } from "express";
import * as usercontroller from '../controllers/user.controller.js'
import { body } from "express-validator";
import * as authMiddleware from '../middlewares/auth.middleware.js'

const router = Router();


router.post('/register',
    body('email').isEmail().withMessage('Email must be a valid email address.'),
    body('password').isLength({min:6}).withMessage('Password must be atleast 6 characters long.'),
    usercontroller.createUserController);

    router.post('/login',
        body('email').isEmail().withMessage('Email must be a valid email address.'),
        body('password').isLength({min:6}).withMessage('Password must be atleast 6 characters long.'),
        usercontroller.loginUserController);

    router.post('/profile',authMiddleware.authuser ,usercontroller.profileController)
export default router;

user.controller.js

import userModel from '../models/user.model.js';
import * as userService from '../services/user.service.js'
import { validationResult } from 'express-validator';

export const createUserController = async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }

    try {
        const user = await userService.createUser(req.body);
        const token = await userModel.generateJWT;
        res.status(201).send(user);
    } catch (error) {
        res.status(400).send(error.message)
    }
}


export const loginUserController = async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }

    try {
        const { email, password } = req.body;
        const user = await userModel.findOne({ email }).select('+password');
        if (!user) {
            return res.status(401).json({
                errors: "Invalid credentials"
            })
        }
        const isMatch = await user.isValidPassword(password);

        if (!isMatch) {
            return res.status(401).json({
                errors: "Invalid password"
            })
        }

        const token = user.generateJWT();
        res.status(200).json({user,token,});
        

        
    }
    catch (error) {
        res.status(400).send(error.message)
    }
}

export const profileController = async (req,res) => {
    console.log(req.user);
    req.status(200).json({
        user:req.user
    })
}

When I’m sending a request from postman as headers with key – “authorization” and value – “beared “. The token is of a already registered user. I’m getting –
{
“error”: “Unauthorized User”
}
in postman and –
TypeError: Cannot read properties of undefined (reading ‘token’)
at authuser (file:///C:/Users/tejas/OneDrive/Desktop/Tejashv/Programs/Project-A6U7X1/backend/middlewares/auth.middleware.js:7:35) in terminal at vs code. Can someone please tell me that what is the reason behind this problem and how can it be solved ?

Why are class declarations faster than object declarations?

I have the following script benchmarking the time it takes to declare an object with a class vs. directly with an object.

console.time("class decls");
class Dog {
        a;
        constructor() {
            this.a = 1;
        }
        bark() {
            this.a + this.a;
        }
    }

for (let i = 0; i < 1_000_000; ++i) {
    let dog = new Dog();
    dog.bark();
}
console.timeEnd("class decls");

console.time("object decls");
for (let i = 0; i < 1_000_000; ++i) {
    let dog = {
        a: undefined,
        bark() {
            this.a + this.a;
        }
    }
    { // inlining the constructor
        dog.a = 1;
    }
    dog.bark();
}
console.timeEnd("object decls");

The results seem to heavily favor the first method, giving the following times when run with Bun and similar results when run with Node:

[8.46ms] class decls
[27.98ms] object decls

Why is it so much faster to declare a class and then construct a new object thereof? Is there some caching going on, or is it something else?