Hapi.js how to set route options via auth plugin

I need to change route options from auth plugin:

example route

hapiServer.route({
            method: 'GET',
            path: '/users',
            handler: this.handler.getUsersForLoggedInUserCompany.bind(this.handler),
            options: {
                auth: auth.setAuth(hapiServer, {
                    scopes: ['Internal', 'User'],
                    roles: ['userRole'],
                }),
                response: {
                    failAction: 'error',
                    status: {
                        200: AccountSchemas.responseUsers,
                    },
                },
            },
        });

In auth.setAuth I have options based on it and some manipulations to hide sensitive values I have to put in

 auth: auth.setAuth(hapiServer, { scopes: ['Internal', 'User'], roles: ['Rsa.Default'] }),
                plugins: {
                    'hapi-swagger': {
                        'x-vi-visibility': 'external',
                        'x-vi-permission': {
                            scopes: ['Internal', 'User'],
                            roles: ['Rsa.Default'],
                        },
                    },
                },

Is it possible? I tried in auth plugin

  // server.ext('onPostStart', () => {
            //     server.table().forEach((route) => {
            //         // @ts-ignore
            //         route.settings.plugins['hapi-swagger'] = {
            //             // @ts-ignore
            //             ...route.settings.plugins['hapi-swagger'],
            //             'x-vi-visibility': isViVisibility(route.settings.auth || {}),
            //             'x-vi-permission': viPermisions(route.settings.auth || {}),
            //         };
            //     });
            // });

but i can not get information about route in normal way and these values are not passing when I call for /openapi.json route

angular 13 SSR, assign a value to a property in onInit, causes ngOnInit() to be called multiple times

In app.component.ts, I assign a value to a property in onInit, and it used in html.

data:any = [];

ngOnInit() {
    this.service.getData().subscribe(res => this.data = res);
}

Any idea why ngOnInit() calls more than once?

At first, I thought it was the request interface causing this issue. However, after some attempts, I found that assigning a value to it during the lifecycle causes the problem.

Elementor Form : client side javascript validation

I already did server side data validation using the hook elementor_pro/forms/validation and it’s working fine.

In addition I would like to do client side data validation before submitting the form to fix invalid data straight away avoiding a round trip to the server.

I would like to do custom validation using Javascript and not using the default browser tooltip bubble.

I added this code and the validation works fine, errors messages are displayed on the form. However the form is still submitted when fields input are invalid.

document.addEventListener('submit', (e) => {
  // this is my custom validation function
  validateForm(e);
})

How to prevent the form being submit? preventDefault() function doesn’t work as the form submit is done via AJAX.

I would like to know what’s the correct way to stop the form submitting when the client side validation failed.

Can’t find variable: require at global code@

I’m new to JavaScript and was trying to import the Google Gemini library to use its AI. However, I’m facing an issue when I use the “require” keyword:

ERROR: Can't find variable: require at global code@

Here is the code that throws this error:

const {
    GoogleGenerativeAI,
    // HarmCategory,
    // HarmBlockThreshold,
  } = require("@google/generative-ai");

setItem coordinates and getitem lat

I use setitem(coordinates) in a previous page that concerns latitude an longitude. I want the next page to use getItem() but just the latitude but I didn’t get it.

First page

function storeCoordinates(location) {     
  const coordinates = {   
    lat: location.lat(), 
    lng: location.lng()       
  };            
  localStorage.setItem('coordinates', JSON.stringify(coordinates));    
}

Next page

window.onload = function () {
  var lat = localStorage.getItem('coordinates.lat');
  var IR = (-75 * lat) + 5025;
  var energie_pro = IR * 0.926 * 0.8 * 0.213 * 1.92 * 8;
  document.getElementById('eco_3000').innerText = energie_pro;
}

Get user selected text of google docs in 2024?

Many workarounds have been created but then deprecated as Google updates how Google docs work.

I know this has been talked about a lot, but no one provided a solution that still works in 2024.

It’s obviously possible because Grammarly exists, but it seems like a black box right now?

Obviously I can make a Google docs add-on, but my goal is to have a Chrome extension that works on any website, not just Google docs.

Loading file list in Next.js does not reflect the latest changes

In Next.js, I implemented a feature to fetch a list of files in a specific directory using a module like fs.

When I deployed it, the functionality itself worked fine, but when I took actions such as uploading or deleting new files to that directory and then re-entered the website, it didn’t reflect those changes at all. (For example, if I added a file called test.txt to the directory and then re-entered the website, it didn’t reflect the latest changes).

After rebuilding by running the npm run build command, I was able to see that the changes were reflected.

