How to submit selected rows from DataTables in a form

I am using DataTables multi item selection and like to submit the selected rows to my form.

Of course, I could manually create an input element for each row in my table:

<input type="hidden" id="row_0" name="par" value="456" disabled="disabled" />
<input type="hidden" id="row_1" name="par" value="876" disabled="disabled" />
...

and then toggle the disabled attribute based on the row selection. Something like this:

for (let row of table.rows({ selected: true })) {
  $(`#row_${row.index()}`).removeAttr("disabled");
}

But maybe there is an easier solution which requires less coding, I did not find any.

TypeScript Error: “Cannot redeclare block-scoped variable ‘x'” when variables are in different files [duplicate]

TypeScript Error: “Cannot redeclare block-scoped variable ‘x'” when variables are in different files

I’m working on a Node.js/TypeScript project and I’m encountering a strange error. I have two separate TypeScript files with variables that have the same name, but TypeScript is complaining about redeclaration.

My setup:

File B (module-practice.ts):

const x = 'Variable X';
console.log(x);
// other code...
module.exports = () => {
  console.log('I am X ......');
  console.log(x);
};

File A (index.ts):

const fn = require('./module-practice');
console.log(fn);
const x = 'Again Variable X';  // Error happens here
fn();

The error I’m getting:

Cannot redeclare block-scoped variable 'x'.

What I’ve tried:

When I add export {}; in file A (index.ts), the error goes away.

My question:

  1. Why am I getting this error when the variables are in completely different files?
  2. Why does adding export {}; fix the issue?
  3. Is this the correct solution or is there a better approach?

I’m confused because I thought each file would have its own scope for variables, especially.

How to enable CSRF protection in Laravel 12 API

I’m developing a Laravel (v12) API-based backend. I want to implemented CSRF protection but I can’t figure out how It’s gonna be doing in Laravel version 12.x.

I read Laravel 12 CSRF protection document but it couldn’t help me.

So how can I use CSRF protection on Laravel 12 APIs?

I tried following way and it I got nothing (CSRF token is not required from server):

<?php

use IlluminateFoundationApplication;
use IlluminateFoundationConfigurationExceptions;
use IlluminateFoundationConfigurationMiddleware;
use IlluminateFoundationHttpMiddlewareVerifyCsrfToken;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->validateCsrfTokens();
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();

enter image description here

Return 200 status code with Location header

PHP documentation for the header() function tells us:

There are two special-case header calls… The second special case is the “Location:” header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.

However, I want to return a 200 status code with a Location header. How can I do this, if at all? I have tried a few variations on the following with no luck:

header('Location: https://example.com/foo', true, 200);
http_response_code(200);
header('HTTP/1.1 200 OK', true, 200);
header('Content-Type: application/json');
echo '{"test":"testing"}';

According to my understanding of the PHP source, the first line should do it because of the explicitly specified status code:

if ((SG(sapi_headers).http_response_code < 300 ||
    SG(sapi_headers).http_response_code > 399) &&
    SG(sapi_headers).http_response_code != 201) {
    /* Return a Found Redirect if one is not already specified */
    if (http_response_code) { /* user specified redirect code */
        sapi_update_response_code(http_response_code);
    } else if (SG(request_info).proto_num > 1000 &&
       SG(request_info).request_method &&
       strcmp(SG(request_info).request_method, "HEAD") &&
       strcmp(SG(request_info).request_method, "GET")) {
        sapi_update_response_code(303);
    } else {
        sapi_update_response_code(302);
    }
}

Composer: how to use local symlinks for packages in development but Git versions in production

I have a project with a composer.json where some libraries are pulled from our GitLab:

"require": {
    "my/library": "1.0.0",
    "my/library-second": "1.2.1"
}

On production, this works fine — Composer fetches the packages from Git.

However, during development, I need to make changes to these libraries locally without creating a release. I want to use path repositories with symlink to my local folder.

