Flatpickr selection getting Cleared on postbacks

I am using flatpickr datetime control in asp.net web form project. That control is within asp:UpdatePanel and i think because of that whenever i select any value of my dropdown my flatpickr datetime’s selection gets cleared.

I want that selection to remain even after selecting values from dropdown
Any suggestions?

Firebase auth | web | phone number login | Firebase Internal error

I am trying to integrate firebase auth in a simple page to comply with play store requirements to be able to delete your account through the web.

My accounts are tied to phone numbers so I just need the user to login with their phone number and delete their account.

I have been trying to do it, but I keep getting a Firebase Internal Error, based on the stacktrace the recaptcha fails, but I can’t figure out what to do. The documentation only contains snippets, but not a full example so I’m not really sure. I would appreciate if somebody can point me to a solution.

Here is my current code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Delete your account</title>
</head>

<body>
    <h1>Welcome to the Firebase Auth Demo</h1>

    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin: 20px;
        }

        h1 {
            color: #333;
        }

        button {
            padding: 10px;
            margin: 5px;
            font-size: 16px;
        }

        form {
            display: flex;
            flex-direction: column;
            max-width: 300px;
            margin: 0 auto;
        }

        input {
            margin-bottom: 10px;
            padding: 5px;
            font-size: 14px;
        }
    </style>

    <div id="login-container">
        <form id="phone-form">
            <label for="phone">Enter your phone number:</label>
            <input type="tel" id="phone" required>
            <button type="submit" id="sign-in-button">Login with
                Phone Number</button>
        </form>
    </div>

    <div id="delete-account-container" style="display:none;">
        <button onclick="deleteAccount()">Delete Account and Data</button>
    </div>

    <script type="module">

        import { initializeApp } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js";
        import { getAuth, signInWithPhoneNumber, RecaptchaVerifier } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-auth.js"

        const firebaseConfig = {
            apiKey: "*********",
            authDomain: "*********",
            projectId: "*********",
            storageBucket: "*********",
            messagingSenderId: "*********",
            appId: "*********"
        };

        const app = initializeApp(firebaseConfig);
        const auth = getAuth(app);

        document.getElementById("phone-form").addEventListener("submit", function (event) {
            event.preventDefault();
            loginWithPhone();
        });

        window.recaptchaVerifier = new RecaptchaVerifier(auth, "sign-in-button", {
            'size': 'invisible',
            'callback': (response) => {
                console.log('I got called!');
                alert('I got called!');
                // reCAPTCHA solved, allow signInWithPhoneNumber.
                // loginWithPhone();
            }
        });

        const appVerifier = window.recaptchaVerifier;

        console.log('RecaptchaVerifier created:', appVerifier);

        window.loginWithPhone = function () {
            const phoneNumber = document.getElementById("phone").value;

            console.log(phoneNumber)


            signInWithPhoneNumber(auth, phoneNumber, appVerifier)
                .then((confirmationResult) => {
                    let code = prompt("Enter the verification code sent to your phone:");
                    return confirmationResult.confirm(code);
                })
                .then((result) => {
                    console.log("Successfully logged in:", result.user);
                    showDeleteButton();
                })
                .catch((error) => {
                    console.error("Login failed:", error);
                });
        }

        window.showDeleteButton = function () {
            document.getElementById("login-container").style.display = "none";
            document.getElementById("delete-account-container").style.display = "block";
        }

        window.deleteAccount = function () {
            if (confirm("Are you sure you want to delete your account and data?")) {
                auth.currentUser.delete()
                    .then(() => {
                        console.log("Account deleted successfully.");
                        alert("Account deleted successfully.");
                        window.location.reload();
                    })
                    .catch((error) => {
                        console.error("Account deletion failed:", error);
                        alert("Account deletion failed. Please try again.");
                    });
            }
        }

    </script>
</body>

</html>

Thank you.

Ignore keys for null values when sending a post request with react and axios

I am new to JS and I am trying to not include the keys which are null when sent with metadata. Foe ex I should not send tags and owner as they are null but send only filepath as it has value. How can I achieve this?

