Find specific element that follows another specific element

In CSS, if you want to target a specific element that immediately follows another specific element, you would use the next-sibling combinator:

<style>
/* any 'p' that immediately follows 'div' will be red */
div + p { color: red; }
</style>

<div>
  <p>foo</p>  <!-- black -->
</div>
<p>bar</p>    <!-- red   -->
<p>baz</p>    <!-- black -->

<div>
  <p>foo</p>  <!-- black -->
</div>
<p>bar</p>    <!-- red   -->
<p>baz</p>    <!-- black -->

But how to make it in JavaScript? I tried closest, but I’m not surprised it doesn’t work. If I understand its description on MDN, it is intended to work differently.

<div class="input" style="display: none">
foo
</div>
<div class="output"></div>

<div class="input" style="display: none">
foo
</div>
<div class="output"></div>

<script>
  'use strict';

  window.onload = function() {
    for (const input of document.querySelectorAll('.input')) {
      document.querySelector(input.closest('body > .output')).innerHTML = 'input.innerHTML';
    }
  }
</script>

How to make it work?

Implementing dynamic scope using with

Preface:
I have an app where I want to allow users to enter mostly mathematical code to create a simulation. It currently uses mathjs to evaluate code snippets, but without control statements it’s a bit inflexible. Even allowing a user to import arbitrary code and inject it into mathjs is somewhat obtuse. What I’d like is something that is relatively robust against accidental mistakes by non-malicious users.

Both mathjs and scraggy do this by walking parsed syntax trees with optional contexts passed in to provide free variable scopes. That seems to incur a large runtime overhead though, so I’ve worked out an alpha alternative based on with statements and a Proxy’d Map-like object, and I’m hoping to get some constructive criticism about performance and relative safety.

Here was my intent:

  1. prevent any writes to the globalThis, but allow access to global objects.
  2. allow ‘scoped’ contexts (I only need 3 deep). implementation below is derived from mathjs
  3. if a free variable is not found in any scope, create it in the current scope, otherwise update it in the scope its in.

Some lingering uncertainties:

  • I’m currently not parsing the content of the code snippets at all to remove bad stuff, but I’m also thinking that may not be required.
  • I don’t think I understand whether the [Symbol.unscopables] symbol would help protect me or help me shoot myself. I’d like to prevent someone from accidentally overwriting my Proxy’d object properties – is that the way to do that? Do I do that in the Proxy or the object?
  • I haven’t yet done performance tests, but the Proxy certainly involves some overhead.

Here’s the underlying Map-like class:

class MapScope  {
  constructor (parent=null) {
    this.localMap = new Map()
    this.parentScope = parent;
  }

  has (key) {
    return this.localMap.has(key) ? true : this.parentScope?.has(key) ?? false;
  }

  get (key) {
    return this.localMap.get(key) ?? this.parentScope?.get(key)
  }

  set (key, value) {
    const iGetIt = ! this.parentScope?.has(key) || this.localMap.has(key);
    return iGetIt ? this.localMap.set(key, value) : this.parentScope.set(key, value);
  }

  keys () {
    if (this.parentScope) {
      return new Set([...this.localMap.keys(), ...this.parentScope.keys()])
    } else {
      return this.localMap.keys()
    }
  }
  
  size() { return this.localMap.size();}

  forEach(cb, thisArg=this.localMap) {
    this.localMap.forEach(cb, thisArg);
  }
  
  delete (key) {
   // return false;
    return this.localMap.delete(key)
  }

  deleteProperty (p) {
    //return false;
    return this.localMap.delete(p)
 m }

  clear () {
    return this.localMap.clear()
  }

  toString () {
    return this.localMap.toString()
  }
}

Here’s the traps object for the Proxy:

var mapTraps = {
  // This says that variables in the local scope shadow the global ones
  // and that any new variables will be in the local scope
  has(target, key) {
    console.log(`called: has(..., ${key})`);
    if (key in globalThis && ! target.has(key)) {
      return false;
    }
    return true;
  },

  get(target,key,receiver) {
    if (!target.has(key)) {
      if (key in globalThis) {
        console.log(`get ${key.toString()} from globalThis`);
        return globalThis[key];
      } else {
        return undefined;
      }
    }
    console.log(`get ${key.toString()} from target`);
    return target.get(key);
  },

  // 
  set(target, key, val){
    console.log(`called: set(..., ${key.toString()})`);
    return target.set(key,val);
  }
}

