RxJS setTimeout operator equivalent

Is there a RxJS operator that can replace set/clearTimeout in this specific case:

this.mouseEnterSubscription = this.mouseEnterStream
  .subscribe(() => {
    this.timeout = setTimeout(() => {
      void this.playVideo();
    }, 500)
});

this.mouseLeaveSubscription = this.mouseLeaveStream.subscribe(() => {
  this.pauseVideo();
  clearTimeout(this.timeout);
});

Need Help Finding Reliable Visa Consultants in Pakistan [closed]

Hope all’s well with you. I’m currently working on my visa for [destination country] and could really use some advice on finding trustworthy visa consultants in Pakistan.

I’ve been doing some research online, but the options are overwhelming. If any of you have experience with visa consultants in Pakistan, I’d love to hear about it. Whether it’s for studying, working, tourism, or immigration, I’m open to suggestions.

I’m looking for consultants who know their stuff and offer good service at fair prices. Any tips or recommendations would be greatly appreciated.

Thanks a ton in advance!

I tried reaching out to various visa consultants in Pakistan and researched online for recommendations. My expectation was to gather insights and experiences from others who have dealt with visa consultants before.

what additions should be made to this text file with helpful symfony husky

Symfony Installation:

Created a Symfony project using Composer with the symfony/skeleton package.
Added the webapp package using Composer.


composer create-project symfony/skeleton:"7.0.*" symfony_test_app
composer require webapp

Database Setup:

Configured the database URL with credentials.
Created the database schema using Symfony's Doctrine commands.

DATABASE_URL=”mysql://username:password@host:port/database_name?serverVersion=10.4.28-MariaDB&charset=utf8mb4″
php ./bin/console doctrine:database:create
php bin/console doctrine:schema:update –force

Symfony Packages Installation:

Installed essential Symfony packages like symfony/orm-pack, symfony/form, symfony/maker-bundle, and symfony/framework-bundle.
Generated migrations, entities, forms, user authentication, etc., using Symfony's console commands.
composer require symfony/orm-pack
composer require symfony/form
composer require symfony/maker-bundle --dev
composer require symfony/framework-bundle
php bin/console make:migration
php bin/console make:entity
php bin/console make:form PersonType Person
php bin/console make:user
php bin/console make:auth

Front-end Dependencies:

Included Bootstrap and jQuery CDN links for styling and client-side scripting.
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

Front-end Script:

Added JavaScript code to filter items based on categories using Bootstrap's button groups.
<script>
    $(document).ready(function(){
        $(".filter-button").click(function(){
            var value = $(this).attr('data-filter');

            if(value === "all") {
                $('.filter').show('1000');
            } else {
                $(".filter").not('.'+value).hide('slow');
                $('.filter').filter('.'+value).show('slow');
            }

            $(".filter-button").removeClass("active");
            $(this).addClass("active");
        });
    });
</script>

Symfony Controller:

Created a Symfony controller named RegistrierungController for handling user registration.
Defined a route /registrierung for accessing the registration form.
<?php

namespace AppController;

use AppEntityUser;
use DoctrineORMEntityManagerInterface;
use SymfonyComponentFormExtensionCoreTypePasswordType;
use SymfonyComponentFormExtensionCoreTypeRepeatedType;
use SymfonyComponentFormExtensionCoreTypeSubmitType;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentHttpFoundationRequest;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentPasswordHasherHasherUserPasswordHasherInterface;
use SymfonyComponentRoutingAnnotationRoute;

class RegistrierungController extends AbstractController
{
    #[Route('/registrierung', name: 'app_registrierung')]
    public function reg(Request $request, EntityManagerInterface $entityManager, UserPasswordHasherInterface $passwordHasher): Response
    {
        // Form handling logic here...
    }
}

Twig Template:

Utilized Twig templating engine to render the registration form.
Extended the base template to maintain consistency across pages.
Rendered the registration form using Symfony's form rendering functions.
twig

{% extends 'base.html.twig' %}

{% block title %}Hello RegistrierungController!{% endblock %}

{% block body %}