const metadata = {
        filepath: file.name,
        tags: [''],
        owner: '',

    };

    const formData = new FormData();
    formData.append('file', file);
    formData.append('metadata', JSON.stringify(metadata));

    axios.post('http://localhost:8000/fileUpload', formData, {
        onUploadProgress: (event) => {
       
            }));
        },
    })

remove meta tag or replace in next js

I am using the service https://reqbin.com/curl and it says that I have an error because of the capital letter in the tag attribute.

The attribute name of [ charSet ] must be in lowercase

I tried to add a tag in the head tag hoping that it would be replaced, but it is not replaced, how can I remove the tag with a capital letter? Next.js adds this tag itself, how can I prevent it from adding it?
enter image description hereenter image description here

How to update a div value with js?

i need some help,

i need that only the selected template is displayed on the screen, and all others are removed, so the expected result should be that those values:
<div class="city">City<span>,</span></div> <div class="country">Co</div>
would be replaced from the selected template values.

In short, what I need to do is for the user to choose a city from all those shown and when they click on the desired city, js obtains the values ​​and shows them on the screen, removing all the other options.

const userLocationContainer = document.querySelector("[data-location-container]")
const locationTemplate = document.getElementById("location-template");

function setValue(selector, value, { parent = document } = {}) {
    parent.querySelector(`[data-${selector}]`).textContent = value
}


userLocationContainer.addEventListener('click', handleLocation);

function handleLocation(location) {
    const clonedTemplate = locationTemplate.content.cloneNode(true);
    setValue("city", location.city, { parent: clonedTemplate });
    setValue("country", location.country, { parent: clonedTemplate });

    // Clear previous content of userLocation and append the cloned template
    
    userLocationContainer.innerHTML = '';
    selectedLocation.append(...clonedTemplate.childNodes);
}
</div>
      <div class="locations" data-location-container>
        <div class="mainPlace" id="userLocation">
          <div class="city">City<span>,</span></div>
          <div class="country">Co</div>
        </div>
      </div>
    </div>
  </header>

  <template id="location-template" data-location>
    <div class="mainPlace-template">
      <div class="city" data-city></div><span>,</span>
      <div class="country" data-country></div>
    </div>
  </template>

Any help will be greatly appreciated.

Android requesting location instead of bluetooth permissions

I am debugging a react native app that absolutely needs bluetooth permissions, however at the moment in android the bluetooth permissions are returning unavailable.
I am requesting permissions in my AndroidManifest.xml like this:

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
  <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
  <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />

And I am checking the status of bluetooth permissions like this:

const checkBluetoothPermissions = () => {
    requestMultiple(
      Platform.OS === 'android'
        ? [
            PERMISSIONS.ANDROID.BLUETOOTH_SCAN,
            PERMISSIONS.ANDROID.BLUETOOTH_CONNECT,
            PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
          ]
        : [PERMISSIONS.IOS.BLUETOOTH_PERIPHERAL],
    ).then(_ => {
      console.log('permission results', _);
    });
  };

What is being logged from this function is
permission results {"android.permission.ACCESS_FINE_LOCATION": "granted", "android.permission.BLUETOOTH_CONNECT": "unavailable", "android.permission.BLUETOOTH_SCAN": "unavailable"}
And when installing the app the only permission that is asked is location and I do not know why.
I followed the instructions here: react-native-permissions.

There is no issue on IOS from the same codebase.

Multiple Color Styles in a single console.log()?

I have an array of hex values,

"colors": ["#d5dd90","#e6bb45","#ef9770"]

I can log these out like this:

colors.forEach((value)=>{
  console.log('%cABC', `background: ${value};`);
})

which results in 3 separate console.log() entries:

ABC

______________

ABC

______________

ABC

______________

Each ‘ABC’ being a different color, one log() called for each item in the array.

What I’d like to do write each item in one line, like so:

ABC
ABC
ABC

______________

So basically have one log() call for each array, each styled with its respective color.

Make a function that even if the user close the window it would still run

I’m working on a project in React, i have to execute a function that uses web socket and it would every second retrieve the data, the problem is that i have to find a way so when the user closes the window this function with web socket subscription keeps running, any ideas?
I tried a serverless function but the problem is that i did not know if i could use web socket connection in it

what is html and how to get a backlink