Here’s how you put these two together – vars because noodling in Node:

var mscope = new MapScope()
var nscope = new MapScope(mscope)
var rscope = new MapScope(nscope)
var mproxy = new Proxy(mscope, mapTraps)
var nproxy = new Proxy(nscope, mapTraps)
var rproxy = new Proxy(rscope, mapTraps)

So mscope is the toplevel scope, nscope is between it and rscope.

Testing looks like this:

with (mproxy) {t = 0}
--> 0
with (mproxy) {t += 2 * Math.random()}
--> 1.75....
with(rproxy) {t<5}
--> true
with(nproxy) {t<5}
--> true

The intended use though is to use these functions to create runtime functions to run user code in the appropriate scope. See: Changing function’s scope for a similar solution or the MDN write-ups on the with statement and Proxy.

function compileSnippet(exp) {
  return new Function ("fscope", `
    with(fscope) {
     return ${exp} ;
    }
  `);
}

var startFn = compileSnippet(startExpr);
var startEachFn = compileSnippet(startEachExpr);

// evaluate in scope - typically for side-effect

startFn(nproxy)
...
startEachFn(nproxy)
...
// endEachFn and endFn also

ESLint rule to disallow useEffect without dependency list

Is there an ESLint rule for React to disallow writing useEffect without dependency list?

I’m looking for something like this:

useEffect(() => {
  if (error) handleError(error)
}) // ❌ I expect ESLint complains here, because there's no dependency list
useEffect(() => {
  if (error) handleError(error)
}, [error]) // ✅ Now it has an explicit dependency list

Nodejs time is one hour ahead from server time

I have a Node.js application and using date command in the terminal, I get the right time:

Sun Mar 30 12:38:25 PM +0330 2025

But using console.log( new Date().toLocaleString() ) I get this:

Sun Mar 30 13:38:25 PM +0330 2025

As you see it’s an hour ahead!

Why I get this and how to fix it?

Why does my browser submit emoji characters as html entities? [duplicate]

Someone submits a text field on my website and their submission is stored in my mysql database. Their comment contains an emoji character. If I store the comment as is, it will be stored as an html entity, such as &#128512;.

I read in another post that you should not convert special characters to html entities when storing them in your mysql database. But how about the opposite: are special characters so preferable to html entities that I should take the extra step and convert the visitor’s comment from an html entity to a special character before storing it in the database?

EDIT: In case anyone is interested, the reason the emoji characters were being submitted as html entities is that my html page lacked the correct charset setting. Once I set its charset to utf-8, emojis started to get stored as is, rendering my entire question moot.

PHPMYADMIN I can’t log in. Constant PhpMyAdminE_STRICT is deprecated

This error is displayed when logging in to phpmyadmin.