The problems I face:

  • If I add local path repositories directly to the main composer.json, it breaks the production build.

  • Using replace or dev-master leads to conflicts with the fixed versions (1.0.0 / 1.2.1).

  • Ideally, I want a way to have a separate local composer.json or override only on the dev machine, so that:

  1. locally the packages are installed as symlinks,

  2. on production the stable Git versions are used,

  3. the main composer.json remains unchanged.

Question:

What is the proper way to structure Composer for this use case?

  • Is there a standard practice or common pattern to separate local and production Composer configuration, while keeping symlinks for local packages during development?

  • How do PHP projects usually handle local development with symlinks on packages without touching production composer.json?

Use a reference to $a to make $a a reference to $b

I have an array $arr = ['a', ['b',['c','d','e']]];.
So $arr[1][1][0] is 'c'.

I have these indexes listed in n array: $idx = [1,1,0];
(this may sound tricky, but comes from the fact that I got them from parsing a kind of scripting pseudo-language).

I have a recursive function which returns a reference to the expected element:
function &getDeepRef(&$array, $indexes){...}

Usage:
$ref = & getDeepRef($arr, $idx);

At that point, everything works as expected:
echo $ref;===> outputs 'c'
$ref = 12;
print_r($arr); ==> $arr is now ['a', ['b',[12,'d','e']]]

Here comes my question:
I need $arr[1][1][0] to become a reference to another variable $otherVar.
Can I do this using the $ref reference?

If yes, I couldn’t find the right syntax for this
($ref = &$OtherVar; unsets $ref as a reference to $arr[1][1][0], and makes it a reference to $otherVar, but in no way helps make $arr[1][1][0] a reference to $otherVar).

If no, how would you make the array element which indexes are listed in an array, become a reference to a given variable?

[Edit]
I found a solution based on eval();, but I’d rather use another way for security reasons:

    $arr = ['a', ['b', 'ii'=> ['c','d','e']],'f'];
    out($arr);
    
    $idxLeft  = [2];
    $idxRight = [1,'ii',0];
    
    $ref = &getDeepRef($arr,$idxRight);//$ref now is a reference to $arr[1]['ii'][0]
    $ref = 'ccc';//demo: $arr[1]['ii'][0] is now 'ccc'
    out($arr);
    
    //Now the target: $arr[2] = &$arr[1]['ii'][0];
    //Following does NOT work:
    $leftRef  = &getDeepRef($arr,$idxLeft);
    $rightRef = &getDeepRef($arr,$idxRight);
    $leftRef = &$rightRef; //this did NOT make $arr[2] a reference to $arr[1]['ii'][0]
        //instead it broke the reference from $leftRef on $arr[2] and made a new reference from $leftRef onto $arr[1]['ii'][0].
    
    //Following DOES work, but I'd prefer avoiding eval();  [notice: the mapping with json_encode is just here for string indexes compatibility, like 'ii']
    $eval = '$arr['. implode('][',array_map('json_encode',$idxLeft)) . '] = &$arr['. implode('][',array_map('json_encode',$idxRight)) . '];';
    out($eval);
    eval($eval);
    out($arr);
    
    $a = &getDeepRef($arr,$idxLeft);
    $a=45;
    out($arr);


    function &getDeepRef(&$var,$indexes){//third param just for exception message
        if(null===($id=array_shift($indexes))){ return $var; }
        if(!is_array($var) || !array_key_exists($id, $var)){ throw new Exception("Bad key: [$id]"); }
        return getDeepRef($var[$id],$indexes);
    }
    
    function out($v){
        static $i=0;
        echo '<br>'.++$i.' - '; print_r($v);
    }

How to run tests of the same phpunit testcase class in parallel with ParaTest?

I have a contrived test case showcasing how multiple test cases can slow the entire execution time down, as even though each is quick on its own, they add up if waited for before executing the next.

use PHPUnitFrameworkTestCase;