please can you tell that how it work i cannot find it.

i cant get it. let me know please i am so much depressed.
My goal is to achieve excellence in my field, and I’m ready to assist with any Excel or data-related tasks.
if you required any related services you can knock me anytime.
Hello! I’m Rizwan Ghazi, a hard working Data Manager and Specialist with intermediate qualifications.
I’m passionate about Computer Science and hope to learn in future.
beyond work, I enjoy playing both outdoor and indoor games.
In my free time, I enhance my technical skills by practicing on various devices.

JAVA connection to server via thread

I can’t solve this problem: how can I send and receive strings from a server without making the GUI Start button disabled until the end of the interaction? (Maybe I also need to make it so that the button can be pressed multiple times to request many strings) I know I have to use threads but I don’t know how.

I hope I explained myself

This is the listener added to the Start button

public class startListener implements ActionListener{
    public void actionPerformed(ActionEvent e) {
        Thread t = new Thread();
        System.out.println(t);
        try {
            t.start(); //I put this randomly, I don't know how to use it
            PrintWriter write = new PrintWriter(Main.socket.getOutputStream());
            write.println("start");
            write.flush();
            
            Scanner read = new Scanner(Main.socket.getInputStream());
            String s = read.nextLine();
            String tot ="";
            //while (read.hasNextLine()) { 
            for(int i=0; i<24;i++) {
                System.out.println("I read: " + s);
                tot += s + "nn";
                s=read.nextLine();
            }
            Main.Log.append(tot);
            } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

}

Conditional Yup Validation for Dynamic Dropdowns

I have a dropdown list of countries, and based on the selected country, the dropdown for states is populated. Some countries don’t have states, so validation is not needed in those cases. I’ve attempted to implement this using Yup for validation. Can you review my code and let me know if it’s correct and if there is another way to implement this?

import * as Yup from "yup";

const noSpecialCharactersRegExp = /^[a-zA-Z0-9]{4,10}$/;

export const Shchema = Yup.object({
  country: Yup.string().required('Country is required').max(120),
  state: Yup.string()
    .when('state', {
      is: options => options.length > 1,
      then: Yup.string()
        .required("State is required")
        .matches(noSpecialCharactersRegExp, "State is not valid")
        .max(100),
      otherwise: Yup.string().notRequired()
    }),
});

If the state options.length is greater than 1, then the field is required, otherwise it is not required.

I tried creating an array of countries that do not have states and if that country is selected, then no validation will occur.

Modification Request for Cart Price Calculation and Customer Dimensions

Can someone help me with this code? I need to update it so that the calculator’s price is displayed as the final price in the cart for product ID 45255. The ID is automatically fetched, and I also need the customer’s dimensions sent to the calculator to be taken into account. Instead of the fixed dimensions of 40×45, it should use the dimensions entered by the customer during the calculation process.

I would greatly appreciate any assistance with this.

function enqueueCalculatorScript() {
   
    ?>
  <script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function() {
        // Fetch and display dimension ranges
        var productTitleElement = document.querySelector('.product_title.entry-title');
        var productTitle = productTitleElement.innerText;

        jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', {
            'action': 'get_dimension_ranges',
            'product_title': productTitle
        }, function(response) {
            if (!response.error) {
                document.getElementById('min_szerokosc').textContent = response.min_width;
                document.getElementById('max_szerokosc').textContent = response.max_width;
                document.getElementById('min_wysokosc').textContent = response.min_height;
                document.getElementById('max_wysokosc').textContent = response.max_height;
            }
        });

        // Elements for calculating price
        var widthInput = document.getElementById('product_width');
        var heightInput = document.getElementById('product_height');
        var calculateButton = document.getElementById('calculate_price');
        var priceDisplay = document.getElementById('calculated_price');

        calculateButton.addEventListener('click', function() {
            var width = widthInput.value;
            var height = heightInput.value;
            var productTitle = productTitleElement.innerText;

            var data = {
                'action': 'get_variants_for_calculation',
                'width': width,
                'height': height,
                'product_title': productTitle
            };

            // Calculate and display price
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function(response) {
    var variants;
    try {
        variants = JSON.parse(response); // Próbuj przekształcić odpowiedź w obiekt JS
    } catch (e) {
        console.error("Parsing error:", e);
        return;
    }

    if (variants.error) {
        priceDisplay.innerHTML = variants.error;
    } else {
        var priceHtml = variants.sale_price ? 
            '<s>' + variants.regular_price + '</s> ' + variants.sale_price :
            variants.regular_price;
        priceDisplay.innerHTML = 'Cena: ' + priceHtml;
    }
});
          
            });
        });