Deprecation Notice in ./libraries/classes/Url.php#221
http_build_query(): Passing null to parameter #2 ($numeric_prefix) of
type string is deprecated
Backtrace
./libraries/classes/Url.php#221: http_build_query(
array,
NULL,
string ‘&’,
)
./libraries/classes/Header.php#231: PhpMyAdminUrl::getCommonRaw()
./libraries/classes/Header.php#282: PhpMyAdminHeader->getJsParams()
./libraries/classes/Header.php#214: PhpMyAdminHeader->getJsParamsCode()
./libraries/classes/Header.php#142: PhpMyAdminHeader->_addDefaultScripts()
./libraries/classes/Response.php#100: PhpMyAdminHeader->__construct()
./libraries/classes/Response.php#134: PhpMyAdminResponse->__construct()
./libraries/classes/Plugins/Auth/AuthenticationCookie.php#87:
PhpMyAdminResponse::getInstance()
./libraries/classes/Plugins/AuthenticationPlugin.php#247:
PhpMyAdminPluginsAuthAuthenticationCookie->showLoginForm()
./libraries/common.inc.php#353: PhpMyAdminPluginsAuthenticationPlugin->authenticate()
./index.php#27: require_once(./libraries/common.inc.php)
Deprecation Notice in ./../../php/Twig/Loader/FilesystemLoader.php#40
realpath(): Passing null to parameter #1 ($path) of type string is deprecated
Backtrace
FilesystemLoader.php#40: realpath(NULL)
./libraries/classes/Template.php#61: TwigLoaderFilesystemLoader->__construct(string ‘templates/’)
./libraries/classes/Template.php#102: PhpMyAdminTemplate->__construct(string ‘login/header’)
./libraries/classes/Plugins/Auth/AuthenticationCookie.php#111: PhpMyAdminTemplate::get(string ‘login/header’)
./libraries/classes/Plugins/AuthenticationPlugin.php#247: PhpMyAdminPluginsAuthAuthenticationCookie->showLoginForm()
./libraries/common.inc.php#353: PhpMyAdminPluginsAuthenticationPlugin->authenticate()
./index.php#27: require_once(./libraries/common.inc.php)
Deprecation Notice in ./libraries/classes/Url.php#221
http_build_query(): Passing null to parameter #2 ($numeric_prefix) of type string is deprecated
Backtrace
./libraries/classes/Url.php#221: http_build_query(
array,
NULL,
string ‘&’,
)
./libraries/classes/Url.php#169: PhpMyAdminUrl::getCommonRaw(
array,
string ‘?’,
)
./libraries/classes/Core.php#749: PhpMyAdminUrl::getCommon(array)
./../../../../../../var/lib/phpmyadmin/tmp/twig/91/91211ba25b99b1424ac2dd7e72af0c0b7ef97ed8e59a13e24b13143b76ee353b.php#40:
PhpMyAdminCore::linkURL(string ‘https://www.phpmyadmin.net/’)
Template.php#407: __TwigTemplate_dd64914d2ea903cb7e97449fb1a49d0d1b0386bce92be9283cbffd5f6c826508->doDisplay(
array,
array,
)
Template.php#380: TwigTemplate->displayWithErrorHandling(
array,
array,
)
Template.php#392: TwigTemplate->display(array)
TemplateWrapper.php#45: TwigTemplate->render(
array,
array,
)
./libraries/classes/Template.php#133: TwigTemplateWrapper->render(array)
./libraries/classes/Plugins/Auth/AuthenticationCookie.php#111:
PhpMyAdminTemplate->render(array)
./libraries/classes/Plugins/AuthenticationPlugin.php#247:
PhpMyAdminPluginsAuthAuthenticationCookie->showLoginForm()
./libraries/common.inc.php#353: PhpMyAdminPluginsAuthenticationPlugin->authenticate()
./index.php#27: require_once(./libraries/common.inc.php)
Deprecation Notice in ./../../php/Twig/Node/Node.php#161
Return type of TwigNodeNode::count() should either be compatible with Countable::count(): int, or the
#[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice
Backtrace
autoload.php#369: require(./../../php/Twig/Node/Node.php)
{closure:/usr/share/php/Twig/autoload.php:6}(string ‘TwigNodeNode’)
TwigFilter.php#150: class_exists(string ‘TwigNodeNode’)
autoload.php#369: require(./../../php/Twig/TwigFilter.php)
CoreExtension.php#214: {closure:/usr/share/php/Twig/autoload.php:6}(string
‘TwigTwigFilter’)
ExtensionSet.php#433: TwigExtensionCoreExtension->getFilters()
ExtensionSet.php#423: TwigExtensionSet->initExtension()
ExtensionSet.php#184: TwigExtensionSet->initExtensions()
Environment.php#871: TwigExtensionSet->getFunction(string ‘Message_error’)
./../../../../../../var/lib/phpmyadmin/tmp/twig/91/91211ba25b99b1424ac2dd7e72af0c0b7ef97ed8e59a13e24b13143b76ee353b.php#55:
TwigEnvironment->getFunction(string ‘Message_error’)
Template.php#407: __TwigTemplate_dd64914d2ea903cb7e97449fb1a49d0d1b0386bce92be9283cbffd5f6c826508->doDisplay(
array,
array,
)
Template.php#380: TwigTemplate->displayWithErrorHandling(
array,
array,
)
Template.php#392: TwigTemplate->display(array)
TemplateWrapper.php#45: TwigTemplate->render(
array,
array,
)
./libraries/classes/Template.php#133: TwigTemplateWrapper->render(array)
./libraries/classes/Plugins/Auth/AuthenticationCookie.php#111:
PhpMyAdminTemplate->render(array)
./libraries/classes/Plugins/AuthenticationPlugin.php#247:
PhpMyAdminPluginsAuthAuthenticationCookie->showLoginForm()
./libraries/common.inc.php#353: PhpMyAdminPluginsAuthenticationPlugin->authenticate()
./index.php#27: require_once(./libraries/common.inc.php)
Deprecation Notice in ./../../php/Twig/Node/Node.php#166
Return type of TwigNodeNode::getIterator() should either be compatible with IteratorAggregate::getIterator(): Traversable, or the
#[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice
Backtrace
autoload.php#369: require(./../../php/Twig/Node/Node.php)
{closure:/usr/share/php/Twig/autoload.php:6}(string ‘TwigNodeNode’)
TwigFilter.php#150: class_exists(string ‘TwigNodeNode’)
autoload.php#369: require(./../../php/Twig/TwigFilter.php)
CoreExtension.php#214: {closure:/usr/share/php/Twig/autoload.php:6}(string
‘TwigTwigFilter’)
ExtensionSet.php#433: TwigExtensionCoreExtension->getFilters()
ExtensionSet.php#423: TwigExtensionSet->initExtension()
ExtensionSet.php#184: TwigExtensionSet->initExtensions()
Environment.php#871: TwigExtensionSet->getFunction(string ‘Message_error’)
./../../../../../../var/lib/phpmyadmin/tmp/twig/91/91211ba25b99b1424ac2dd7e72af0c0b7ef97ed8e59a13e24b13143b76ee353b.php#55:
TwigEnvironment->getFunction(string ‘Message_error’)
Template.php#407: __TwigTemplate_dd64914d2ea903cb7e97449fb1a49d0d1b0386bce92be9283cbffd5f6c826508->doDisplay(
array,
array,
)
Template.php#380: TwigTemplate->displayWithErrorHandling(
array,
array,
)
Template.php#392: TwigTemplate->display(array)
TemplateWrapper.php#45: TwigTemplate->render(
array,
array,
)
./libraries/classes/Template.php#133: TwigTemplateWrapper->render(array)
./libraries/classes/Plugins/Auth/AuthenticationCookie.php#111:
PhpMyAdminTemplate->render(array)
./libraries/classes/Plugins/AuthenticationPlugin.php#247:
PhpMyAdminPluginsAuthAuthenticationCookie->showLoginForm()
./libraries/common.inc.php#353: PhpMyAdminPluginsAuthenticationPlugin->authenticate()
./index.php#27: require_once(./libraries/common.inc.php)