class ShouldTestInParallel extends TestCase
{
    /**
     * @dataProvider delayProvider
     */
    public function testItRunsTestsInParallel(int $delay)
    {
        sleep($delay);
        $this->assertTrue(true);
    }

    public function delayProvider()
    {
        return array_map(function ($value) {
            return [$value];
        }, array_fill(0, 10, 1));
    }

}

In order speed up test execution time, I installed paratest:

composer require brianium/paratest --dev

Now I expected the test to finish after 1 seconds.

I execute the test via phpstorm (and have enabled the paratest config), yet the entire test run still takes ~10s as each test is executed one after the other.

/bin/php -d memory_limit=5G /myproject/vendor/bin/paratest_for_phpstorm /myproject/library/vendor/phpunit/phpunit/phpunit --bootstrap /myproject/tests/bootstrap.php --debug --verbose --configuration /myproject/tests/phpunit.xml --filter Test\Vm\ShouldTestInParallel --test-suffix ShouldTestInParallel.php /myproject/tests/Vm --teamcity
Testing started at 1:57 PM ...
PHPUnit 9.6.25 by Sebastian Bergmann and contributors.

Runtime:       PHP 8.0.30
Configuration: /myproject/tests/phpunit.xml

Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #0 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #1 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #2 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #3 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #4 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #5 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #6 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #7 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #8 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #9 (1)' ended


Time: 00:10.026, Memory: 28.00 MB

OK (10 tests, 10 assertions)
Process finished with exit code 129 (interrupted by signal 1:SIGHUP)

How To Keep user logged in on refresh but log out on browser/tab close in Angular?

How can i make my angular application maintain the user session on page refresh but automatically log out the user when the browser tab or windows is closed?

What I Tried

  1. I used the beforeunload event in Angular (window.addEventListener(‘beforeunload’, …)) to know when the tab is closing.

  2. I called my authService.logout() inside this event to log the user out.

  3. But I noticed this also runs when the page refreshes or when the user navigates away, which I don’t want.

  4. I also checked the MDN docs and tried using returnValue for the unload event, but it shows the generic browser message and still activates on refresh.

What I Expected

  1. When the user refreshes the Angular page, the session/token should be kept so they remain logged in.

  2. When the user closes the browser or tab, the app should log them out automatically, clearing tokens/session both locally and on the backend.

I wanna make my Vanilla HTML, CSS, and JavaScript E-Commerce Website comes with Multi-Languages dropdown list

I wanna make a dropdown list with all languages and the selected language be translated automatically like using Google Translate API instead of make [data-en] or [data-ar] attributes to translate text contents manually.

This is an Example of the translation Way I do..

// Language Switcher
    const langButtons = document.querySelectorAll('.lang-btn');
    
    langButtons.forEach(button => {
        button.addEventListener('click', function() {
            const lang = this.getAttribute('data-lang');
            
            // Update active button
            langButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
            
            // Update language attributes
            document.body.setAttribute('data-lang', lang);
            document.body.setAttribute('dir', lang === 'ar' ? 'rtl' : 'ltr');
            
            // Update all text elements
            updateTextContent(lang);
        });
    });

    // Function to update text content based on language
    function updateTextContent(lang) {
        const elements = document.querySelectorAll('[data-en], [data-ar]');
        
        elements.forEach(element => {
            if (lang === 'en') {
                if (element.hasAttribute('data-en')) {
                    if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
                        element.setAttribute('placeholder', element.getAttribute('data-en'));
                    } else {
                        element.textContent = element.getAttribute('data-en');
                    }
                }
            } else if (lang === 'ar') {
                if (element.hasAttribute('data-ar')) {
                    if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
                        element.setAttribute('placeholder', element.getAttribute('data-ar'));
                    } else {
                        element.textContent = element.getAttribute('data-ar');
                    }
                }
            }
        });
    }