</script>

        <?php
    }


add_action('wp_enqueue_scripts', 'enqueueCalculatorScript');

function getVariantsForCalculation() {
    $product_title = isset($_POST['product_title']) ? sanitize_text_field($_POST['product_title']) : '';

    $query = new WP_Query([
        'post_type' => 'product',
        'title' => $product_title
    ]);

    if ($query->have_posts()) {
        $query->the_post();
        $post_id = get_the_ID();
        $variants = get_post_meta($post_id, 'custom_variants', true);

        $client_width = isset($_POST['width']) ? floatval(sanitize_text_field($_POST['width'])) : 0;
        $client_height = isset($_POST['height']) ? floatval(sanitize_text_field($_POST['height'])) : 0;

        // Initialize nearest match and distance
        $nearestVariant = null;
        $smallestDistance = PHP_FLOAT_MAX;

        // Iterate over each variant to find the nearest match
        foreach ($variants as $variant) {
            $variantWidth = floatval($variant['width']);
            $variantHeight = floatval($variant['height']);

            // Calculate Euclidean distance from the requested size
            $distance = sqrt(pow($variantWidth - $client_width, 2) + pow($variantHeight - $client_height, 2));

            // Update nearest match if a closer one is found
            if ($distance < $smallestDistance) {
                $smallestDistance = $distance;
                $nearestVariant = $variant;
            }
        }

        if ($nearestVariant) {
    $response = [
        'regular_price' => $nearestVariant['regular_price'],
        'product_id' => $post_id  // Include the product ID
    ];
           

            if (!empty($nearestVariant['sale_price'])) {
                $response['sale_price'] = $nearestVariant['sale_price'];
            }

            echo json_encode($response);
        } else {
            echo json_encode(['error' => 'No matching variant found']);
        }
    } else {
        echo json_encode(['error' => 'Product not found']);
    }

    wp_die();
}


// Hook dla użytkowników zalogowanych
add_action('wp_ajax_get_variants_for_calculation', 'getVariantsForCalculation');

// Hook dla użytkowników niezalogowanych
add_action('wp_ajax_nopriv_get_variants_for_calculation', 'getVariantsForCalculation');

// Modify the price in the cart for product ID 45255
function custom_price_for_cart_items( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
        return;
    }

    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        if ( $cart_item['product_id'] == 45255 || ( isset( $cart_item['variation_id'] ) && $cart_item['variation_id'] == 45255 ) ) {
            $cart_item['data']->set_price( 15 ); // Set custom price to 15
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'custom_price_for_cart_items', 10, 1 );

function custom_price_html_for_product_id_45255( $price_html, $product ) {
    if ( $product->get_id() == 45255 ) {
        $price_html = wc_price(15); // Display custom price as 15 zł
    }
    return $price_html;
}
add_filter( 'woocommerce_get_price_html', 'custom_price_html_for_product_id_45255', 10, 2 );

function custom_price_for_product_45255( $price, $product ) {
    if ( $product->get_id() == 45255 ) {
        return 15; // Set custom price to 15
    }
    return $price;
}
if ( !is_admin() ) {
    add_filter( 'woocommerce_product_get_price', 'custom_price_for_product_45255', 10, 2 );
    add_filter( 'woocommerce_product_get_regular_price', 'custom_price_for_product_45255', 10, 2 );
    add_filter( 'woocommerce_product_variation_get_regular_price', 'custom_price_for_product_45255', 10, 2 );
    add_filter( 'woocommerce_product_variation_get_price', 'custom_price_for_product_45255', 10, 2 );
}