<h1>RegistrierungController</h1>

{{ form_start(regform) }}
{{ form_widget(regform) }}
{{ form_end(regform) }}

{% endblock %}

Front-end Component:

Implemented a carousel component using Bootstrap's Carousel to display car details.
Dynamically populated car details using Twig's loop syntax.
Linked each carousel item to a detailed view page using Symfony's routing system.
<section>
    <div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel" data-interval="3000">
        <div class="carousel-inner">
            {% for car in cars %}
                <div class="carousel-item {% if loop.first %}active{% endif %}">
                    <h2>{{ car.getModel() }}</h2>
                    <img class="carousel-image" src="{{ asset('images/' ~ car.getImage()) }}" alt="{{ car.getBrand() }}">
                    <br>
                    <a class="details-button" href="{{ path('car_details', {'id': car.getId()}) }}">Click here for more details</a>
                </div>
            {% endfor %}
        </div>
    </div>
</section>

This setup provides a comprehensive guide for setting up a Symfony application with user registration and front-end components like filtering buttons and carousels for displaying data.

object data push using map function in react/javscript

object array

{ 
 first : { label :"a" , status : true , text: "dummy" },
 second : { label :"b" , status : true , text: "dummy" },
 third : { label :"c" , status : false , text: "dummy" }
 }

I have the object and map and push inot other object check the object key have label is “c” ,if present then dont push

 const newData = data && data.map(item => {
            if(item.label !=='c') {   
                return {
                ...item, 
                };
            }
            }); 

expected result

{ 
 first : { label :"a" , status : true , text: "dummy" },
 second : { label :"b" , status : true , text: "dummy" } 
 }

How to simplify multiple if statements branches in Javascript?

I’m writing codes to find a proper target and make subsequent operation on it. My current codes would first try to look for Type 1. If it doesn’t exist, I’ll try to look for Type 2 and so on. Because the find function costs CPU too much, I’d like to avoid using it to find all Types at the beginning. The following are my current codes. How can I simplify them?

const target1 = find1(Type1);
if(target1){
    operate1(target1);
}else{

    const target2 = find2(Type2);
    if(target2){
        operate2(target2);
    }else{

        const target3 = find3(Type3);
        if(target3){
            operate3(target3);
        }else{
            ...
        }
    }
}        

How to set PageIndex in ‘react-data-table-component’?

I have stored currentPageIndex of ‘react-data-table-component’ using onChangePage={handlePageChange} and store the pageIndex in context.

I want to retain the page index in my table when i come back to the list page.

I get my savedpageIndex from context.

But I can’t pass the pageIndex to ‘react-data-table-component’. It always goes back to the first page!.

This below assignment not working as expected ‘currentPage={10}’.

<DataTable
            title={<THeader />}                        
            columns={columns}
            data={tableData}
            actions={actionComponentMemo}
            customStyles={customTableStyles}
            pagination
            **currentPage={10}**
            onChangePage={handlePageChange}
            fixedHeader
            fixedHeaderScrollHeight="440px" //remove this if you dont need table scroll
            selectableRows
            selectableRowsHighlight
            selectableRowsRadio="checkbox"
            pointerOnHover
            className=" border z-10"
            contextActions={contextActions}
            onSelectedRowsChange={handleRowSelected}
            clearSelectedRows={toggleCleared}  
            onRowClicked={(row)=> navigate(`/consumer-list/${row.id}`)}
          />

NextJS – Authentication – Refresh logic in middleware with custom backend

How do I implement a refresh mechanism for authentication in NextJS with a custom backend?

My plan so far was to

  • Decode the access token and refresh token from cookies
  • If the access token expired but the refresh token is still valid, then I want to refresh my access token
  • At the end I want to set the currentUser in a separate cookie from the decoded access token (also this doesn’t seem to work)

My code

import jwt from 'jsonwebtoken'
import { NextRequest, NextResponse } from 'next/server'
import authService from './app/lib/auth.service'

const protectedRoutes = ['/dashboard']
const publicRoutes = ['/login', '/register', '/']

