Moving uploaded file error becasue of FakePath [closed]

Im trying to add user profile photo, but the problem is moving the uploaded file to the target directory because of the fakepath.

since the this is fakepath and temp location is (C:fakepathroundtableandchairs.jpg), moving the uploaded file will return error as well.

what i did is, i have change the line 106 and i also removed moving uploaded file section and the return is success.

I already did a research about the fakepath it is because of the browser security.

is there any way to get the temp path of the file in localhost (not live)? i just want to test it first in my computer (localhost). or to get this [name][tmp_name][size][type] using the code?

public function add(array $data)
{

    if ($errors = $this->registrator->validateUser($data, false)) {
    Response::validationError($errors);
    }

    $allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];

    $profilepic = (string)$data['profile_image'];

    // Handle secure profile image upload
    $targetDirectory = 'c:/Apache24/AdminLTE/dist/assets/img/usersprofile/';
    $imageFileType = strtolower(pathinfo($profilepic, PATHINFO_EXTENSION));

    // Generate a unique filename: complete_name_uniqueID.extension
    $safeName = preg_replace('/[^A-Za-z0-9]/', '_', $data['username']); // Remove special chars
    $uniqueID = uniqid();
    $imageName = "{$safeName}_{$uniqueID}.{$imageFileType}";
    $targetFile = $targetDirectory . $imageName;

    $profilepicsize = getimagesize($profilepic);
    // Validate image file size
    if ($profilepicsize > 5000000) {
        return "File size exceeds the 2MB limit.";
    }

    //Validate Mime Types
    if (!in_array($imageFileType, $allowedTypes)) {
                return ['success' => false, 'message' => 'Invalid file type. Only JPG, JPEG, PNG, GIF allowed.'];
            }

    // Prevent executable file uploads
    if (preg_match('/.(php|html|htm|js|exe|sh)$/i', $profilepic[0])) {
        return "Invalid file type.";
    }

    // Ensure upload directory exists
    if (!is_dir($targetDirectory)) {
        if (!mkdir($targetDirectory, 0755, true)) {
            return "Failed to create upload directory.";
        }
    }

    // Move the uploaded file
    if (!move_uploaded_file($profilepicpic, $targetFile)) {
        return "Error uploading the image.";
    }

    // Insert data into the database
    $this->db->insert('users', [
            'email' => $data['email'],
            'username' => $data['username'],
            'password' => $this->hashPassword($data['password']),
            'confirmed' => 'Y',
            'confirmation_key' => '',
            'register_date' => date('Y-m-d H:i:s'),
            'profile_image' => $imageName
        ]);

    $this->db->insert('user_details', [
        'user_id' => $this->db->lastInsertId(),
        'first_name' => $data['first_name'],
        'last_name' => $data['last_name'],
        'phone' => $data['phone'],
        'address' => $data['address']
    ]);

        Response::success(["message" => trans("user_added_successfully")]);
}

Warning: getimagesize(roundtableandchairs.jpg): Failed to open stream: No such file or directory in C:Apache24htdocsAdminLTEdistScriptUser.php on line 106

line 106 :

$profilepicsize = getimagesize($profilepic); 

Replacement of line 106

$profilepicsize = pathinfo($profilepic, PATHINFO_DIRNAME);

Is it possible to pass recaptcha v2 using php-webdriver? [closed]

I am trying to fill a web form to send SMS using php-webdriver on a site that uses recaptcha v2. My PHP script also start Selenium standalone server from bat files: selenium-server-hub.bat and selenium-server-node.bat.

selenium-server-hub.bat

chcp 65001
chdir C:inetpubwwwrootmedserviceswwwrootseleniumserver
"C:Program FilesJavajdk-24binjava.exe" -jar "selenium-server-4.35.0.jar" hub

selenium-server-node.bat

chcp 65001
chdir C:inetpubwwwrootmedserviceswwwrootseleniumserver
"C:Program FilesJavajdk-24binjava.exe" -Dwebdriver.edge.driver=msedgedriver.exe -jar "selenium-server-4.35.0.jar" node --config "NodeWebDriver.json"

NodeWebDriver.json

{
  "capabilities": [
    {
      "browserName": "MicrosoftEdge",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver",
      "platform": "WINDOWS"
    },
    {
      "browserName": "firefox",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver",
      "platform": "WINDOWS"
    },
    {
      "browserName": "chrome",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver",
      "platform": "WINDOWS"
    },
    {
      "browserName": "internet explorer",
      "maxInstances": 1,
      "seleniumProtocol": "WebDriver",
      "platform": "WINDOWS"
    }
  ],
  "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
  "maxSession": 5,
  "port": 5555,
  "register": true,
  "registerCycle": 5000,
  "hub": "http://Администратор:[email protected]:4444",
  "nodeStatusCheckTimeout": 5000,
  "nodePolling": 5000,
  "role": "node",
  "unregisterIfStillDownAfter": 60000,
  "downPollingLimit": 2,
  "debug": false,
  "servlets": [],
  "withoutServlets": [],
  "custom": {}
}

PHP script, which fills a web form and attempts to pass recaptcha

<?php
require_once "C:\Program Files\IIS Express\PHP\v8.3\lib\php-webdriver\vendor\autoload.php";