// Ensure the regular price is the same as the custom price
function set_regular_price_for_product_45255( $regular_price, $product ) {
    if ( $product->get_id() == 45255 ) {
        return 15; // Set regular price to 15
    }
    return $regular_price;
}
add_filter( 'woocommerce_product_get_regular_price', 'set_regular_price_for_product_45255', 10, 2 );
add_filter( 'woocommerce_product_variation_get_regular_price', 'set_regular_price_for_product_45255', 10, 2 );

function add_custom_dimensions_to_cart_item( $cart_item_data, $product_id, $variation_id ) {
    // Get the product title from the product ID
    $product = wc_get_product($product_id);
    $product_title = $product ? $product->get_title() : '';

    // Use WP_Query to get the ID based on the title
    $query = new WP_Query([
        'post_type' => 'product',
        'title' => $product_title
    ]);

    if ($query->have_posts()) {
        $query->the_post();
        $queried_product_id = get_the_ID();

        // Compare with the queried product ID
        if ( $product_id == $queried_product_id || $variation_id == $queried_product_id ) {
            $cart_item_data['custom_dimensions'] = '40x45';
        }
    }

    return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_dimensions_to_cart_item', 10, 3 );


function display_custom_dimensions_in_cart( $item_data, $cart_item ) {
    if ( array_key_exists( 'custom_dimensions', $cart_item ) ) {
        $item_data[] = array(
            'name' => 'Wymiary',
            'value' => $cart_item['custom_dimensions']
        );
    }
    return $item_data;
}
add_filter( 'woocommerce_get_item_data', 'display_custom_dimensions_in_cart', 10, 2 );

function add_custom_dimensions_to_order_items( $item, $cart_item_key, $values, $order ) {
    if ( array_key_exists( 'custom_dimensions', $values ) ) {
        $item->add_meta_data( 'Wymiary', $values['custom_dimensions'] );
    }
}
add_action( 'woocommerce_checkout_create_order_line_item', 'add_custom_dimensions_to_order_items', 10, 4 );

Blob-video link doesn’t work in Chromium browser

I use URL.createObjectURL() to generate blob-url to local video.
It works on most of the browser (tested bunch of mobile and desktop browsers).
But now I tried to use Chromium (for autotesting purposes).
It does generate blob-url, but it is just empty.
So i can’t put this url to video source. Obviously, video events like ‘loadedmetadata’ do not trigger.
Also, blob link doesn’t work in another tab.

function setVideo(el) 
{
  console.log('inited');
    const file = el.files[0];
  let video = document.querySelector('#video');
  let url = URL.createObjectURL(file);
  let videoSrc = video.querySelector('source');
  videoSrc.src = url;
  videoSrc.setAttribute('type', file.type);
  let metaLoaded = function () {
   console.log('metaloaded');
  };
  
  video.load();

  if ( video.readyState > 0 )
    metaLoaded();
  else
    video.addEventListener('loadedmetadata', metaLoaded, false);
}

Example https://jsfiddle.net/pwdhs42v/3/
Works on all browsers except of Chromium (122.0.6258.0)
Any idea why it works like that? Could it be some security restriction? If so, can I disable it?

Thanks in advance!

Is there an equivalent to getElementById but for looking INSIDE script tags?

I am used to using document.getElementById to find something very specific.

However I now want to find something that’s inside script tags, when you go to “view source:

so, for example, for this random product page you can “view source” and find (in page) landingImageUrl":"

<script type="a-state" data-a-state="{&quot;key&quot;:&quot;desktop-landing-image-data&quot;}">{"landingImageUrl":"https://m.media-amazon.com/images/I/41iuSZgmF2L.__AC_SX300_SY300_QL70_ML2_.jpg"}</script>

what I am looking for is that URL to a small image.

Can i do this programmatically?

  • I suppose I could use a regular expression to get the image URL https://m.media-amazon.com/images/I/41iuSZgmF2L.__AC_SX300_SY300_QL70_ML2_.jpg if I had downloaded the HTML file.
  • Are there any other techniques I could use, even outside javascript, such as AppleScript ?

Benefits of .nvmrc file?

I understand that this will let the project know what version of node is being used. But without it, the projects still run and the dependencies still get installed so what is the benefit of having it? And also is it useless if the end user doesn’t run ‘nvm use’?

Expecting to find out and understand what are the benefits of having a .nvmrc file.