And then this one. And I can’t do anything.

Error during session start; please check your PHP and/or webserver log file and configure your PHP installation properly. Also ensure that cookies are enabled in your browser.

Constant PhpMyAdminE_STRICT is deprecated

1

Using a base/generic type class as a parameter in a method

I am trying to use the implements of PHP where the parameter is a base/generic type class.

BaseFormRequest.php

class BaseFormRequest extends FormRequest
{
... methods here
}

StorePostRequest.php

class StorePostRequest extends BaseFormRequest
{
... methods here
}

IController.php

interface IController
{
    public function store(BaseFormRequest $request);
}
class PostController extends Controller implements IController
{

    public $service;

    public function __construct(PostService $service)
    {
        $this->service = $service;
    }

    public function store(StorePostRequest $request)
    {
        $post = $this->service->store($request);
    }
}

As you can see in the code:

  1. in StorePostRequest, it extends the BaseFormRequest.
  2. in the IController, the parameter in store method is type BaseFormRequest.
  3. in PostController, the parameter in store method is type StorePostRequest.

I am getting the error

Declaration of PostController::store(StorePostRequest $request) must be compatible with IController::store(AppHttpRequestsBaseFormRequest $request)

What I do know is that

  1. if I remove the implements IController, the code works as intended
  2. if I change the PostController@store param to BaseFormRequest, or IController@store param to StorePostRequest the error is fixed, but I cant customize the rules in each model this way.

Is it not possible to use a generic class in interface so that when I implement it in my controller, I can use the correct class that extends to the generic class?

How to let end user change password created by dovecot