use FacebookWebDriverRemoteRemoteWebDriver;
use FacebookWebDriverRemoteDesiredCapabilities;
use FacebookWebDriverWebDriverBy;

function CheckIfSeleniumServerStarted(string $role) : bool
{
    $isStarted = false;
    $handle = curl_init();
    if($handle instanceof CurlHandle)
    {
        curl_setopt_array($handle,
        [
            CURLOPT_URL => $role === "node" ? "http://Администратор:7565@localhost:5555" : "http://Администратор:7565@localhost:4444",
            CURLOPT_HTTPHEADER => [ "Connection: keep-alive", "Accept: */*" ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 60,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_USERAGENT => $_SERVER["HTTP_USER_AGENT"],
            CURLOPT_SSL_VERIFYHOST => FALSE,
            CURLOPT_SSL_VERIFYPEER => FALSE
        ]);
        $result = curl_exec($handle);
        $isStarted = is_string($result) && ($statusCode = curl_getinfo($handle, CURLINFO_HTTP_CODE)) >= 200 && $statusCode < 300;
        curl_close($handle);
    }
    return $isStarted;
}

ini_set("display_errors", true);
header('Content-Type: text/html; charset=utf-8');
$log_filename = str_replace("php", "log", __FILE__);
$log_handle = fopen($log_filename, "w+");
if($log_handle !== false)
{
    set_error_handler(fn(int $errno, string $errstr, string $errfile = null, int $errline = 0) =>
        error_log("Error: {$errno} in {$errfile}, line no {$errline}n{$errstr}", 3, $log_filename), E_ALL);
}
// Start Selenium server
$cmdPath = "C:\Windows\system32\cmd.exe";
$workingDir = __DIR__ . "\selenium\server";
$shell = null;
if(!CheckIfSeleniumServerStarted("hub"))
{
    $command = "{$cmdPath} /C {$workingDir}\selenium-server-hub.bat 2>&1 &";
    $shell = new COM("WScript.Shell");
    $shell->Run($command, 1, false);
    sleep(1);
}
if(!CheckIfSeleniumServerStarted("node"))
{
    $command = "{$cmdPath} /C {$workingDir}\selenium-server-node.bat 2>&1 &";
    $shell = $shell ?? new COM("WScript.Shell");
    $shell->Run($command, 1, false);
    sleep(1);
}
$classRemoteWebDriver = "\Facebook\WebDriver\Remote\RemoteWebDriver";
$classRemoteWebElement = "\Facebook\WebDriver\Remote\RemoteWebElement";
$pageHtml = "";
$edgeOptions = ["args" => [ "--ignore-certificate-errors"]];
$capabilities = DesiredCapabilities::microsoftEdge();
$capabilities->setCapability("ms:edgeOptions", $edgeOptions);
$host = "http://localhost:4444";
$webDriver = RemoteWebDriver::create($host, $capabilities);
if($webDriver instanceof $classRemoteWebDriver)
{
    $webDriver->get("https://bomgovka.ru");
    $elemNumber = $webDriver->findElement(WebDriverBy::xpath("//input[@id='number']"));
    $elemMessage = $webDriver->findElement(WebDriverBy::xpath("//textarea[@id='message']"));
    if($elemNumber instanceof $classRemoteWebElement && $elemMessage instanceof $classRemoteWebElement)
    {
        $phoneNumber = "XXXXXXXXXXX";
        $elemNumber->sendKeys($phoneNumber);
        sleep(3);
        $elemMessage->sendKeys("Test message");
        sleep(3);
        $element = $webDriver->findElement(WebDriverBy::xpath("//iframe[starts-with(@name, 'a-') and starts-with(@src, 'https://www.google.com/recaptcha')]"));
        error_log("Recaptcha iframe is " . ($element instanceof $classRemoteWebElement ? "found" : "not found"), 3, $log_filename);
        if($element instanceof $classRemoteWebElement)
        {
            $webDriver = $webDriver->switchTo()->frame($element);
            error_log("Switch to recaptcha iframe is " . (!($webDriver instanceof $classRemoteWebDriver) ? "not " : "") . "completed.", 3, $log_filename);
            if($webDriver instanceof $classRemoteWebDriver)
            {
                $element = $webDriver->wait(25)->until(FacebookWebDriverWebDriverExpectedCondition::elementToBeClickable(WebDriverBy::xpath("//div[@class = 'recaptcha-checkbox-border']")));
                error_log("Recaptcha checkbox is " . ($element instanceof $classRemoteWebElement ? "found and clickable" : "not found or not clickable"), 3, $log_filename);
                if($element instanceof $classRemoteWebElement)
                {
                    $element->click();
                    $pageHtml = $webDriver->getPageSource();
                    $webDriver = $webDriver->switchTo()->defaultContent();
                    error_log("Switch to default content is " . (!($webDriver instanceof $classRemoteWebDriver) ? "not " : "") . "completed.", 3, $log_filename);
                    if($webDriver instanceof $classRemoteWebDriver)
                    {
                        $elemButton = $webDriver->wait(25)->until(FacebookWebDriverWebDriverExpectedCondition::elementToBeClickable(WebDriverBy::xpath("//input[@name='contact-submit']")));
                        error_log("Submit button is " . ($elemButton instanceof $classRemoteWebElement ? "found and clickable." : "not found or not clickable."), 3, $log_filename);
                        if($elemButton instanceof $classRemoteWebElement)
                        {
                            $elemButton->click();
                            sleep(3);
                            $pageHtml = $webDriver->getPageSource();
                        }
                    }
                }
            }
        }
    }
    $webDriver->quit();
}
echo $pageHtml;
if(is_resource($log_handle))
{
    fclose($log_handle);
}
?>

But as a result of the script executing, recaptcha is not passed and site returns “Error. Please pass the ‘I’m not a robot’ check”.
How to pass recaptcha using php-webdriver correctly or it’s impossible using only php-webdriver?

Woocommerce Product Variant

I am not getting solution,in wocommerce site i have addred product like HOODIES which has two sizes Youth|Adult Youth Size has two color option White|Grey and Adult has White|Grey|Red I want is as user select Youth Sizefrom drop down only White| Grey appears and when select Adult all White|Grey|Red appear. I don’t want to use any plugin. Can it be possible ?

Why does this behave differently inside a JavaScript arrow function compared to a normal function? [duplicate]

I am learning JavaScript and came across a difference in how this works in arrow functions vs regular functions.

const obj = {

name: “Tharun”,

regularFunc: function () {

console.log("Regular:", this.name);

},

arrowFunc: () => {

console.log("Arrow:", this.name);

}

};

obj.regularFunc(); // Output: “Regular: Tharun”

obj.arrowFunc(); // Output: “Arrow: undefined”

In the above code:

regularFunc prints the object’s name as expected.

arrowFunc gives undefined.

I read that arrow functions don’t have their own this, but I am confused about where the this is coming from in each case.

Can someone explain in detail why arrow functions behave differently with this compared to normal functions and when I should use one over the other?

I tried using both a regular function and an arrow function inside an object method to print the name property. With the regular function, I expected this to point to the object, and it worked correctly (Regular: Tharun). But with the arrow function, I also expected it to point to the object, however it returned undefined. I want to understand why this behaves differently here and what is the correct use case for each.

Why can my div console.log all it’s children at once but if i want them separated only the first one exists [duplicate]

currentArrayDOM is a div with 3 elements inside it; an h1, button and a div.

When I console.log(currentArrayDOM.children) they all show up collapsed in an HTMLCollection but if i try console.log(currentArrayDOM.children[1]) its undefined although console.log(currentArrayDOM.children[0]) gives me the h1. Its just the other 2 elements that disappear.

console.log(currentArrayDOM);
for (const childrenElement of currentArrayDOM.children) {
     console.log(childrenElement);
}
console.log(currentArrayDOM.children);
console.log(currentArrayDOM.children[1]);

devTools output

I was expecting to be able to use all the elements separately but it seems like that’s not allowed.

Why is arr undefined even though function returns an array? [duplicate]

const randomGIFFunc = async function(dirname) {
      const dirPath = 'src/gifs/' + dirname;
      fs.readdir(dirPath, (err, files) => {
        if (err) {
            console.log('Error reading directory: ', err );
            return;
          }
        
        const randomIndex = Math.floor(Math.random() * files.length);
        const randomGIFname = files[randomIndex];
        const randomGIFpath = dirPath + '/' + randomGIFname;

        console.log('arr in function: ' + [randomGIFpath, randomGIFname]);
        return [randomGIFpath, randomGIFname];
      })
    }

later in async code

switch (act) {
      case 'hug':
        const arr = await randomGIFFunc('hug');
        console.log("arr: " + arr); //undefined
        const randomGIFpath = await arr[0]; const randomGIFname = await arr[1];
        break;

terminal:

arr: undefined
There was an error running this command: TypeError: Cannot read properties of undefined (reading '0')
arr in function: src/gifs/hug/01.gif,01.gif

Everything I tried is already in code I gave

I can only guess that for some reason function actually happens later (judging be terminal logs) but I have no idea why code isn’t waiting for it to finish

Mongodb $push $each onto array is resetting createdAt date for all subdocuments

Hopefully this makes sense. Using mongoose to push new items into an array of subdocuments, the documents get added fine, however on certain (random) occasions, the createdAt date of the current subdocuments in the array all get changed to the most recently added timestamp. This just started happening recently and I cannot recreate the issue locally, however on production my clients (many users) are experiencing this.

My model is as follows, root shipment schema contains an subdocument array of documents (shipment documents) which are files that a user uploads to the shipment.

const DocumentFileSchema = new Schema({
    user: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            required: true
        },
        firstName: {
            type: String,
            required: true
        },
        lastName: {
            type: String,
            required: true
        }
    },
    file: {
        type: String,
        required: true
    },
    name: {
        type: String,
        required: true
    }
}, {
    timestamps: true
});