Below is the code for /lab/page.js.

const fetchFiles = async () => {
    try {
      console.log('Fetching files...');
      const res = await fetch('/api/files/lab', {
        credentials: 'include'
      });
      if (!res.ok) {
        throw new Error(`Error: ${res.status} ${res.statusText}`);
      }
      const data = await res.json();
      console.log('Files fetched successfully:', data.files);
      setFiles(data.files);
    } catch (error) {
      console.error('Failed to fetch files:', error);
      setError(error.message);
    }
  };

And below is the code for /api/files/lab/route.js. This is the API to get the list of files.

import { NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';

export async function GET() {
  const directoryPath = '*MY_DIRECTORY*';
  try {
    const files = await fs.readdir(directoryPath);
    const fileDetails = await Promise.all(files.map(async (file) => {
      const filePath = path.join(directoryPath, file);
      const stats = await fs.stat(filePath);
      return {
        name: file,
        uploadDate: stats.mtime.toISOString(),
        path: `/api/files/lab/download?file=${encodeURIComponent(file)}`,
      };
    }));
    return NextResponse.json({ files: fileDetails });
  } catch (error) {
    console.error('Error reading directory:', error);
    return NextResponse.json({ error: 'Failed to read directory' }, { status: 500 });
  }
}

I’ve identified the problem as being caused by changes not being reflected in static builds, but I haven’t found a solution yet.

ESLint expects a callback returned at end of arrow function

I have this array:

var json = [
    {
      "id": 1,
      "firstName": "Paul",
      "lastName": "Carr",
      "company": "Foo"
    },
    {
      "id": 2,
      "firstName": "Mary",
      "lastName": "Menan",
      "company": "Foo"
    },
    {
      "id": 3,
      "firstName": "Donal",
      "lastName": "Carr",
      "company": "Bar"
    }
  ];

and this checkbox code:

<div>
      <input type="checkbox" id="checkbox" checked={isChecked} onChange={checkHandler} />
      <p>{isChecked ? json.map(j => <div>{j.id}, {j.firstName}, {j.lastName}, {j.company}</div>) : json.map(k => {
        if(k.company !== "Bar") {
          <div>{k.id}, {k.firstName}, {k.lastName}, {k.company}</div>
        }
      })}</p>
    </div>
  )

If the box is checked I want the entire array printed. If not, only the people who are not in company Foo should be printed. However, when I run the code I get:

src/App.js
  Line 44:111:  Array.prototype.map() expects a value to be returned at the end of arrow function  array-callback-return

My code works but I’m not sure how I fix it so I don’t get the lint warning. What should it look like?

Excessive use of Javascript window object

I am working on a javascript SDK which works in browser, here they have used window.someVariableName to store a data. We wanted that variable to be accessible any where in javascript code, but this expose the internal variables to the user, which is not secure.
Is there any standard way to handle this?

I created a singleton class in javascript and added all variables in that class with getters and setters.

Unable to load List.js accurately while loading data using AJAX

I’m working on a pagination feature using List.js for my email page on a website where emails are loaded using PHP, MySQL, and AJAX. I have installed List.js locally and referenced it correctly in my footer. While the pagination works fine on other pages, it’s not functioning correctly on my emails page.

Here’s a brief overview of the setup:

Page Loading: When the user navigates to the email page, email.php loads. I’ve added a PHP condition to load email_inbox.php by default inside email.php unless the user selects another option (e.g., sent, draft, trash). In that case, email.php dynamically loads the selected content.

Issue Description: The problem is that when the page loads, the emails are displayed with pagination for a brief moment, and then all the emails appear without pagination.

NOTE: I have tested the email_inbox.php code in a separate file, and it loaded the emails with pagination correctly.

Here’s a simplified version of my code to illustrate the issue:

  • email_inbox.php