all
I’ve followed this link:
https://www.linode.com/docs/guides/email-with-postfix-dovecot-and-mysql/
to setup an email server to host multiple email domains. Everything works fine. I was wondering if anybody knows how to let the email end user to setup their own password when their accounts are created. As it is now, I need to use the command:
sudo doveadm pw -s SHA512-CRYPT
to create a password for an user and then input the password hash to the sql server. In other words, I want to automate this process of changing password through a webpage or online interface. I don’t have much experience of writing encrypted php codes. Is there such software or code snippet already existed ?

Span doesn’t show social name [closed]

I have this screen to edit user information (fictional, not from a real person). All other fields (name, birth date, age, address, etc.) work and show just fine, but not the social name. The request also does not show on the network tab when pressing F12 in the browser.

enter image description here

Some related function in jsonParser to load the social name is called loadNomeSocial, it is called first here. I tried to debug this function but nothing shows up in the console:

function jsonParseInfoPessoa(json) {
    let objJson = JSON.parse(json);
    usuarioJson = objJson;
    nome = objJson[0].nome;
    $('.nome').append(nome);
    let controleConta = $('#bloqConta');

    if (objJson[0].excluido == 1) {
        $('#nomeLabel').append(nome + "- Usuário Desativado");
        //adicionando botao de reativar
        controleConta.append('<a href="control/main.php?req=ativaConta&id=' + identificador + '" class="btn btn-primary">Reativar conta</a>');
    } else {
        //botao de desativar
        $('#nomeLabel').append(nome);
        controleConta.append('<a href="control/main.php?req=desativaConta&id=' + identificador + '" class="btn btn-danger">Desativar conta</a>');
    }

    //formatando data de nascimento objJson[0].data_nascimento
    let nascFormatada = objJson[0].data_nascimento.split('-');
    nascFormatada = nascFormatada[2] + ' / ' + nascFormatada[1] + ' / ' + nascFormatada[0];
    let idade = calculaIdade(objJson[0].data_nascimento);
    $('#nasc').append(nascFormatada+'<br>Idade: '+idade + ' Anos');
    if (objJson[0].menor_idade === "1") {
        loadMenor();
        $('#maiorIdade').attr('hidden',true);
    } else {
        loadContato(identificador);
        loadEnd(identificador);
        loadDocument();
        loadDepententes();
        loadLogin(identificador);
        loadNomeSocial(identificador);
    }
    if (objJson[0].ruralino === "1") {
        loadRuralino();
    } else {
        btnInsertRuralino();
    }
    if (objJson[0].excluido == '0') addBtnEdicaoPessoa();
}

Function that makes the request and loads the social name:

function loadNomeSocial(id) {
    ajaxLoadGET('control/main.php?req=selectNomeSocialByPessoaId&id=' + id, parseNomeSocial, '#nome_social');

    function parseNomeSocial(json, corpo) {
    console.log("Resposta da requisição Nome Social:", json);
    let objJson = JSON.parse(json);
    if (objJson.length > 0) {
        $('#nome_social').append(objJson[0].nomesocial);
    } else {
        console.log("Nenhum nome social encontrado.");
    }
}
}

Function that loads the values when clicking the pencil icon to edit them:

function editUsuarioNome() {
    $('#btNome').removeAttr("onclick");
    let dadosBasicos = $('#nomeNasc');

    ajaxLoadGET('control/main.php?req=selecUsuarioLogado', function(response) {
        let userData = typeof response === 'string' ? JSON.parse(response) : response;

        // Log do valor exato e seu tipo para diagnóstico
        console.log("Valor de nv_acesso:", userData.nv_acesso);
        console.log("Tipo de nv_acesso:", typeof userData.nv_acesso);
        console.log("Código de caracteres:", Array.from(userData.nv_acesso || "").map(c => c.charCodeAt(0)));

        // Adicionar log para nome_social
        console.log("Valor de nome_social:", nome_social);
        console.log("Tipo de nome_social:", typeof nome_social);
        console.log("Código de caracteres nome_social:", Array.from(nome_social || "").map(c => c.charCodeAt(0)));

        // Normalização do valor para evitar problemas com acentos ou espaços
        let nivelNormalizado = "";
        if (userData.nv_acesso) {
            nivelNormalizado = userData.nv_acesso.trim().normalize("NFD").replace(/[u0300-u036f]/g, "");
        }
        console.log("Nível normalizado:", nivelNormalizado);

        let nasc = usuarioJson[0].data_nascimento;
        dadosBasicos.empty();
        let opcoesSelect = "";

        // Abordagem inversa - exibir Coordenação para todos EXCETO para níveis específicos
        let niveisComuns = ["Administrador", "Professor", "Aluno", "Visitante"];
        let isNivelComum = niveisComuns.some(nivel =>
            userData.nv_acesso === nivel || nivelNormalizado === nivel
        );

        // Se NÃO for um dos níveis comuns, assumimos que é Coordenação
        if (!isNivelComum) {
            opcoesSelect += `<option value=5>${CargoCoordenador}</option>`;
        }
        opcoesSelect += `
            <option value=4>Visitante</option>
            <option value=3>${CargoAluno}</option>
            <option value=2>${CargoProf}</option>
            <option value=1>${CargoAdm}</option>
        `;

        // Adicionar um evento para capturar quando o campo nome_social é alterado
        dadosBasicos.append(`
            <form action="control/main.php?req=updateDadosBasicos&id=${identificador}" method="POST">
                <p>Nível de Acesso: <select id="nv_acesso" name="nv_acesso">${opcoesSelect}</select></p>
                <p>Nome: <input type='text' name='nome' value="${nome}" required="required"></p>
                <p>Data nascimento: <input type="date" name="nascimento" value="${nasc}" required="required"></p>
                <p>Nome Social: <input type='text' name='nome_social' value="${nome_social}" id="nomeSocial"></p>
                <br/>
                <input type="submit" class="btn btn-primary" value="Gravar"/>
            </form>
        `);

        // Adicionar evento para monitorar alterações no campo nome_social
        $('#nomeSocial').on('input', function() {
            console.log("Nome Social alterado para:", $(this).val());
        });

        // Adicionar um interceptador para o envio do formulário para ver os dados antes do envio
        $('form').on('submit', function(e) {
            // Para fins de debug, você pode querer ver o que está sendo enviado
            console.log("Dados do formulário a serem enviados:");
            const formData = new FormData(this);
            for (const pair of formData.entries()) {
                console.log(pair[0] + ': ' + pair[1]);
            }

            // Remova esta linha se quiser interromper o envio para debug
            // e.preventDefault();
        });
    }, '#nv_acesso');
}

The console for nome_social shows:

Valor de nome_social:
jsonParser.min.js:17 Tipo de nome_social: string
jsonParser.min.js:17 Código de caracteres nome_social: []length: 0[[Prototype]]: Array(0)

jsonParsermin function:

function loadNomeSocial(id){console.log("Chamando loadNomeSocial com ID:",id),ajaxLoadGET("control/main.php?req=selectNomeSocialByPessoaId&id="+id,parseNomeSocial,".carr");function parseNomeSocial(json,corpo){console.log("Resposta da requisição Nome Social:",json);let objJson=JSON.parse(json);objJson.length>0?$(".nome-social").append(objJson[0].nomesocial):console.log("Nenhum nome social encontrado.")}}

Div where the span is:

<div id="nomeNasc">
    <p>Nome: <span class="nome"> </span></span></p>
    <p>data nascimento: <span id="nasc"></span></p>
    <p>Nome Social: <span id="nome_social"></span></p>
</div>

sh: tailwind: command not found [closed]

enter image description here

I am developing a project of a blog system, and while being in the early stages of that, while setting up the project, while setting up tailwind, I got this error.

this terminal screenshot shows all the errors and I am not able to run script: npx tailwindcss init -p and it shows the error sh: tailwind: command not found

Terminal showing error

Issues with Render.js: Problems with Puppeteer and Parallel Rendering

I’m having trouble with a Node.js script (render.js) that uses Puppeteer for rendering videos and images in parallel. The script creates a renderer that generates frames based on an HTML page and then combines them into either PNG files or video files using FFmpeg. The script uses multiple worker processes to handle rendering concurrently.

You can find the code for this project on GitHub here: https://github.com/dtinth/html5-animation-video-renderer

However, I’m encountering an issue where the rendering process is not functioning as expected. Here’s an overview of the problem:

Error:
When I run the command:

node render --url="file:///D:/Desktop/airports/New%20folder/Flourish%20template_%20Bar%20chart%20race.htm" --png="D:/Desktop/airports/New%20folder/PNG_output" --no-video