const ShipmentSchema = new Schema({
    ...
    documents: [DocumentFileSchema]
}, {
    timestamps: true,
    collection: 'shipments',
    toJSON: { virtuals: true }
})

I’m adding files using the following function (upload handled elsewhere).
I recently added the createdAt date into this function to force a value instead of letting mongo handle the timestamp, and this has not solved the issue.

const addFiles = async (id, body, files) => {
    let user = JSON.parse(body.user);

    let docs = [];
    if (files) {
        files.forEach(v => docs.push({ user: { ...user }, name: v.key.replace('shipments/',''), file: withHttp(v.location), createdAt: new Date() }));
        return ShipmentModel.findByIdAndUpdate(
            { _id: id },
            { $push: { documents: { $each: docs } } },
            { new: true }
        );

    }
}

The record in mongo (locally) works flawless but as mentioned on production (which is the same mongo database), users are uploading documents at different times and the database ends up with all subdocument timestamps reset to the newest time.

What is does locally (correct, proper timestamps):

{
  "_id": {
    "$oid": "xxx"
  },
  ...
  "documents": [
    {
      "_id": {
        "$oid": "xxx"
      },
      "user": {
        "id": {
          "$oid": "xxx"
        },
        "firstName": "John",
        "lastName": "Doe"
      },
      "name": "VERSION 2-A.pdf",
      "file": "xxx.pdf",
      "updatedAt": {
        "$date": "2025-08-20T16:13:21.609Z"
      },
      "createdAt": {
        "$date": "2025-08-20T16:13:21.609Z"
      }
    },
    {
      "_id": {
        "$oid": "xxx"
      },
      "user": {
        "id": {
          "$oid": "xxx"
        },
        "firstName": "Jane",
        "lastName": "Doe"
      },
      "name": "PDF_Caregiver Connections-2.pdf",
      "file": "xxx.pdf",
      "updatedAt": {
        "$date": "2025-08-20T16:54:59.307Z"
      },
      "createdAt": {
        "$date": "2025-08-20T16:54:59.307Z"
      }
    }
  ],
  "createdAt": {
    "$date": "2024-07-23T18:05:50.052Z"
  },
  "updatedAt": {
    "$date": "2025-08-20T17:28:39.538Z"
  },
  "__v": 0
}