<header class="header">
        <div class="container">
            <div class="header-content">
                <div class="logo">
                    <h2 data-en="ABC Therapy" data-ar="ABC ثيرابي">ABC Therapy</h2>
                </div>
                <nav class="navigation">
                    <a href="#home" class="nav-link active" data-en="Home" data-ar="الرئيسية">Home</a>
                    <a href="#testimonials" class="nav-link" data-en="Testimonials" data-ar="آراء المرضى">Testimonials</a>
                    <a href="#services" class="nav-link" data-en="Services" data-ar="الخدمات">Services</a>
                    <a href="#about" class="nav-link" data-en="About" data-ar="من نحن">About</a>
                    <a href="#contact" class="nav-link" data-en="Contact" data-ar="تواصل معنا">Contact</a>
                </nav>
                <div class="header-actions">
                    <button class="appointment-btn" data-en="Book Appointment" data-ar="احجز موعد">Book Appointment</button>
                </div>
            </div>
        </div>
    </header>

HTML Document to tranlate only from English to Arabic or vice versa

download all pdfs with playwright not working

here is the code

  const browser = await chromium.launch();
  console.log('browser',browser);
  const context = await browser.newContext({
    acceptDownloads: true
  });
  const page = await context.newPage();
  await page.goto(pageUrl, { waitUntil: 'domcontentloaded' });

  // Get all PDF links (anchors ending with .pdf)
  const pdfLinks: string[] = await page.$$eval(
    "a[href$='.pdf']",
    anchors => anchors.map(a => (a as HTMLAnchorElement).href)
  );

  console.log(`Found ${pdfLinks.length} PDF(s).`);

  for (const rawLink of pdfLinks) {
    const pdfUrl = new URL(rawLink, pageUrl).toString();
    // Open link in a new tab to trigger download
    const [download] = await Promise.all([
      page.waitForEvent('download'),
      page.click(`a[href='${pdfUrl}']`).catch(async () => {
        const pdfPage = await context.newPage();
        await pdfPage.goto(pdfUrl);
        await pdfPage.close();
      })
    ]);
    const urlObj = new URL(pdfUrl);
    const filename = path.basename(urlObj.pathname);
    const filepath = path.join(downloadDir, filename);
    await (download as Download).saveAs(filepath);
    console.log(`Downloaded: ${filepath}`);
  }

  await browser.close();

Expected result is all the pdf will be downloaded but in reality browser only opens the first pdf but not downloading it, the rest of pdf pages are not opening and the browser just closed down.

any idea how to solve it?

Javascript default settings

I’m building an collection of functions and need to have this collection have default options, which the user can set on use.

(function (blackout, $, undefined) {
    blackout.text = "Please wait ...";
    blackout.timeout = 1000;
    blackout.img = "/Content/Images/loader.png";
    var defaultOptions = {
        text: "Please wait...",
        timeout: 1000,
        img: "/Content/Images/loader.png",
    };

    blackout.show = function ({text = blackout.defaultOptions.text, timeout = blackout.defaultOptions.timeout, img = blackout.defaultOptions.img}) {
        return this;
    }
    blackout.hide = function () {
        return this;
    }
}(Skd.blackout = Skd.blackout || {}, jQuery));

What I need is the option to call Skd.blackout.show() executing with default options or Skd.blackout.show({ text: "Hi Stack Overflow" }) showing the same, but with a differenct text.

How do I accomplise this?

I’ve tried a bunch of approaces and a hitting the dev-wall every time

Import issue in the react file

When I’m importing react to the index.js this shows me a invisible line and when I’m saving the code it’s getting Total invisible. When I’m running the html file the output is not showing. I’ve stored all the files in my single folder

I’ve installed npm, react, react-dom, I’ve also run the npm run start,

Restricting the Code with only one particular table

I have following JS code and working perfectly if it is on each and every html page (containing two of three Tables) of my project. But when i placed that code in JS external file and linked that file with html pages, it is triggering each and every table on a html page. I tried to restrict it with only MyTable3, but if I click in any table of the page, the code starts working. Is it possible to have the code in an external JS file and it should only work with a particular Table i.e. myTable3. Thanks.