export function middleware(req: NextRequest) {
    const res = NextResponse.next()
    const path = req.nextUrl.pathname
    const isProtectedRoute = protectedRoutes.includes(path)
    const isPublicRoute = publicRoutes.includes(path)

    const isAuthorized = !isProtectedRoute || checkIfAuthorized(req, res)

    // Redirect to /login if the user is not authenticated
    if (isProtectedRoute && !isAuthorized) {
        return NextResponse.redirect(new URL('/login', req.nextUrl))
    }

    // Redirect to /dashboard if the user is authenticated and is trying to access a public route
    if (isPublicRoute && isAuthorized && !req.nextUrl.pathname.startsWith('/')) {
        return NextResponse.redirect(new URL('/dashboard', req.nextUrl))
    }

    return NextResponse.next()
}

const checkIfAuthorized = (req: NextRequest, res: NextResponse) => {
    const accessToken = req.cookies.get('accessToken')?.value
    if (!accessToken) return false

    // check expiration
    const decodedAccessToken = jwt.decode(accessToken) as any
    if (!decodedAccessToken) return false

    const accessExpiredAt = new Date(decodedAccessToken?.exp * 1000)
    const now = new Date()
    if (accessExpiredAt < now) {
        // we have to refresh
        const refreshToken = req.cookies.get('refreshToken')?.value
        if (!refreshToken) return false

        const decodedRefreshToken = jwt.decode(refreshToken) as any
        const refreshExpiredAt = new Date(decodedRefreshToken?.exp * 1000)
        if (refreshExpiredAt < now) return false
        
        // TODO: refresh - how? I cannot use async functions here?
        // await authService.refresh()
    }

    // set user if it's not set
    if (!req.cookies.get('currentUser')?.value) {
        // TODO: how? the following doesn't set the cookie
        req.cookies.set('currentUser', JSON.stringify(decodedAccessToken))
        res.cookies.set('currentUser', JSON.stringify(decodedAccessToken))
    }

    return true
}

// Routes Middleware should not run on (e.g. images)
export const config = {
    matcher: ['/((?!api|_next/static|_next/image|.*\.png$).*)'],
}

Print HTML page along with the styles [duplicate]

Looking for printing HTML page, the printing option is working, but I wanted to ignore the navigation bar in the print.

enter image description here

    <style>
        * {
    font-family: Arial, Helvetica, sans-serif;
    color: rgb(65, 65, 65);
    -webkit-print-color-adjust: exact !important;
    color-adjust: exact !important;
    print-color-adjust: exact !important;
}

@media print {
   @page {
     margin-left: 0.8in;
     margin-right: 0.8in;
     margin-top: 0;
     margin-bottom: 0;
   }
}

#container {
    width: 800px;
    margin: 0 auto;
}
    </style>

    <script>
        document.addEventListener("DOMContentLoaded", () => {
    let printLink = document.getElementById("print");
    let container = document.getElementById("container");

    printLink.addEventListener("click", event => {
        event.preventDefault();
        printLink.style.display = "none";
        window.print();
    }, false);

    container.addEventListener("click", event => {
        printLink.style.display = "flex";
    }, false);

}, false);
    </script>

Any suggestion would be appreciated.

Initialize the select2 in dynamic form in alpinejs

I’ve spent hours and hours on how I initialize the select2 on alpinejs in dynamic form.

  1. I have an html file with a select tag and Add button
  2. I initialize the select to be a select2

(Expected) When I click the Add button it will add another select form. That also should initialize as select 2

(Actual) : When I click the Add button it does not initialized as select2

I’ve tried every time I that I click the Add button it will trigger the initializeSelect2

It does work, but on 2nd to the last select form does not work

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <script src="//unpkg.com/alpinejs" defer></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
        <link
            href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css"
            rel="stylesheet"
        />
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
    </head>
    <body>
        <div
            x-data="{
        count: 1,
        selects: ['One', 'Two', 'Three'],
        toggle() { this.count++; initSelect2() }
    }"
        >
            <button @click="toggle()">Add</button>

            <template x-for="i in count" :key="i">
                <select id="" name="" class="select2 form-control">
                    <template x-for="(select, index) in selects" :key="index">
                        <option value="" x-text="select"></option>
                    </template>
                </select>
            </template>
        </div>
        <script>
            function initSelect2()
            {
                $(".select2").select2();
            }
            $(document).ready(function () {
                initSelect2();
            });
        </script>
    </body>