When another user adds a new document at a completely separate time this is what happens on production (but only happens randomly, not for every shipment), it resets createdAt date to most recent subdocument timestamp:

{
  "_id": {
    "$oid": "xxx"
  },
  ...
  "documents": [
    {
      "_id": {
        "$oid": "xxx"
      },
      "user": {
        "id": {
          "$oid": "xxx"
        },
        "firstName": "JOE",
        "lastName": "RANTSEVIC"
      },
      "name": "937379JR RC.pdf",
      "file": "xxx.pdf",
      "createdAt": {
        "$date": "2025-08-25T11:51:49.375Z"
      },
      "updatedAt": {
        "$date": "2025-08-25T11:51:49.375Z"
      }
    },
    {
      "_id": {
        "$oid": "xxx"
      },
      "user": {
        "id": {
          "$oid": "xxx"
        },
        "firstName": "ALAN",
        "lastName": "SALAZR"
      },
      "name": "RP-937379JR-Carrier-Contract.pdf",
      "file": "xxx.pdf",
      "createdAt": {
        "$date": "2025-08-25T11:51:49.375Z"
      },
      "updatedAt": {
        "$date": "2025-08-25T11:51:49.375Z"
      }
    }
  ],
  "createdAt": {
    "$date": "2025-08-25T11:15:00.627Z"
  },
  "updatedAt": {
    "$date": "2025-08-25T15:09:36.155Z"
  },
  "__v": 0
}

Please help!

Smugmug API Setting Thunbnails for albums/Removing Blurry Thunbnails

Hello I am currently coding to photo gallery website and Im using the Smumug API to get all my pulbic albums+photos in the album to show up on the gallery and the issue is that for the gallery to show the albums Im getting the placeholder.jpg as the thunbnails and the second issue is when going into the albums the photo thunbnails are extremely blurry and ive been trying everything to get rid of the blurry from the thunbnails but when I click on the img to do the viewmodel box the img perfectly fine looking.

(I am fairly new to coding Javascript and using API’s most of the javascript involving the API is helped from using AI’s and if someone could help me fix this and also give me some references online to where to find more exmaples of JS being used for API calling and how if im having issues where I can go to find the solution instead of using AI)
JavaScript Code:

`async loadAlbums() {
    try {
        this.isLoading = true;
        this.updateLoadingState();

        const response = await 
  axios.get('https://api.smugmug.com/api/v2/user/jdstudiophotography!albums', {
            params: {
                APIKey: this.API_KEY,
                count: 100,
                _expand: 'HighlightImage,HighlightImage.ImageSizes'
            },
            headers: {
                'Accept': 'application/json',
                'X-Smug-Version': 'v2'
            }
        });

        if (!response.data.Response || !response.data.Response.Album) {
            throw new Error('Invalid albums response');
        }

        this.albums = response.data.Response.Album.map(album => {
            let coverImage = './images/albums/placeholder.jpg';
            // In loadAlbums method, update the coverImage selection in the map 
  function:
            coverImage = '';
            if (album.HighlightImage && album.HighlightImage.ImageSizes) {
                const imageSizes = album.HighlightImage.ImageSizes;
                coverImage = imageSizes.LargeImageUrl ||
                            imageSizes.MediumImageUrl ||
                            imageSizes.SmallImageUrl ||
                            album.HighlightImage.ThumbnailUrl;
            }

            return {
                id: album.AlbumKey,
                title: album.Title || 'Untitled Album',
                imageCount: album.ImageCount || 0,
                coverImage
            };
        });

        this.isLoading = false;
        this.renderAlbums();
    } catch (error) {
        console.error('Error loading albums:', error);
        this.isLoading = false;
        this.updateLoadingState('Error loading albums.');
    }
 }`