var cells = document.getElementsByTagName('td');
for(var i = 0; i <= cells.length; i++){
    cells[i].addEventListener('click', clickHandler);
}

function clickHandler()
{
    document.getElementById("tulip").value = (this.textContent);
    document.getElementById("tulip").click(); 
}

Cannot read properties of undefined (reading ‘loadVideoById’)

Ive been doing an audio player that uses youtube links for my personal website (of which I used the code from Max Zheng How to play only the audio of a Youtube video using HTML 5?), and a few days ago I finally managed to make it work. But there is a problem: the function I made to change songs became way too long:

      function checkin(z){
        document.getElementById("x").innerHTML = z;
        if (z == 1) {
          document.getElementById("nome_musica").innerHTML = "Engenheiros do Hawaii - Infinita Highway (ao vivo)";
      //substitute the text above with the name of the song
          id_video = a;
          //YT.Player.load();
          // refresh();
      //substitute the variable with your song
        }else if (z == 2){
          document.getElementById("nome_musica").innerHTML = "They Might Be Giants - Istambul(not Constantinople)";
          id_video = d;
         //player.load();
          ytPlayer.loadVideoById(id_video);
          // refresh();
        }else if (z == 3){
          document.getElementById("nome_musica").innerHTML = "Kocchi no Kento - Hai Yorokonde";
          id_video = c;
          //player.load();
         ytPlayer.loadVideoById(id_video);
          // refresh();
        }else{
          document.getElementById("error").innerHTML = "error in the system";
        }
      }

I tried to make a For loop as well as two separate arrays (one for the links and another for the song titles) so it repeats comparing the song number n times, with n being the arrays length.

      const links = [a,d,c,f];
      const nomes = ["Engenheiros do Hawaii - Infinita Highway (ao vivo)","They Might Be Giants - Istambul(not Constantinople)","Kocchi no Kento - Hai Yorokonde","the pillows - THE LAST DINOSAUR"];

      var inicio = checkin(xe);

      function checkin(n){
        document.getElementById("x").innerHTML = n;
        for (let i = 1; i < links.length; i++) {
          if (n===i){
            let j = i - 1;
            id_video = links[j].toString();
            
            ytPlayer.loadVideoById(id_video);//"jLdAuGarfM0");
            document.getElementById("nome_musica").innerHTML = nomes[j].toString();
          }else{
            continue;
          }
        }
      }

But when I try this loop, the console says Cannot read properties of undefined (reading ‘loadVideoById’); although the loadVideoById worked perfectly fine in the other function. What the hell is the issue here? Is it just that it doesnt work inside for loops?
I can work it with the other function, but I would prefer if I could use the one with a For loop.

How Do I Use Proxies with Puppeteer and a Local Chrome Instance?

I’m using Puppeteer and JS to write a web scraper. The site I’m scraping is pretty intense, so I need to use a local chrome instance and a residential proxy service to get it working. Here’s my basic setup.

const chromeProcess = spawn(chromePath, [
    `--remote-debugging-port=${PORT}`,
    `--user-data-dir=${userDataDir}`,
    `--proxy-server=${proxyUrl}`,
    "--no-first-run",
    "--no-default-browser-check",
    "--disable-extensions",
    "--start-maximized",
    "--disable-features=IsolateOrigins,site-per-process"
  ], { stdio: "ignore" });

  let browser = await puppeteer.connect({ browserURL: `http://127.0.0.1:${PORT}` });
  let page = await browser.newPage();

I’ve been getting a multitude of errors trying to get the proxy service working, however, (like net::ERR_NO_SUPPORTED_PROXIES) where the page won’t load, or will show a “page not found” error in the browser. I’ve tried tunneling with mitmproxy with no luck, so I’m just not sure what’s possible at this point.

Does anyone have any insight into using proxies with a local chrome instance? Is this even possible?