I get the following error output:

Spawn worker 1
Worker 1: getInfo
render

Renders a video

Options:
  --version      Show version number                                   [boolean]
  --help         Show help                                             [boolean]
  --url          The URL to render
                                [string] [default: "file://D:DesktopNew folder
                                 (5)PNG/examples/gsap-hello-world.html?render"]
  --video        The path to video file to render. Without `--alpha` this MUST
                 be .mp4, and with `--alpha` this MUST be .mov
                                                 [string] [default: "video.mp4"]
  --parallelism  How many headless Chrome processes to use to render in parallel
                                                           [number] [default: 8]
  --start        Frame number to start rendering           [number] [default: 0]
  --end          Frame number to end rendering (that frame number will not be
                 rendered)                                              [number]
  --png          Directory for PNG frame output                         [string]
  --alpha        Renders a image/video with alpha transparency. For video, the
                 file extension MUST be .mov                           [boolean]
  --scale        Device scale factor                       [number] [default: 1]

Error: Evaluation failed: ReferenceError: getInfo is not defined
    at __puppeteer_evaluation_script__:9:22
    at ExecutionContext._evaluateInternal (D:DesktopNew folder (5)PNGnode_modulespuppeteerlibcjspuppeteercommonExecutionContext.js:175:23)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async ExecutionContext.evaluate (D:DesktopNew folder (5)PNGnode_modulespuppeteerlibcjspuppeteercommonExecutionContext.js:110:16)
    at async D:DesktopNew folder (5)PNGrender.js:21:20
    at async Object.getInfo (D:DesktopNew folder (5)PNGrender.js:48:17)
    at async work (D:DesktopNew folder (5)PNGrender.js:128:24)
    at async Object.main [as handler] (D:DesktopNew folder (5)PNGrender.js:261:20)

The error suggests that there is an issue with getInfo not being defined. However, I’m not sure why it is failing or where I should define this function.

What I’ve tried:

  • Ensuring that the getInfo function is properly defined and
    accessible.
  • Verifying that the script is correctly passing information between
    workers and handling the necessary functions.
  • Adding more logging to track down the flow of execution, but the
    issue persists.

The goal:
I want the script to render frames from the provided URL and output PNGs to the specified directory without creating a video, but it’s failing with this getInfo is not defined error.
Has anyone worked with Puppeteer and parallel rendering in Node.js and encountered similar issues? Any suggestions on how to properly define or handle the getInfo function, or how to debug this further, would be greatly appreciated!

Thanks in advance for your help!

Data not rendering in Mantine’s Select Component

The cities data is coming from an Api cityOptions is being logged to
the console, but
when I try to show it in the UI in a dropdown, no data shows.

const cityOptions = cities?.map((city) => ({
    value: city.id.toString(),
    label: city.name,
  })) || [];
  console.log("cityoptions", cityOptions)

<Select
  name="city"
  placeholder="Cities"
  value={city || null}
  maw={200}
  size="md"
  data={isLoading ? []: cityOptions}
  disabled={isLoading}
  onChange={(value) => setCity(value as string)}
  icon={<IconSelector size={18} stroke={1.75} />}
  clearable
  style={{ marginBottom: 0 }}
/>

How can I redirect correctly after logging into Twitter?

When the user is logged in, the code works correctly, the user authorizes the app and redirects me correctly to –> api/x/callback, the problem is when I have a user who is not logged in to X, when I access –> api/auth/x/callback, it redirects me to X’s login, I log in correctly, but it does not redirect me correctly to the (Authorize App) page, but instead it redirects me to X’s profile, does anyone know a solution to this problem, I would greatly appreciate your help

this is –> api/auth/x/callback

import { NextResponse } from 'next/server'
import crypto from 'crypto'

const X_CLIENT_ID = process.env.X_CLIENT_ID as string
const REDIRECT_URI = `${process.env.NEXT_PUBLIC_URL}${process.env.NEXT_PUBLIC_X_REDIRECT_URI}`

export async function GET() {
  if (!X_CLIENT_ID) {
    return NextResponse.json(
      { error: 'X_CLIENT_ID is not defined' },
      { status: 500 }
    )
  }

  const codeVerifier = crypto.randomBytes(32).toString('hex')
  const codeChallenge = crypto
    .createHash('sha256')
    .update(codeVerifier)
    .digest('base64url')

  const response = NextResponse.redirect(
    `https://twitter.com/i/oauth2/authorize?${new URLSearchParams({
      response_type: 'code',
      client_id: X_CLIENT_ID,
      redirect_uri: REDIRECT_URI,
      scope: 'tweet.read tweet.write users.read offline.access',
      state: crypto.randomBytes(16).toString('hex'),
      code_challenge: codeChallenge,
      code_challenge_method: 'S256'
    })}`
  )

  response.cookies.set('code_twitter_verifier', codeVerifier, {
    httpOnly: true,
    secure: true,
    sameSite: 'lax',
    path: '/'
  })

  return response
}

this is –> api/x/callback

import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'

const X_CLIENT_ID = process.env.X_CLIENT_ID as string
const X_CLIENT_SECRET = process.env.X_CLIENT_SECRET as string
const REDIRECT_URI = `${process.env.NEXT_PUBLIC_URL}${process.env.NEXT_PUBLIC_X_REDIRECT_URI}`

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url)
  const code = searchParams.get('code')

  if (!code) {
    const redirectUrl = new URL(
      '/admin/organizations',
      request.url
    )

    return NextResponse.redirect(redirectUrl)
  }

  const codeVerifier = cookies().get('code_twitter_verifier')?.value
  if (!codeVerifier) {
    return NextResponse.json(
      { error: 'code_verifier not found' },
      { status: 400 }
    )
  }

  const credentials = Buffer.from(`${X_CLIENT_ID}:${X_CLIENT_SECRET}`).toString(
    'base64'
  )

  const tokenResponse = await fetch('https://api.twitter.com/2/oauth2/token', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: `Basic ${credentials}`
    },
    body: new URLSearchParams({
      grant_type: 'authorization_code',
      code,
      redirect_uri: REDIRECT_URI,
      code_verifier: codeVerifier
    }).toString()
  })

  const tokenData = await tokenResponse.json()

  if (!tokenResponse.ok) {
    return NextResponse.json(
      { error: 'No se pudo obtener el token' },
      { status: 401 }
    )
  }

  const { access_token, refresh_token, expires_in } = tokenData

  const userResponse = await fetch('https://api.twitter.com/2/users/me', {
    headers: {
      Authorization: `Bearer ${access_token}`
    }
  })

  const userData = await userResponse.json()

  const { id, username } = userData.data

  if (!userResponse.ok) {
    return NextResponse.json({ error: 'User not found' }, { status: 401 })
  }

  const redirectUrl = new URL(
    '/admin/organizations/channels/twitter',
    request.url
  )
  redirectUrl.searchParams.append('accessToken', access_token)
  redirectUrl.searchParams.append('refreshToken', refresh_token)
  redirectUrl.searchParams.append('userId', id)
  redirectUrl.searchParams.append('screenName', username)
  redirectUrl.searchParams.append('expiresIn', expires_in)

  return NextResponse.redirect(redirectUrl)
}