`async loadAlbumImages(albumId) {
    try {
        this.isLoading = true;
        this.updateLoadingState();
        const response = await    
      axios.get(`https://api.smugmug.com/api/v2/album/${albumId}!images`, {
            params: {
                APIKey: this.API_KEY,
                count: 100,
                _expand: 'ImageSizes'
            },
            headers: {
                'Accept': 'application/json',
                'X-Smug-Version': 'v2',
                'X-Smug-ResponseType': 'JSON'
            }
        });

        if (!response.data.Response || !response.data.Response.AlbumImage) {
            throw new Error('Invalid album images response structure');
        }

        const images = response.data.Response.AlbumImage.map(image => {
            const imageSizes = image.ImageSizes || {};
            return {
                id: image.ImageKey,
                title: image.Title || image.FileName,

                thumbnail: imageSizes.MediumImageUrl || 
                          imageSizes.SmallImageUrl || 
                          image.ThumbnailUrl,
                // Keeps medium URL for grid view
                mediumUrl: imageSizes.MediumImageUrl || 
                          imageSizes.SmallImageUrl || 
                          image.ThumbnailUrl,
                // Keeps original for maximum quality when needed
                originalUrl: image.OriginalUrl || image.ArchivedUri
            };
        });

        this.currentImages = images;
        this.isLoading = false;
        this.renderImages();

    } catch (error) {
        console.error('Error loading album images:', error);
        this.isLoading = false;
        this.updateLoadingState('Error loading album images. Please try again 
       later.');
     }
  }`

`renderImages() {
const container = document.querySelector(‘.grid-albums’);
container.innerHTML = ”;

const placeholder = './images/albums/placeholder.jpg';

this.currentImages.forEach((image, index) => {
    const imageElement = document.createElement('div');
    imageElement.className = 'image-card';
    imageElement.innerHTML = `
        <div class="image-thumbnail">
            <img src="${image.thumbnail || placeholder}" alt="${image.title}"
                 loading="lazy"
                 onerror="this.onerror=null; this.src='${placeholder}';">
            <div class="image-info">
                <h3>${image.title}</h3>
            </div>
        </div>
    `;

    imageElement.addEventListener('click', () => {
        this.showLightbox(image, index);
    });

    container.appendChild(imageElement);
});

}`

`renderAlbums() {
const container = document.querySelector(‘.grid-albums’);
container.innerHTML = ”; // Clear the container

const placeholder = './images/albums/placeholder.jpg';

this.albums.forEach(album => {
    const albumElement = document.createElement('div');
    albumElement.className = 'album-card';
    albumElement.innerHTML = `
        <div class="album-thumbnail">
            <img src="${album.coverImage || placeholder}" alt="${album.title}"
                 loading="lazy"
                 onerror="this.onerror=null; this.src='${placeholder}';">
            <div class="album-info">
                <h3>${album.title}</h3>
                <p>${album.imageCount} photos</p>
            </div>
        </div>
    `;

    albumElement.addEventListener('click', () => {
        window.location.href = `gallery.html?albumId=${album.id}`;
    });

    container.appendChild(albumElement);
});

}`

Img Blurry
Gallery Album Thumbnail

I attemped to have the code where it gets all the sizes for the albums thunbnail and if Smugmug has any highligh imgs saved to also reterive that information and go from the biggest size to smallest and if all of those fail that it will as the final use the placeholder.jpg but im still getting that placeholder.jpg and the same was from the actual imgs in the album but the imgs thumbnail are still blurry

Selector excluding nested values

Basically, I want to create a selector, that would exclude nested elements – it should find only elements at the first level of nesting. I have this:

it('Test selector non-nested', () => {
  const mainAttribute = 'data-main';
  const itemAttribute = 'data-item';
  const sideAttribute = 'data-side';
  document.body.innerHTML = `
<div>
    <div ${mainAttribute}>
        <div ${itemAttribute}>
            <div ${sideAttribute}>
                <div ${mainAttribute}>
                    <div ${itemAttribute}>
                        <div ${sideAttribute}></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