<?php
if (empty($emails)) {
    echo "<div class='text-center'>No emails found</div>";
} else { ?>
    <div id='all-emails' data-list='{"valueNames":["email"],"page":5,"pagination":true}'>

        <div class='list' id='emails-list'>
            <?php
            foreach ($emails as $email) {
                $id = $email['id'];
                $sender = $email['sender'];
                $sender_name = $email['sender_name'];
                $cc_recipient = $email['cc_recipient'];
                $bcc_recipient = $email['bcc_recipient'];
                $subject = $email['subject'];
                $content = $email['content'];
                $content = str_replace("xC2xA0", ' ', $content);
                $is_read = $email['is_read'];
                $is_starred = $email['is_starred'];
                $is_archived = $email['is_archived'];
                $is_deleted = $email['is_deleted'];
                $is_draft = $email['is_draft'];
                $is_interview = $email['is_interview'];
                $is_application_received = $email['is_application_received'];
                $is_not_accepted = $email['is_not_accepted'];
                $is_job_ad = $email['is_job_ad'];
                $is_skill_test = $email['is_skill_test'];
                $timeZone = new DateTimeZone('Asia/Karachi');
                $created_at = DateTime::createFromFormat('Y-m-d H:i:s', $email['created_at'], $timeZone);
                $sent_at = $email['sent_at'];
                $updated_at = $email['updated_at'];
                $attachments = $email['attachments'];

                // Calculate the time difference
                $currentDate = new DateTime();
                $timeDifference = $currentDate->diff($created_at);
                // Determine the most appropriate unit
                if ($timeDifference->days == 0) {
                    if ($timeDifference->h == 0) {
                        if ($timeDifference->i == 0) {
                            $timeAgo = $timeDifference->s . 's';
                        } else {
                            $timeAgo = $timeDifference->i . 'm';
                        }
                    } else {
                        $timeAgo = $timeDifference->h . 'h';
                    }
                } else {
                    if ($timeDifference->y > 0) {
                        $timeAgo = $timeDifference->y . 'Y';
                    } elseif ($timeDifference->m > 0) {
                        $timeAgo = $timeDifference->m . 'M';
                    } else {
                        $timeAgo = $timeDifference->d . 'D';
                    }
                }
            ?>

                <div class="email border-top border-translucent hover-actions-trigger py-3 <?php echo $is_read == 0 ? 'bg-white' : ''; ?>" id="email-item" data-email-id="<?php echo $id; ?>" data-email-read="<?php echo $is_read; ?>">
                    <div class="row align-items-center gx-2">
                        <div class="col-auto">
                            <div class="d-flex flex-column flex-sm-row">
                                <button class="btn p-0 star-btn" data-email-id="<?php echo $id; ?>" data-email-folder="inbox" data-email-starred="<?php echo $is_starred; ?>">
                                    <span class="<?php echo $is_starred ? "fas" : "far"; ?> text-body-quaternary fa-star"></span>
                                </button>
                            </div>
                        </div>
                        <div class="col-auto">
                            <a class="text-body-emphasis fw-bold inbox-link fs-9 email-items email-links" href="email.php?folder=details" data-folder="details" data-email-id="<?php echo $id; ?>" data-current-folder="inbox">
                                <?php
                                if (empty($sender_name)) {
                                    echo $sender;
                                } else {
                                    echo $sender_name;
                                }
                                ?>
                            </a>
                        </div>
                        <div class="col-auto ms-auto">
                            <div class="hover-actions end-0">
                                <button class="btn btn-phoenix-secondary btn-icon dropdown-toggle dropdown-caret-none" type="button" data-bs-toggle="dropdown" data-boundary="window" aria-haspopup="true" aria-expanded="false" data-bs-reference="parent">
                                    <span class="fa-solid fa-ellipsis"></span>
                                </button>
                                <div class="dropdown-menu dropdown-menu-end py-2">
                                    <?php if ($_SESSION['role'] === 'candidate') : ?>
                                        <a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#kanbanAddTask" href="javascript:void(0);">Mark Interview</a>
                                    <?php endif; ?>

                                    <a class="dropdown-item archive-btn" data-email-folder="inbox" data-email-id="<?php echo $id; ?>" href="javascript:void(0);" data-email-archived="<?php echo $is_archived; ?>">Archive</a>

                                    <a class="dropdown-item interview-btn" data-email-folder="inbox" data-email-id="<?php echo $id; ?>" href="javascript:void(0);" data-email-interview="<?php echo $is_interview; ?>">Move to
                                        Interviews</a>

                                    <a class="dropdown-item application-received-btn" data-email-folder="inbox" data-email-id="<?php echo $id; ?>" href="javascript:void(0);" data-email-application-received="<?php echo $is_application_received; ?>">Move to
                                        Application Received</a>

                                    <a class="dropdown-item not-accepted-btn" data-email-folder="inbox" data-email-id="<?php echo $id; ?>" href="javascript:void(0);" data-email-not-accepted="<?php echo $is_not_accepted; ?>">Move to
                                        Not Accepted</a>

                                    <a class="dropdown-item job-ad-btn" data-email-folder="inbox" data-email-id="<?php echo $id; ?>" href="javascript:void(0);" data-email-job-ad="<?php echo $is_job_ad; ?>">Move to
                                        Job Ads</a>

                                    <a class="dropdown-item skill-test-btn" data-email-folder="inbox" data-email-id="<?php echo $id; ?>" href="javascript:void(0);" data-email-skill-test="<?php echo $is_skill_test; ?>">Move to
                                        Skill Test Assessments</a>

                                    <a class="dropdown-item text-danger" id="delete-email" data-email-deleted="<?php echo $is_deleted; ?>" data-email-folder="inbox" data-email-id="<?php echo $id; ?>" href="javascript:void(0);">Delete</a>
                                </div>
                            </div>
                            <span class="fs-10 fw-bold"><?php echo $timeAgo; ?></span>
                        </div>
                    </div>
                    <div class="ms-4 mt-sm-0">
                        <a class="d-block inbox-link email-items email-links" href="email.php?folder=details" data-folder="details" data-email-id="<?php echo $id; ?>" data-current-folder="inbox">
                            <span class="fs-9 line-clamp-1 text-body-emphasis"><?php echo $subject; ?></span>
                            <p class="fs-9 ps-0 text-body-tertiary mb-0 line-clamp-2">
                                <?php
                                $doc = new DOMDocument();
                                libxml_use_internal_errors(true);
                                $doc->loadHTML($content);
                                libxml_clear_errors();

                                removeElementsByTagName('script', $doc);
                                removeElementsByTagName('style', $doc);
                                removeElementsByTagName('link', $doc);

                                $textContent = strip_tags($doc->saveHTML());

                                $maxLength = 100;
                                if (strlen($textContent) > $maxLength) {
                                    $plainContent = substr($textContent, 0, $maxLength) . '...';
                                }

                                echo $plainContent;
                                ?>
                            </p>
                        </a>

                        <?php
                        if (!empty($attachments)) {
                            foreach ($attachments as $attachment) {
                                $filename = $attachment['file_name'] ?: $attachment['file_address'];
                                $fileExtension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
                                $iconClass = getIconClass($fileExtension);
                        ?>

                                <a class="d-inline-flex align-items-center border border-translucent rounded-pill px-3 py-1 me-2 mt-2 inbox-link" href="queries/download_attachments.query.php?file_url=<?php echo $attachment['file_address']; ?>" download>
                                    <span class="<?php echo $iconClass; ?> fs-9"></span>
                                    <span class="ms-2 fw-bold fs-10 text-body"><?php echo htmlspecialchars($filename); ?></span>
                                </a>

                        <?php
                            }
                        }
                        ?>
                    </div>
                </div>

            <?php
            } ?>

        </div>
        <div class="row align-items-center justify-content-between py-2 pe-0 fs-9">
            <div class="col-auto d-flex">
                <p class="mb-0 d-none d-sm-block me-3 fw-semibold text-body" data-list-info="data-list-info">
                </p>
                <a class="fw-semibold" href="#!" data-list-view="*">
                    View all<span class="fas fa-angle-right ms-1" data-fa-transform="down-1"></span>
                </a>
                <a class="fw-semibold d-none" href="#!" data-list-view="less">
                    View Less<span class="fas fa-angle-right ms-1" data-fa-transform="down-1"></span>
                </a>
            </div>
            <div class="col-auto d-flex">
                <button class="page-link" data-list-pagination="prev">
                    <span class="fas fa-chevron-left"></span>
                </button>
                <ul class="mb-0 pagination"></ul>
                <button class="page-link pe-0" data-list-pagination="next">
                    <span class="fas fa-chevron-right"></span>
                </button>
            </div>
        </div>
    </div>
<?php
}
?>
  • email.php