Why does vite use dirname(fileURLToPath(import.meta.url))?

The vite build documentation gets the directory of vite.config.js like this:

const __dirname = dirname(fileURLToPath(import.meta.url))

And I was curious why it’s being done like this. According to this question we can get the __dirname directory via import.meta.dirname for more recent versions of node, so is const __dirname = dirname(fileURLToPath(import.meta.url)) just an older way of doing it?

parse: expected property name or ‘}’

error code

const exp = JSON.parse('<%= JSON.stringify(cafe.reviews || []) %>');

& # 3 9 ; causing issue. ans tried every thing around the internet but still having same error..

code:

<script>
    const exp = JSON.parse('<%= JSON.stringify(cafe.reviews || []) %>');

    function escapeHTML(str) {
        return str.replace(/[&<>"']/g, match => ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#39;'
        }[match]));
    }

    const experience = document.querySelector('.usersExperience');
    if (experience) {
        experience.innerHTML = exp.map(review => `
          <div>
            <h4>${escapeHTML(review.userId?.name || "N/A")}</h4>
            <h3>${escapeHTML(review.userId?.dietaryIdentity || "N/A")}</h3>
            <p>${escapeHTML(review.review || "N/A")}</p>
          </div>
        `).join("");
    }
  </script>

guys. What am i doing wrong