</html>

Playground Link

How is the order of Promise’s Handler (then – catch – finally) push into MicroTask queue in Javascript?

  • [Case 1]
new Promise((resolve, reject) => {
    resolve(1);
})
    .then((result) => console.log(result))
    .catch((error) => console.log(error))
    
new Promise((resolve, reject) => {
    reject('Error!');
})
    .then((result) => console.log(result))
    .catch((error) => console.log(error))

new Promise((resolve, reject) => {
    resolve(3);
})
    .then((result) => console.log(result))
    .catch((error) => console.log(error))

  • Result of expect: 1 – Error! – 3
  • Result of actual: 1 – 3 – Error!

=> When push Promise’s Handler into MicroTask queue, I think there is a priority: .then() > .catch()

  • [Case 2.1]
new Promise((resolve, reject) => {
    resolve(1);
})
    .finally(() => console.log('Promise settled! 1'))
    .then((result) => console.log(result))
    .catch((error) => console.log(error))
    
new Promise((resolve, reject) => {
    reject('Error!');
})
    .then((result) => console.log(result))
    .catch((error) => console.log(error))
    .finally(() => console.log('Promise settled! 2'))

new Promise((resolve, reject) => {
    resolve(3);
})
    .then((result) => console.log(result))
    .catch((error) => console.log(error))
    .finally(() => console.log('Promise settled! 3'))
  • Result of expect: Promise settled! 1 – Error! – 3 – 1 – Promise settled! 2 – Promise settled! 3
  • Result of actual: Promise settled! 1 – 3 – Error! – Promise settled! 2 – Promise settled! 3 – 1

=> When push Promise’s Handler into MicroTask queue, I think there is a priority: .finally() > .then() > .catch()

  • [Case 2.2]
new Promise((resolve, reject) => {
    resolve(1);
})
    .finally(() => console.log('Promise settled! 1'))
    .then((result) => console.log(result))
    .catch((error) => console.log(error))
    
new Promise((resolve, reject) => {
    reject('Error! 2');
})
    .finally(() => console.log('Promise settled! 2'))
    .then((result) => console.log(result))
    .catch((error) => console.log(error))

new Promise((resolve, reject) => {
    reject('Error! 3');
})
    .then((result) => console.log(result))
    .catch((error) => console.log(error))
    .finally(() => console.log('Promise settled! 3'))

new Promise((resolve, reject) => {
    resolve(4);
})
    .then((result) => console.log(result))
    .catch((error) => console.log(error))
    .finally(() => console.log('Promise settled! 4'))

  • Result of expect: Promise settled! Promise settled! 1 – Promise settled! 2 – Error! 3 – 4 – 1 – Error! 2 – Promise settled! 3 – Promise settled! 4
  • Result of actual: Promise settled! Promise settled! 1 – Promise settled! 2 – 4 – Error! 3 – Promise settled! 3 – Promise settled! 4 – 1 – Error! 2

=> When push Promise’s Handler into MicroTask queue, I think there is a priority: .finally() > .then() > .catch()

I don’t know if my thinking is correct? Hope you guys have experience explaining how it works. Many thanks!

Increasing Web Scraping speed with puppeteer

I am trying to create an Node.js API, that scrapes website, (I started only with Goodreads as a website to be scraped and will expand further when I first the optimize the approach) and provides the scraped data to the end user, which will be using my API.

My initial approach was planning the API structure, deciding to use puppeteer and then start creating. When creating the first endpoint successfully I noticed something – it tooks about 2-3 seconds in Postman, in order for the request to finish, which is really slow.

Here is my code:

scraper-handler.ts