`;

  const result = [];
  const foundElements = document.querySelectorAll(`[${mainAttribute}]`);
  for (const element of foundElements) {
    result.push(element);
  }

  for (const element of result) {
    const selector = `:scope [${sideAttribute}]:not(:scope [${itemAttribute}] [${itemAttribute}] [${sideAttribute}])`;
    element.innerHTML = element.innerHTML; // It makes it work!
    const results = element.querySelectorAll(selector);
    expect(results.length).toEqual(1);
  }
});

As you can see, I want to find elements having “sideAttribute”, but only in the top element having the “itemAttribute”. It means that in this case I want to have 1 result for both iterations of the loop.

It doesn’t work UNLESS I will throw element.innerHTML = element.innerHTML; in there, then it magically starts working. What’s going on here?

lz4 encoding and binary decoding

why does this decoding of firefox recovery fail?

const profilesPath = path.join(os.homedir(), 'AppData', 'Roaming', 'Mozilla', 'Firefox', 'Profiles');
const defaultProfile = fs.readdirSync(profilesPath).find(profile => profile.includes('.Default'));
const recoveryFile = path.join(profilesPath, defaultProfile, 'sessionstore-backups', 'recovery.jsonlz4');

const rawData = fs.readFileSync(recoveryFile);
const uncompressedSize = rawData.readUInt32LE(8);
const lz4Data = rawData.subarray(12);
const decompressed = Buffer.alloc(uncompressedSize);
lz4.decodeBlock(lz4Data, decompressed);

const jdata = JSON.parse(decompressed.toString('utf8'));
const selectedTab = jdata.windows[0].tabs[jdata.windows[0].selected - 1];
const currentUrl = selectedTab.entries[selectedTab.entries.length - 1].url;

res.json({ activeTabUrl: currentUrl });

same with the binary decoding of google chrome data

const chromeSessionsPath = path.join(os.homedir(), 'AppData', 'Local', 'Google', 'Chrome', 'User Data', 'Default', 'Sessions');

if (!fs.existsSync(chromeSessionsPath)) {
  return res.status(404).json({
    error: 'Chrome Sessions directory not found'
  });
}

const sessionFiles = fs.readdirSync(chromeSessionsPath);
const tabsFiles = sessionFiles.filter(file => file.startsWith('Tabs_'))
  .map(file => ({
    name: file,
    path: path.join(chromeSessionsPath, file),
    mtime: fs.statSync(path.join(chromeSessionsPath, file)).mtime
  }))
  .sort((a, b) => b.mtime - a.mtime);

if (tabsFiles.length === 0) {
  return res.status(404).json({
    error: 'No Chrome tabs files found'
  });
}

const sessionData = fs.readFileSync(tabsFiles[0].path);

const dataString = sessionData.toString('utf8', 0, Math.min(sessionData.length, 10000));
const urlMatches = dataString.match(/https?://[^sx00-x1fx7f-x9f"<>{}|\^`[]]+/g);

if (urlMatches && urlMatches.length > 0) {
  const currentUrl = urlMatches[urlMatches.length - 1];
  res.json({
    activeTabUrl: currentUrl
  });
} else {
  res.status(404).json({
    error: 'No URLs found in Chrome session'
  });
}

i wanted to make a combined active URL and history viewer for all my browsers but recovering the data from these files is cumbersome.

how to place the co-ordinates of View to the absolute View in react native

I’m trying to create shared-element transition. Using ref i’m accessing the View location (height, width, pageX, pageY) from measure method and i have another View with absolute position where i’m passing this data so that transition start from that place

but instead after adding the pageX and pageY to respective left and top – the absolute view is not on the exact location

import { Image } from "expo-image";
import React, { useRef } from "react";
import { Button, StyleSheet, Text, View } from "react-native";
import Animated, {
    useAnimatedStyle,
    useSharedValue,
} from "react-native-reanimated";

const AnimatedExpoImage = Animated.createAnimatedComponent(Image);

const Example = () => {
    const imageViewRef = useRef<View>(null);
    const rootViewRef = useRef<View>(null);

    const position = useSharedValue({ x: 0, y: 0 });
    const size = useSharedValue({ width: 0, height: 0 });

    const activeImagePositionStyle = useAnimatedStyle(() => {
        return {
            top: position.value.y,
            left: position.value.x,
        };
    });

    const activeImageSizeStyle = useAnimatedStyle(() => {
        return {
            height: size.value.height,
            width: size.value.width,
        };
    });

    return (
        <View ref={rootViewRef} style={{ flex: 1, backgroundColor: "white" }}>
            <View>
                <View
                    style={{
                        justifyContent: "center",
                        alignItems: "center",
                        height: 50,
                    }}
                >
                    <Text>Paul Jarvis</Text>
                </View>
                <View
                    ref={imageViewRef}
                    style={{
                        height: 200,
                        width: "85%",
                        alignSelf: "center",
                    }}
                >
                    <Image
                        contentFit="cover"
                        style={{ height: "100%", width: "100%" }}
                        source={{
                            uri: "https://picsum.photos/id/16/2500/1667",
                        }}
                    />
                </View>
                <Button
                    title="Get Details"
                    onPress={() => {
                        imageViewRef.current?.measure(
                            (x, y, width, height, pageX, pageY) => {
                                position.value = { x: pageX, y: pageY };
                                size.value = { width, height };
                            }
                        );
                    }}
                />
            </View>

            <View style={[StyleSheet.absoluteFill]}>
                <View style={{ flex: 1 }}>
                    <AnimatedExpoImage
                        contentFit="cover"
                        style={[
                            styles.image,
                            activeImagePositionStyle,
                            activeImageSizeStyle,
                        ]}
                        source={{
                            uri: "https://picsum.photos/id/17/2500/1667",
                        }}
                    />
                </View>
            </View>
        </View>
    );
};

export default Example;

const styles = StyleSheet.create({
    image: {
        width: null,
        height: null,
        position: "absolute",
        top: 0,
        left: 0,
    },
});

GIF error example

Group an array of objects with a tolerance factor

I have an array of objects with a name and a value that looks like this (sorted by values):

var array = [ 
    { Name: "F", Value: 320 },
    { Name: "E", Value: 321 },
    { Name: "C", Value: 340 },
    { Name: "G", Value: 340 },
    { Name: "A", Value: 400 },
    { Name: "D", Value: 403 },
    { Name: "B", Value: 404 }
]