<div id="load-folder-emails">
    <?php
    if (isset($_GET['folder'])) {
        $folder = $_GET['folder'];
        if (isset($_GET['emailId'])) {
            $emailId = $_GET['emailId'];
        }
        if (isset($_GET['currentFolder'])) {
            $currentFolder = $_GET['currentFolder'];
        }
    } else {
        $folder = 'inbox';
    }

    if ($folder == 'inbox') {
        include_once 'email_inbox.php';
    } else if ($folder == 'sent') {
        include_once 'email_sent.php';
    } else if ($folder == 'draft') {
        include_once 'email_draft.php';
    } else if ($folder == 'spam') {
        include_once 'email_spam.php';
    } else if ($folder == 'deleted') {
        include_once 'email_deleted.php';
    } else if ($folder == 'starred') {
        include_once 'email_starred.php';
    } else if ($folder == 'archived') {
        include_once 'email_archived.php';
    } else if ($folder == 'details') {
        include_once 'email_details.php';
    } else if ($folder == 'interviews') {
        include_once 'email_interviews.php';
    } else if ($folder == 'applicationReceived') {
        include_once 'email_application_received.php';
    } else if ($folder == 'notAccepted') {
        include_once 'email_not_accepted.php';
    } else if ($folder == 'jobAds') {
        include_once 'email_job_ads.php';
    } else if ($folder == 'skillTestAssessments') {
        include_once 'email_skill_assessment.php';
    }
    ?>