import { NextFunction, Request, Response } from "express";
import { MOST_POPULAR_LISTS } from "../utils/api/urls-endpoints.js";
import { listScraper } from "./spec-scrapers/list-scraper.js";
import { lists } from "../utils/api/full-urls.js";
import puppeteer from "puppeteer";
import { GOODREADS_POPULAR_LISTS_URL } from "../utils/goodreads/urls.js";

export const scraperHandler = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const browser = await puppeteer.launch({
    // headless: false,
    // defaultViewport: null,
  });

  const pages = await browser.pages();

  await pages[0].setUserAgent(
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36"
  );

  switch (req.url) {
    case `/${MOST_POPULAR_LISTS}`: {
      const result = await listScraper(
        browser,
        pages[0],
        GOODREADS_POPULAR_LISTS_URL,
        1,
        ".cell",
        ".listTitle",
        ".listTitle"
      );

      res.status(200).json({
        status: "success",
        data: result,
      });
      break;
    }
    default: {
      next();
      break;
    }
  }
};

And here is the case /${MOST_POPULAR_LISTS}:

list-scraper.ts

import puppeteer, { Page } from "puppeteer";
import { Browser } from "puppeteer";

export const listScraper = async (
  browser: Browser,
  page: Page,
  url: string,
  pageI = 1,
  main: string,
  title = "",
  ref = ""
)  => {
  // const page = await browser.newPage();

  await page.goto(url, {
    waitUntil: "domcontentloaded",
  });
  
  const books = await page.evaluate(
    (mainSelector, titleSelector, refSelector) => {
      // const nextLink = document.querySelector('a[rel="next"]');

      // console.log(nextLink);
      const elements = document.querySelectorAll(mainSelector);
      
      return Array.from(elements)
        .slice(0, 3)
        .map((element) => {
          const title =
            titleSelector.length > 0 &&
            (element.querySelector(titleSelector) as HTMLElement | null)
              ?.innerText;
          const ref =
            refSelector.length > 0 &&
            (element.querySelector(refSelector) as HTMLAnchorElement | null)
              ?.href;

          return { title, ref };
        });
    },
    main,
    title,
    ref
  );
  // await page.click(".pagination > a");

  await browser.close();

  return books;
};

The imported variables values are not that important.

So my question is how I can optimize my approach and what techniques can I use, in order to make the scraping faster and thus drastically improve the performance of my API?

I searched various posts and many suggest some kind of manipulation of the CPU, but I didn’t understood how it could be used in my case. Also the Child process in Node.js was suggested quite few times.

Thank you in advance!

How to Delay a Fetch Request in JavaScript Without Using setTimeout or setInterval?

I’m working on a JavaScript project where I need to delay a fetch request. However, due to some project constraints, I can’t use setTimeout or setInterval. I’m aware that these are the usual methods for delaying execution in JavaScript, but I need an alternative approach because these functions have been overridden in our codebase.

I’ve considered using Promise or busy-waiting with a while loop, but these methods are not ideal as they either still use setTimeout under the hood or block the execution of other code.

Here’s a basic example of the kind of operation I’m trying to perform:

async function delayedFetch(url, delayTime) {
  // Need to delay here without using setTimeout or setInterval
  const response = await fetch(url);
  const data = await response.json();
  return data;
}

delayedFetch('https://api.example.com/data', 2000)
  .then(data => console.log(data));

Fastest method for updating 15 fields in db through api calls [closed]

I’m making a web application for complete business handling purpose.

In billing page, on submitting a bill, it has to generate a bill, reduce the stock, update our daily collected money, increase the sale of a particular product, update total tax, add new customer, add type of money transaction and has to add many more in the db through api.

I’m going to use next js, node js, mongodb for this project.( Suggest me, if I should change my db for better performance)

Please suggest me how to increase my billing speed

I’m thinking about two methods.

  1. To execute all the APIs using promise.all method. (I think it’s not the fastest method for 15 API calls in js)

    or

  2. To generate a bill and reduce the stock during billing. And update all other fields, of all our bills of that day, during mid night ( we do not create bills at this time)

Please suggest me the fastest method to generate bills and add all the fields in db.