I want to combine objects with the same value plus a tolerance. Grouping can be done like this:

var groupedArray = Object.groupBy(array, e => e.Value ); // Is it possible to add a tolerance factor here?

This creates groups that have exactly the same values. But what I actually want is a grouping with a certain tolerance. So, if values ​​are just slightly larger than the previous value, they should still be included in the group. The result could then look like this:

{
  320: [{
    Name: "F",
    Value: 320
  }, {
    Name: "E",
    Value: 321
  }],
  340: [{
    Name: "C",
    Value: 340
  }, {
    Name: "G",
    Value: 340
  }],
  400: [{
    Name: "A",
    Value: 400
  }, {
    Name: "D",
    Value: 403
  }, {
    Name: "B",
    Value: 404
  }]
}

… so all values ​​with a tolerance of, for example, +5 are in one group. Is it possible to add such a tolerance factor?

React Virtualized MultiGrid: Box shadow on first fixed column appears on left instead of right

I’m using React Virtualized MultiGrid and trying to add a box shadow to the first fixed column. I am able to apply the box shadow, but it always appears on the left side, whereas I need it on the right side (opposite).

I’ve tried multiple approaches in CSS, but nothing seems to work. I’ve attached a CodeSandbox link with the full code, including the CSS in style.css.

Can someone please help me fix this so the shadow appears on the right side of the first column?

image

WebView2 in wpf application makes crash the app

I am using the Microsoft.Web.WebView2component in my WPF c# application.
Nuget version is 1.0.3405.78.
It is a great solution to manipulate html content in a WPF application.
Except an error that I can not handle. I must miss something.

I am generating some dynamic Htmls and openning them in the WebView2. If the page contains a Fileupload, when I upload some files and show it in the page, randomly, the whole application crashes without any error message.

Here is my C# code and Html sample :

C# part :

  await wv2.EnsureCoreWebView2Async();

  //Loads javascript content.
  wv2.CoreWebView2.DOMContentLoaded += async (sender, e) =>
  {
     if (javascriptGenerated == false)
     {
       // Inject the JavaScript code
       await    wv2.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(GenerateJSPart());
       javascriptGenerated = true;
     }
  };
  

    var htmlPath = GenerateHtml();
    wv2.Source = new Uri(htmlPath, UriKind.Absolute);


    wv2.CoreWebView2.PermissionRequested += (sender, e) =>
    {
       if (e.PermissionKind == CoreWebView2PermissionKind.FileReadWrite || e.PermissionKind == CoreWebView2PermissionKind.UnknownPermission)
         {
           e.State = CoreWebView2PermissionState.Allow;
          }
    };




    private string GenerateJSPart()
    {
     //Script to add file uploads.
     string js = "document.addEventListener('DOMContentLoaded', function() {   " +

       "const fileInputs = document.querySelectorAll('input[type="file"]');      " +
       " fileInputs.forEach(input => {       " +
       " input.addEventListener('change', function(e) {           " +
       " handleFileUpload(e.target);       " +
       " });   " +
       " });" +
       "});" +
       "" +
       "function handleFileUpload(fileInput) {  " +
       "  const file = fileInput.files[0];       " +
       " if (!file) {       " +
       " return;  " +
       "  }        " +
       "" +

       "if (!file.type.startsWith('image/')) {       " +
       " alert('Please select an image file.');       " +
       " fileInput.value = ''; " +

       "    return;   " +
       " }        " +
       "" +

       "const parentDiv = fileInput.closest('div');      " +
       "  if (!parentDiv) {        " +
       "console.error('Parent div not found');        return;    " +
       "}        " +
       "" +
       "const reader = new FileReader();        " +
       "reader.onload = function(e) {       " +
       " const existingImg = parentDiv.querySelector('img');        " +
       "if (existingImg) {            existingImg.remove();        " +
       "}" +
       "const img = document.createElement('img');      " +
       "img.src = e.target.result;        " +
       "img.style.maxWidth = '100%';        " +
       "img.style.height = 'auto';       " +
       " img.style.display = 'block';     " +
       "img.style.margin = '10px 0';       " +
       " img.style.border = '1px solid #ddd';        " +
       "img.style.borderRadius = '4px';              " +

       "  fileInput.parentNode.insertBefore(img, fileInput.nextSibling);              " +
       " fileInput.style.display = 'none';       " +
       " const label = parentDiv.querySelector('label');       " +
       " if (label) {            " +
       "label.style.display = 'none';        " +
       "}              " +
       "  addRemoveButton(parentDiv, fileInput, label, img); " +
       "   };       " +
       " reader.onerror = function() {       " +
       " alert('Error reading file. Please try again.');      " +
       "  fileInput.value = '';    " +
       "};        " +
       "reader.readAsDataURL(file);" +
       "}" +
       "function addRemoveButton(parentDiv, fileInput, label, img) {    " +
       "const removeBtn = document.createElement('button');   " +
       " removeBtn.textContent = "" + "Remove Image" + "";    " +
       "removeBtn.type = 'button';    " +
       "removeBtn.style.cssText = 'background-color: #dc3545;       " +
       " color: white;       " +
       " border: none;       " +
       " padding: 5px 10px;        " +
       "border-radius: 4px;        " +
       "cursor: pointer;        " +
       "margin-top: 5px;       " +
       " font-size: 12px;';       " +
       " removeBtn.onclick = function() {        " +
       "img.remove();       " +
       " removeBtn.remove();                " +
       "fileInput.style.display = 'none'; " +
       "if (label) {           " +
       " label.style.display = 'inline-block';       " +
       " }               " +
       "  fileInput.value = '';   " +
       " };       " +
       " img.parentNode.insertBefore(removeBtn, img.nextSibling);" +
       "}";

   return js ;
 }