</div>

Advice needed on full-stack development [closed]

The project I am working on is to read a COMTRADE file (IEEE standard file) and display its contents as graphs on a webpage.

I have a working version of this where I am using javascript to read and interpret from the COMTRADE file and display the signals read as graphs using javascript. I am using the open source plotting library plotly.

I want to move my COMTRADE reader part to python. The reason is that the project also involves further processing of the signals which is easier to do in python.

I now have a COMTRADE reader in python, which can read and interpret different versions of COMTRADE files and give the required signal values as output

Now my question is, how do I go about stringing it all together. That is, I want my front end to be javascript (with HTML & CSS). I want my file processing and later further mathematical processing of the signal to be in python.

The whole process is initiated when a button on a webpage is clicked to point to the file location. The file must then be read, interpreted by python and the results be passed back to the front end which shall be displaying it as graphs. Further mathematical processing of this signal is initiated by more button on the webpage. When these buttons are clicked, python code which does some more mathematical operations on this signal shall be executed and the results will be displayed back on the webpage.

Can somebody point me in the right direction. That is I want some advice on whether this is feasible and if yes, How do I do it ?

Thanks
Tamizh

Playwright: repeatedly connect and disconnect to same browser and page instances using connectOverCDP

I have a environment where I need to have a browser and one page constantly open. I want to use Playwright to connect to it, do certain actions on the application, and stop the script. I might need to run several scripts against this browser and page instances. So it’s a no to new pages etc. – it needs to be this specific page and browser instance. So the first script could click on a button, the next could login etc.

Using Playwright, I can connect to the browser using connectOverCDP without any problems. I get the context and the page and can interact with the page. The first time I run any script, all works fine. But when I run a new script using the similar way to connect and get the page, I get an error about “Execution context was destroyed, most likely because of a navigation” or something similar. There is no way to gracefully disconnect from the connection.

I’ve tried several ways to disconnect from the connection: browser.close(), page.close(), context.close(). Without any of them, the scripts are left hanging. I can stop the script using process.exit(). But whatever I do, the next script is having issues or the page is actually closed – which is not what I need to do.

I have used Puppeteer to connect to the browser and after using browser.disconnect() all works fine on the next script call. But as Playwright is used in other projects, it makes sense to try to use the same thing in this case too.

So my question is, is there a way to do what I’m trying to do?

This is my current way to connect to the browser (localhost for dev purposes).

const browser = await playwright.chromium.connectOverCDP("http://localhost:9222");
const context = browser.contexts()[0];
const page = context.pages()[0];

Swapping images in Django(Using javascript/js)

This is the block of HTML code which contains one Main image and other additional images. If the user clicks on any additional images, the image should get replaced by the Main image. The logic works fine until I click the same image twice. After that the main image is lost

<img id="mainThumbnail" class="card-img-top mb-5 mb-md-0 rounded" src="{{ product.image.url }}" alt="{{ product.name }}" />

<!-- Additional Images -->
{% if additional_images %}
<div class="additional-images mt-4">
    <div class="row">
    {% for image in additional_images %}
        <div class="col-2">
            <img class="img-fluid rounded cursor-pointer thumbnail-image" src="{{ image.image.url }}" alt="Additional image for {{ product.name }}" onclick="swapImages('{{ image.image.url }}', this)" />
        </div>
    {% endfor %}
    </div>
</div>
{% endif %}

This is my javascript function

function swapImages(newImageUrl, clickedElement) {
    console.log(this);
    // Get the current main image URL
    const currentThumbnailUrl = document.getElementById('mainThumbnail').src;

    // Update the main thumbnail image with the new image URL
    document.getElementById('mainThumbnail').src = newImageUrl;

    // Update the clicked image with the previous main thumbnail image URL
    clickedElement.src = currentThumbnailUrl;

    // Remove 'selected' class from all thumbnail images
    document.querySelectorAll('.thumbnail-image').forEach(img => img.classList.remove('selected'));

    // Add 'selected' class to the clicked thumbnail image
    clickedElement.classList.add('selected');
}

document.querySelectorAll('.cursor-pointer').forEach(el => el.style.cursor = 'pointer');

I don’t wanted to use the javascript but that’s the only solution I can find. I’d want the image to replace when clicked.