Html part :

document.addEventListener('DOMContentLoaded', function() {   const fileInputs = document.querySelectorAll('input[type="file"]');       fileInputs.forEach(input => {        input.addEventListener('change', function(e) {            handleFileUpload(e.target);        });    });});function handleFileUpload(fileInput) {    const file = fileInput.files[0];        if (!file) {        return;    }        if (!file.type.startsWith('image/')) {        alert('Please select an image file.');        fileInput.value = '';     return;    }        const parentDiv = fileInput.closest('div');        if (!parentDiv) {        console.error('Parent div not found');        return;    }        const reader = new FileReader();        reader.onload = function(e) {        const existingImg = parentDiv.querySelector('img');        if (existingImg) {            existingImg.remove();        }const img = document.createElement('img');      img.src = e.target.result;        img.style.maxWidth = '100%';        img.style.height = 'auto';        img.style.display = 'block';     img.style.margin = '10px 0';        img.style.border = '1px solid #ddd';        img.style.borderRadius = '4px';                fileInput.parentNode.insertBefore(img, fileInput.nextSibling);               fileInput.style.display = 'none';        const label = parentDiv.querySelector('label');        if (label) {            label.style.display = 'none';        }                addRemoveButton(parentDiv, fileInput, label, img);    };        reader.onerror = function() {        alert('Error reading file. Please try again.');        fileInput.value = '';    };        reader.readAsDataURL(file);}function addRemoveButton(parentDiv, fileInput, label, img) {    const removeBtn = document.createElement('button');    removeBtn.textContent = "Remove image";    removeBtn.type = 'button';    removeBtn.style.cssText = 'background-color: #dc3545;        color: white;        border: none;        padding: 5px 10px;        border-radius: 4px;        cursor: pointer;        margin-top: 5px;        font-size: 12px;';        removeBtn.onclick = function() {        img.remove();        removeBtn.remove();                fileInput.style.display = 'none'; if (label) {            label.style.display = 'inline-block';        }                 fileInput.value = '';    };        img.parentNode.insertBefore(removeBtn, img.nextSibling);}
<html xmlns="http://www.w3.org/1999/xhtml"><head><style> .tcenter {text-align: center;margin-bottom: 10px;}span {cursor: pointer;}.custom-file-upload {border:1px solid dodgerblue;border-radius: 8px;padding:10px;padding-top:3px;padding-bottom:3px;cursor:pointer;font-size:12px;}.editing-textarea {font-family: inherit;font-size: inherit;font-weight: inherit; font-style: inherit;color: inherit;background-color: rgb(250, 250, 250);border: 1px solid dodgerblue;padding: 2px;margin: 0;resize: vertical;min-height: 20px;width: auto;min-width: 100px;display: inline-block;vertical-align: middle;}span.editable-span {cursor: pointer;transition: background-color 0.3s;}span.editable-span:hover {background -color: #f0f0f0;border -radius: 3px;}span:hover {background -color: #f0f0f0;border -radius: 3px;}.footer-div {margin-top:100px;}@media print {button {display: none !important;}.image-container {position: relative;display: inline-block; }.remove-btn:hover {background-color: #c82333 !important;}.uploaded-image {max-width: 100%; height: auto; display: block; margin: 10px 0; border: 1px solid #ddd;border -radius: 4px; box -shadow: 0 2px 4px rgba(0,0,0,0.1); }.custom-file-upload {display: none;}.footer-div {bottom:0;page-break-after: always; } .pagebreak{page-break-before: always;border:0 !important;}.content-block, p { page-break-inside: avoid; } body {}}textarea {resize:none;overflow:hidden;height:auto;min-height:50px;field-sizing:content;}textarea:focus {outline: none !important; border:1px dashed dodgerblue;box-shadow: 0 0 10px #719ECE;}.pagebreak{height:30px;margin-bottom:45px;}.pathologie-images{margin-bottom:-4px;}@media print {textarea {background-color: transparent !important;resize:none;}}</style><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>CADELIO</title><style type="text/css">
p { margin-top: 0px;margin-bottom: 12px;line-height: 1.15; } 
body { font-family: 'Verdana';font-style: Normal;font-weight: normal;font-size: 16px; } 
.Normal { telerik-style-type: paragraph;telerik-style-name: Normal;border-collapse: collapse; } 
.TableNormal { telerik-style-type: table;telerik-style-name: TableNormal;border-collapse: collapse; } </style></head><body><p class="Normal "><span class="editable-span">&nbsp;</span></p><p class="Normal "> </p><div class="tcenter" id="upload-div-1"><label for="fileUpload1" class="custom-file-upload">Select an image</label><input type="file" accept="image/*" class="fu-label" style="display:none;" name="fileUpload1" id="fileUpload1"></div><p></p></body></html>

Any idea?