I want to use javascript to get my site users webcam and take some pictures with it

I want to use javascript to access my site users camera and take pictures with it which will be uploaded with php to my server please who can give me a full html css javascript and php example please full code

I want it to ask for permission from the user and the when accepted take some pictures or even short videos which will then be uploaded with php to my server with no encryption

discord bot is showing online but doesnt show up need commands

so i keep getting a: The application did not respond.

yet it shows up as online on discord
and now of the new commands i made are showing up yet the old ones i deleted are still there


import { Client, Collection, GatewayIntentBits } from 'discord.js';
import fs from 'fs';
import dotenv from 'dotenv';
dotenv.config();

const client = new Client({
  intents: [GatewayIntentBits.Guilds]
});

client.commands = new Collection();

const commandsPath = './src/commands';
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
  import(`./src/commands/${file}`).then(commandModule => {
    client.commands.set(commandModule.default.data.name, commandModule.default);
  });
}

client.once('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('interactionCreate', async interaction => {
  if (!interaction.isCommand()) return;

  const command = client.commands.get(interaction.commandName);
  if (!command) return;

  try {
    await command.execute(interaction);
  } catch (error) {
    console.error(error);
    await interaction.reply({ content: 'There was an error executing that command.', ephemeral: true });
  }
});

client.login(process.env.DISCORD_TOKEN);

Make a discord bot for my discord

recognize_google do not work with sr.AudioData() in python

I want to get an audio file in js and then send this file to python and then recognise the text being spoken. I know that tools exist in js, but I need server-side recognition in order to secure the interface in an online mini-game.
main.js

async function try_case(click) {
    var el = click.target;
    el.innerHTML = microphoneHtml;
    for (var i = 0; i < items.length; i++) {
        items[i].removeEventListener('click', try_case);
    }
    navigator.mediaDevices.getUserMedia({ audio: true })
        .then(function(stream) {
            var mediaRecorder = new MediaRecorder(stream);
            mediaRecorder.start();
            var audioChunks = [];
            mediaRecorder.addEventListener("dataavailable", function(event) {
                audioChunks.push(event.data);
            });
            mediaRecorder.addEventListener("stop", function() {
                document.getElementsByClassName('micro-listener')[0].classList.add('exit');
                setTimeout(function() {
                    el.innerHTML = "";
                }, 500);
                var audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                var formData = new FormData();
                formData.append('audio', audioBlob);

                fetch(`/dashboard/games/memowordrize/${sessionID}/record`, {
                        method: 'POST',
                        headers: {
                            'X-CSRFToken': csrf_token
                        },
                        body: formData
                    })
                    .then(response => response.text())
                    .then(data => {
                        console.log(data);
                    });

            });
            setTimeout(function() {
                mediaRecorder.stop();
            }, 3000);
        });

    return;
}

memowordrize.py

@memowordrize_bp.route('/dashboard/games/memowordrize/<string:session_id>/record', methods=['POST'])
@check_game
def record(session_id):
    try:
        if 'audio' not in request.files:
            return jsonify({
                "code": 403,
                "message": "Aucun fichier audio n'a été trouvé!",
                "result": []
            })
        audio_file = request.files['audio']
        audio_data = audio_file.read()
        
        recognizer = sr.Recognizer()
        audio = sr.AudioData(audio_data, 16000, 2)
        text = recognizer.recognize_google(audio, language="fr-FR")
        print(text)
        return jsonify({
            "code": 200,
            "message": "Le texte a été reconnu!"
        })
        

    except Exception as e:
        logging.error("An error has occured: " + str(e))
        return jsonify({
            "code": 500,
            "message": "Une erreur s'est produite!",
            "result": []
        }), 500

Everything works (I didn’t put in all my code), it’s from the line text = recognizer.recognize_google(audio, language="fr-FR") that an error is detected.

The error is captured but nothing is displayed to indicate: ERROR:root:An error has occured:. But nothing is indicated. No indication on the net or by chatGpt.

(node:23840) MaxListenersExceededWarning: Possible EventEmitter memory leak detected

I was installing some dependencies using npm install and then while it was getting installed i kept on getting the following warning:

PS D:EXTRA CLASSESWeb DevelopmentReactreact-course-v3-main4-fundamental-projects2-toursstarter> npm install
(node:23840) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [TLSSocket]. Use emitter.setMaxListeners() to increase limit
(Use `node --trace-warnings ...` to show where the warning was created)
(node:23840) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [TLSSocket]. Use emitter.setMaxListeners() to increase limit
(node:23840) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [TLSSocket]. Use emitter.setMaxListeners() to increase limit
(node:23840) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [TLSSocket]. Use emitter.setMaxListeners() to increase limit
(node:23840) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [TLSSocket]. Use emitter.setMaxListeners() to increase limit
(node:23840) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [TLSSocket]. Use emitter.setMaxListeners() to increase limit
[..................] / idealTree:starter: sill idealTree buildDeps

I tried doing the following as suggested in the error message:

PS D:EXTRA CLASSESWeb DevelopmentReactreact-course-v3-main4-fundamental-projects2-toursstarter> emitter.setMaxListeners(0)

but then it gave the following error:

emitter.setMaxListeners : The term 'emitter.setMaxListeners' is not recognized as the name of a cmdlet, function, script file, or operable program.  
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1

What can i do to fix this issue?

Regex ignore patterns

I’m trying to highlight some text but I want to exclude some patterns from being matched.

First I’m securing the text, replacing & with &amp; and < with &lt; then I look for matches and add the strong tag around it

html.replace(new RegExp(`${patterns.join('|')}`, 'g'), (match, group) => {
                return `<strong>${match}<strong>`;
            });

So if I have a text like amp & and try to highlight amp it becomes <strong>amp<strong> &<strong>amp<strong>;. How can I ignore &amp; and &lt; from being matched?

I tried (new RegExp(^(?!&amp;|&lt;)(${patterns.join('|')}), ‘g’) but it’s not working

How to dynamically add elements to a element with vanilla JS?

I am trying to dynamically add two options to a <select> dropdown based on previous options selected. For lack of a better analogy, its kinda like the NCAA March madness bracket.
There are two choices a user can pick, and then from there that selection choosen, moves on to the next head to head choice, and the bracket will have the selected options in the dropdown to choose from, if the previous has not been selected then the drop down is blank.

<div class="top">
    <select name="c01_T" id="c01_T" class="choice-select" onclick="refresh(id)">
        <option value="none">Select Me</option>
        <option value="Choice 1">Choice 1</option>
        <option value="Choice 2">Choice 2</option>
    </select>
</div>
<div class="bot">
    <select name="c01_B" id="c01_B" class="choice-select" onclick="refresh(id)">
        <option value="none">Select Me</option>
        <option value="Choice 3">Choice 3</option>
        <option value="Choice 4">Choice 4</option>
        </select>
</div>
<div class="top">
    <select name="c09_T" id="c09_T" class="choice-select" onclick="refresh(id)">
        <option value="none">Select Me</option>
    </select>
</div>
<div class="bot">
    <select name="c09_B" id="c09_B" class="choice-select" onclick="refresh(id)">
        <option value="none">Select Me</option>
    </select>
</div>

<div class="bot">
    <select name="c13_T" id="c13_T" class="choice-select" onclick="refresh(id)">
        <option value="none">Select Me</option>
    </select>
</div>

then my vanilla JS function is this..

var idHome, idAway, textH, textA;
function refresh(id) {
    idHome, idAway, textH, textA = null;
    if (id == "c09_T") {
        x = document.getElementById('c01_T').selectedIndex;
        textH = document.getElementsByTagName("option")[x].value;
        y = document.getElementById('c01_B').selectedIndex;
        textA = document.getElementsByTagName("option")[y].value;
        
    } else if (id == "c09_B") {
        x = document.getElementById('c08_T').selectedIndex;
        textH = document.getElementsByTagName("option")[x].value;
        y = document.getElementById('c08_B').selectedIndex;
        textA = document.getElementsByTagName("option")[y].value;
        
    } else if (id == "c13_T") {
        x = document.getElementById('c09_T').selectedIndex;
        textH = document.getElementsByTagName("option")[x].value;
        y = document.getElementById('c09_B').selectedIndex;
        textA = document.getElementsByTagName("option")[y].value;
    } else if (id == "c13_B") {
        x = document.getElementById('c10_T').selectedIndex;
        textH = document.getElementsByTagName("option")[x].value;
        y = document.getElementById('c10_B').selectedIndex;
        textA = document.getElementsByTagName("option")[y].value;
    }   
    if (textH !== "none" && textA !== "none") {
       teamSelect = document.getElementById(id);
       teamSelect.options.length = 2; //set length at 3 in case select is clicked more than once
       teamSelect.remove(1); //remove options and reset in case its clicked more than once
       teamSelect.remove(2); //remove options and reset in case its clicked more than once
    
       teamSelect.add(new Option(textH, textH)); // add option 1
       teamSelect.add(new Option(textA, textA)); // add option 2    
    }   
}

The problem is that its showing the <options> in the dropdown in the browser…but regardless of which one I select it always returns the second option (index 1)…the one that’s not the first “Select me” option.
Why wont the <select> element show the selected option?
Thanks for any help!

Javascript saving on cart

`document.addEventListener('DOMContentLoaded', (event) => {
  
  $(document).ready(function() {
    // Function to update the cart subtotal and full cart
    function updateCartTotals() {
      let subtotal = 0;
      $('.cart-total-price').each(function() {
        subtotal += parseFloat($(this).text().replace('$', ''));
      });
  
      // Update the cart subtotal
      $('.cart-subtotal').text('$' + subtotal.toFixed(2));
  
      // Update the full cart
      $('.full-cart').text('$' + subtotal.toFixed(2));
    }
  
    // Call the updateCartTotals function when the page loads
    updateCartTotals();
  
    // Call the updateCartTotals function when a cart item is added or removed
    $(document).on('click', '.cart-remove', function() {
      updateCartTotals();
    });
  
    $(document).on('change', '.cart-quantity input', function() {
      updateCartTotals();
    });
  });
  
  function removeCartItem(event) {
    // Get the button element that was clicked
    var buttonClicked = event.target;
  
    // Get the table row (TR element) containing the button
    var tableRow = buttonClicked.closest('tr');
  
    // Get the product name from the table row
    var productName = tableRow.getElementsByClassName('cart-pro')[0].innerText;
  
    // Get the existing cart from localStorage
    var cart = JSON.parse(localStorage.getItem('cart')) || [];
  
    // Find the index of the product in the cart
    var productIndex = cart.findIndex(function(item) {
      return item.name === productName;
    });
  
    // If the product is found in the cart, remove it
    if (productIndex > -1) {
      let removedItem = cart.splice(productIndex, 1)[0];
  
    // Save the updated cart back to localStorage
      localStorage.setItem('cart', JSON.stringify(cart));

      // Remove the table row
      if (tableRow) {
        tableRow.remove();
      }
    }
  }
  
  // Quantity Changes
  function quantityChanged(event){
    var input = event.target
    if (isNaN(input.value) || input.value <= 0){
        input.value = 1;
    }
  }

  // register products from shop to sproduct 

  let pro1 = document.querySelector('.pro1');

  if (pro1) {
    pro1.addEventListener('click', function() {
      let imgSrc = this.querySelector('.r-img').src;
      let category = this.querySelector('.Category').textContent;
      let productName = this.querySelector('.product').textContent;
      let price = this.querySelector('.shop-price').textContent;
      let description = this.querySelector('.main-desc').textContent;

      localStorage.setItem('imgSrc', imgSrc);
      localStorage.setItem('category', category);
      localStorage.setItem('productName', productName);
      localStorage.setItem('price', price);
      localStorage.setItem('description', description);

      window.location.href = 'sproduct.html';
    });
  }

  // Then, in sproduct.html, you can retrieve these details from localStorage
  window.onload = function() {
    const mainImg = document.getElementById('MainImg');
    const productName = document.querySelector('.sprod-pro-name');
    const productPrice = document.querySelector('.sproduct-price');
    const category = document.querySelector('.sprod-category');
    const description = document.querySelector('.spro-main-desc');
  
    if (mainImg && productName && productPrice) {
      mainImg.src = localStorage.getItem('imgSrc');
      category.textContent = localStorage.getItem('category');
      productName.textContent = localStorage.getItem('productName');
      productPrice.textContent = localStorage.getItem('price');
      description.textContent = localStorage.getItem('description');
    }
  
    // register products from sproduct to cart
    const addToCartButton = document.querySelector('#addCart');
    const selectedSize = document.querySelector('.s-size');
    const quantityInput = document.querySelector('.quantity');
  
    if (addToCartButton) {
      addToCartButton.addEventListener('click', function () {
        const productImage = mainImg.src;
        const name = productName.textContent.trim();
        let price = parseFloat(productPrice.textContent.slice(1));
        let pprice = parseFloat(productPrice.textContent.slice(1));
        const size = selectedSize.value;
        const quantity = parseInt(quantityInput.value);

        if (size === 'M') {
          pprice += 50;
        }
        else if (size === 'L') {
          pprice += 100;
        }

        const product = {
          image: productImage,
          name,
          price,
          pprice,
          size,
          quantity,
        };

  
        let existingCart = [];
        if (localStorage.getItem('cart')) {
          existingCart = JSON.parse(localStorage.getItem('cart'));
        }
  
        existingCart.push(product);
  
        localStorage.setItem('cart', JSON.stringify(existingCart));
  
      // Show success message
      document.getElementById('successPopup').style.display = 'block';
      setTimeout(() => {
        document.getElementById('successPopup').style.display = 'none';
      }, 10000); // Hide success message after 10 seconds

        window.location.href = 'cart.html';
      });
    } 
  };

  
// Functionality for cart.html

  const cartData = JSON.parse(localStorage.getItem('cart')) || [];

  function generateCartItem(item) {
    let sizePrice = item.size === 'M' ? 50 : (item.size === 'L' ? 100 : 0);
    return `
    <tr>
    <td><i class="bi bi-x-square-fill cart-remove"></i><a href="#"></a></td>
    <td><img src="${item.image}" alt="" class="cart-img"></td>
    <td class="cart-pro">${item.name}</td>
    <td class="cart-price">$${item.price}</td>
    <td class="cart-price1" style="display: none;">$${item.pprice}</td>
    <td class="cart-quantity"><input type="number" value="${item.quantity}" min="0"></td>
    <td class="cart-size">
        <select class="c-size">
            <option class="Small" ${item.size === 'S' ? 'selected' : ''}>S</option>
            <option class="Medium" ${item.size === 'M' ? 'selected' : ''}>M</option>
            <option class="Large" ${item.size === 'L' ? 'selected' : ''}>L</option>
        </select>
    </td>
    <td class="cart-total-price">$${((item.price + sizePrice) * item.quantity).toFixed(2)}</td>
</tr>
    `;
  }
  
  const cartItemsHTML = cartData.map(generateCartItem).join('');

  if (document.querySelector('tbody')) {
    document.querySelector('tbody').innerHTML = cartItemsHTML;
  }

  let sizes = document.querySelectorAll('.c-size');
  let quantities = document.querySelectorAll('.cart-quantity input');
  let prices = document.querySelectorAll('.cart-price1');
  let totalPriceElements = document.querySelectorAll('.cart-total-price');
  
  sizes.forEach((size, index) => {
    let price = parseFloat(prices[index].innerText.replace('$', ''));
    let totalPriceElement = totalPriceElements[index];
    let lastSize = size.value;
    let quantity = quantities[index];
    let lastQuantity = parseInt(quantity.value);
  
    size.addEventListener('change', function() {
      let newSize = size.value;
      if ((lastSize === 'S' && newSize === 'M') || (lastSize === 'M' && newSize === 'L')) {
          price += 50;
      } else if (lastSize === 'S' && newSize === 'L') {
          price += 100;
      } else if ((lastSize === 'L' && newSize === 'M') || (lastSize === 'M' && newSize === 'S')) {
          price -= 50;
      } else if (lastSize === 'L' && newSize === 'S') {
          price -= 100;
      }
      lastSize = newSize;
      totalPriceElement.innerText = '$' + (price * quantity.value).toFixed(2);

    // Find the corresponding item in cartData and update its size and price
      let item = cartData[index];
      item.size = size.value;
      item.price = price;

    // Update the total price in the cart.html page
      let subtotal = parseFloat(document.querySelector('.cart-subtotal').innerText.replace('$', ''));
      document.querySelector('.cart-subtotal').innerText = '$' + (subtotal + (price * quantity.value) - (lastPrice * lastQuantity)).toFixed(2);
      document.querySelector('.full-cart').innerText = '$' + (subtotal + (price * quantity.value) - (lastPrice * lastQuantity)).toFixed(2);

    // Save the updated cartData to localStorage
    localStorage.setItem('cart', JSON.stringify(cartData));

    });
  
    quantity.addEventListener('change', function() {
      let newQuantity = parseInt(quantity.value);
      if (newQuantity < lastQuantity) {
        totalPriceElement.innerText = '$' + (price * newQuantity).toFixed(2);
      } else {
        totalPriceElement.innerText = '$' + (price * newQuantity).toFixed(2);
      }
      lastQuantity = newQuantity;
    
    // Find the corresponding item in cartData and update its quantity
     let item = cartData[index];
     item.quantity = parseInt(quantity.value);
 
    // Save the updated cartData to localStorage
     localStorage.setItem('cart', JSON.stringify(cartData));

    });
  });
});`

cart.html

`            <div id="subtotal">
                <h3>Cart Totals</h3>
                <table>
                    <tr>
                        <td>Cart Subtotal</td>
                        <td class="cart-subtotal"></td>
                    </tr>
                    <tr>
                        <td>Shipping</td>
                        <td>Free</td>
                    </tr>
                    <tr>
                        <td><strong>Total</strong></td>
                        <td class="full-cart"><strong></strong></td>
                    </tr>
                </table>
                <a href="checkout.html"><button class="normal">Proceed to checkout</button></a>
            </div>
        </div>`

1.When I select a size for an item in cart.html and refresh the page, the selected size gets reset. Please how can i correct this behavior.
2.When I change the size of an item in cart.html, the cart-total-price changes correctly, as it should. The same goes for the quantity change. However, the cart-subtotal and full-cart values are not being updated accordingly.

i tried using everything but i can’t find the bug pls help me

Is it possible to console.log the contents of the loaded third party script from an HTML script tag?

Lets say I am using the turndown Javascript package:

https://github.com/mixmark-io/turndown

and loading it this way in my HTML:

<script src="https://unpkg.com/turndown/dist/turndown.js"></script>

This loads the following:

enter image description here

and makes TurnDown service available to be used as such:

var turndownService = new TurndownService({ headingStyle: 'atx', emDelimiter : '*' });

Is it possible to console.log the entire script which has been loaded by the above script tag? Aka, is it possible to log the following:

var TurndownService = (function () {
  'use strict';

  function extend (destination) { ........

  .....

  return TurndownService;

}());

The reason I need to do this is that I want to pass these third party scripts to a WebView in iOS using webkit handlers.

How to add disabled attribute and remove required attribute to an input text field with javascript with a checkbox onclick action?

I need to update form fields : remove required and turn disabled on
in order to let the user not filling those fields with a chekbox onclick action

i tried to do it myself but i need to be sure how to adress disabled attribute and required attribute to a input text field. I have to understand if i have to put the attribute in the html tag or just play with javascript or jquery

Filtering Parcels by Valid Pixel Percentage for Statistics Calculation in Google Earth Engine

I’m working on a Google Earth Engine project where I need to calculate statistics (mean, standard deviation) of vegetation indices for different parcels. However, some images have significant cloud cover, affecting the statistics’ accuracy.

My goal is to filter out parcels with less than 50% valid pixels to ensure statistics are calculated using reliable information.

  • I’m using the Sentinel-2 image collection (“COPERNICUS/S2_SR_HARMONIZED”).
  • I’ve implemented functions for calculating vegetation index statistics.
  • I need help integrating the valid pixel percentage filtering into the processing workflow.
var parcelas = ee.FeatureCollection('projects/resag-1/assets/PAR_22_Cebada')


var convencional = ee.FeatureCollection(parcelas)
    .filter(ee.Filter.eq('Manejo','convencional'));

var conservacion = ee.FeatureCollection(parcelas)
    .filter(ee.Filter.eq('Manejo','conservacion'));
 
    
var addindices = function(image) {
  var ndvi = image.normalizedDifference(['B8','B4']).rename('NDVI');
  var CRC1 = image.normalizedDifference(['B11','B2']).rename('CRC1');
  var NDSVI = image.normalizedDifference(['B11','B4']).rename('NDSVI');  /// normalized Diff Moisture Index
  var NDI7 = image.normalizedDifference(['B8','B12']).rename('NDI7'); 
  var NDI5 = image.normalizedDifference(['B8','B11']).rename('NDI5');
  var NDRI = image.normalizedDifference(['B12','B3']).rename('NDRI'); 
  var DFI = image.expression(                                               
      '100*(1-B12/B11)*(B4/B8A)', {         
      'B11': image.select('B11'),
      'B12': image.select('B12'),
      'B4' : image.select('B4'),
      'B8A': image.select('B8A')
    }).rename('DFI'); 
  var NDI3 = image.normalizedDifference(['B4','B12']).rename('NDI3'); 
  var NDI4 = image.normalizedDifference(['B8A','B12']).rename('NDI4'); 
  var RATIO = image.expression(                                               /// Triangle vegetation index
      'B12/B11'/*10000*/, {         
      'B11': image.select('B11'),
      'B12': image.select('B12')
    }).rename('RATIO');
  var MCRC = image.normalizedDifference(['B11','B3']).rename('MCRC'); 
  var SRNDI = image.normalizedDifference(['B12','B4']).rename('SRNDI'); 
  var NDTI = image.normalizedDifference(['B11','B12']).rename('NDTI'); /// normalized Diff Red Edge Index
  var STI = image.expression(                                               /// Triangle vegetation index
      'B11/B12',{         // DIVIDIDO PARA 10000 POR LA REFLECTANCIA ADICIONAL 10 PARA RANGO
      'B11': image.select('B11'),
      'B12': image.select('B12')
    }).rename('STI');
  return image.addBands([ndvi,CRC1,NDSVI,NDI7,NDI5,MCRC,SRNDI,NDTI,STI,RATIO,DFI,NDI3,NDI4,NDRI]);
};



// Funcion mask clouds
function maskclouds_scl(imagen) {
  var scl = imagen.select('SCL');
  // Seleccionar las clases de vegetacion, suelo, agua y nieve
  var veg = 4;
  var soil = 5;
  var water = 6;
  var snow = 11;
  // Mascara
  var mask = scl.eq(veg).or(scl.eq(soil)).or(scl.eq(water)).or(scl.eq(snow));
  var properties = imagen.propertyNames();
  var imagen_mask = ee.Image(imagen.updateMask(mask).copyProperties(imagen,properties));
  return imagen_mask;
}


//sentinel-2 LA2
var S2 = ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED");

var dataset = S2.filter(ee.Filter.date('2022-01-01', '2022-12-31'))
                // filtro inicialmente por nubosidad
                  //.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',10))
                  .filterBounds(parcelas)
                  .map(maskclouds_scl)
                  .map(addindices)
                  .select('B2','B3','B4','B5','B6','B7','B8','B8A','B11','B12',
                          'NDVI','CRC1','NDSVI','NDI7','NDTI','STI','NIRv','MCRC','SRNDI','NDI5','RATIO','DFI','NDI3','NDI4','NDRI');
print(dataset)                  

//STATISTICS

var stats = dataset.map(function(image) {
  return convencional.map(function(f){
    var mean = image.reduceRegion({reducer: ee.Reducer.mean(),geometry: f.geometry(),scale: 20});
    var std = image.reduceRegion({reducer: ee.Reducer.stdDev(),geometry: f.geometry(),scale: 20});
    return f.set({
      'date': image.date().format(),
      // MEDIA
      'NDVI_mean': mean.get('NDVI'),'CRC1_mean': mean.get('CRC1'),
      'NDSVI_mean': mean.get('NDSVI'),'NDI7_mean': mean.get('NDI7'),
      'NDTI_mean': mean.get('NDTI'),'STI_mean': mean.get('STI'),
      'MCRC_mean': mean.get('MCRC'),
      'SRNDI_mean': mean.get('SRNDI'),'NDI5_mean': mean.get('NDI5'),
      'RATIO_mean': mean.get('RATIO'),'DFI_mean': mean.get('DFI'),
      'NDI3_mean': mean.get('NDI3'),'NDI4_mean': mean.get('NDI4'),
      'NDRI_mean': mean.get('NDRI'),
      // DESVIACION ESTANDAR
      'NDVI_std': std.get('NDVI'),'CRC1_std': std.get('CRC1'),
      'NDSVI_std': std.get('NDSVI'),'NDI7_std': std.get('NDI7'),
      'NDTI_std': std.get('NDTI'),'STI_std': std.get('STI'),
      'MCRC_std': std.get('MCRC'),
      'SRNDI_std': std.get('SRNDI'),'NDI5_std': std.get('NDI5'),
      'RATIO_std': std.get('RATIO'),'DFI_std': std.get('DFI'),
      'NDI3_std': std.get('NDI3'),'NDI4_std': std.get('NDI4'),
      'NDRI_std': std.get('NDRI')
    });
  });
})
.flatten()
// MEDIA
.filter(ee.Filter.neq('NDVI_mean', null))
.filter(ee.Filter.neq('CRC1_mean', null)).filter(ee.Filter.neq('NDSVI_mean', null))
.filter(ee.Filter.neq('NDI7_mean', null)).filter(ee.Filter.neq('NDTI_mean', null))
.filter(ee.Filter.neq('STI_mean', null)).
.filter(ee.Filter.neq('MCRC_mean', null)).filter(ee.Filter.neq('SRNDI_mean', null))
.filter(ee.Filter.neq('NDI5_mean', null)).filter(ee.Filter.neq('RATIO_mean', null))
.filter(ee.Filter.neq('DFI_mean', null)).filter(ee.Filter.neq('NDI3_mean', null))
.filter(ee.Filter.neq('NDI4_mean', null)).filter(ee.Filter.neq('NDRI_mean', null))
// DESVIACION ESTANDAR
.filter(ee.Filter.neq('NDVI_std', null))
.filter(ee.Filter.neq('CRC1_std', null)).filter(ee.Filter.neq('NDSVI_std', null))
.filter(ee.Filter.neq('NDI7_std', null)).filter(ee.Filter.neq('NDTI_std', null))
.filter(ee.Filter.neq('STI_std', null)).
.filter(ee.Filter.neq('MCRC_std', null)).filter(ee.Filter.neq('SRNDI_std', null))
.filter(ee.Filter.neq('NDI5_std', null)).filter(ee.Filter.neq('RATIO_std', null))
.filter(ee.Filter.neq('DFI_std', null)).filter(ee.Filter.neq('NDI3_std', null))
.filter(ee.Filter.neq('NDI4_std', null)).filter(ee.Filter.neq('NDRI_std', null));
// Export
Export.table.toDrive({
  collection: stats,
  description: 'index_S2_cons',
  fileFormat: 'CSV',
  folder: ''
}); 

//Estadisticas conservacion
var stats = dataset.map(function(image) {
  return conservacion.map(function(f){
    var mean = image.reduceRegion({reducer: ee.Reducer.mean(),geometry: f.geometry(),scale: 20});
    var std = image.reduceRegion({reducer: ee.Reducer.stdDev(),geometry: f.geometry(),scale: 20});
    return f.set({
      'date': image.date().format(),
      'NDVI_mean': mean.get('NDVI'),'CRC1_mean': mean.get('CRC1'),
      'NDSVI_mean': mean.get('NDSVI'),'NDI7_mean': mean.get('NDI7'),
      'NDTI_mean': mean.get('NDTI'),'STI_mean': mean.get('STI'),
      'MCRC_mean': mean.get('MCRC'),
      'SRNDI_mean': mean.get('SRNDI'),'NDI5_mean': mean.get('NDI5'),
      'RATIO_mean': mean.get('RATIO'),'DFI_mean': mean.get('DFI'),
      'NDI3_mean': mean.get('NDI3'),'NDI4_mean': mean.get('NDI4'),
      'NDRI_mean': mean.get('NDRI'),
      // DESVIACION ESTANDAR
      'NDVI_std': std.get('NDVI'),'CRC1_std': std.get('CRC1'),
      'NDSVI_std': std.get('NDSVI'),'NDI7_std': std.get('NDI7'),
      'NDTI_std': std.get('NDTI'),'STI_std': std.get('STI'),
      'MCRC_std': std.get('MCRC'),
      'SRNDI_std': std.get('SRNDI'),'NDI5_std': std.get('NDI5'),
      'RATIO_std': std.get('RATIO'),'DFI_std':  std.get('DFI'),
      'NDI3_std':  std.get('NDI3'),'NDI4_std':  std.get('NDI4'),
      'NDRI_std':  std.get('NDRI')
    });
  });
})
.flatten()
// MEDIA
.filter(ee.Filter.neq('NDVI_mean', null))
.filter(ee.Filter.neq('CRC1_mean', null)).filter(ee.Filter.neq('NDSVI_mean', null))
.filter(ee.Filter.neq('NDI7_mean', null)).filter(ee.Filter.neq('NDTI_mean', null))
.filter(ee.Filter.neq('STI_mean', null))
.filter(ee.Filter.neq('MCRC_mean', null)).filter(ee.Filter.neq('SRNDI_mean', null))
.filter(ee.Filter.neq('NDI5_mean', null)).filter(ee.Filter.neq('RATIO_mean', null))
.filter(ee.Filter.neq('DFI_mean', null)).filter(ee.Filter.neq('NDI3_mean', null))
.filter(ee.Filter.neq('NDI4_mean', null)).filter(ee.Filter.neq('NDRI_mean', null))
// DESVIACION ESTANDAR
.filter(ee.Filter.neq('NDVI_std', null))
.filter(ee.Filter.neq('CRC1_std', null)).filter(ee.Filter.neq('NDSVI_std', null))
.filter(ee.Filter.neq('NDI7_std', null)).filter(ee.Filter.neq('NDTI_std', null))
.filter(ee.Filter.neq('STI_std', null))
.filter(ee.Filter.neq('MCRC_std', null)).filter(ee.Filter.neq('SRNDI_std', null))
.filter(ee.Filter.neq('NDI5_std', null)).filter(ee.Filter.neq('RATIO_std', null))
.filter(ee.Filter.neq('DFI_std', null)).filter(ee.Filter.neq('NDI3_std', null))
.filter(ee.Filter.neq('NDI4_std', null)).filter(ee.Filter.neq('NDRI_std', null));




// Export
Export.table.toDrive({
  collection: stats,
  description: 'index_S2_con',
  fileFormat: 'CSV',
  folder: ''
}); 

Setting the scrollbar position of a block element in HTML

I want to set the scrollbar position of a block to specific coordinates when the page is loaded.

The closest thing I found to this is the

window.scrollTo

method in JavaScript, which sets the scrollbar positions of the horizontal and vertical scrollbars of the whole page in the browser. This script can then be run when the page is loaded.

I want to do the same with a block like this:

<div>
    <p> lots of text </p>
<div>
<style>
    div {
        overflow: scroll;  
}
</style>

Why toggle is not working if I don’t add CSS?

I am an absolute beginner. I am trying to do this project on animated search bar where it toggles between buttons.

Before adding CSS, I was trying to click on the icons to toggle but it didn’t work. Then I added CSS and it is working just fine. I thought CSS is for styling HTML documents.

What am I not understanding here? Does toggling work when 2 icons are together, overlapping or something. Can someone explain what is going on?

Code Snippet
(GitHub Source)

const searchBarContainerEl = document.querySelector(".search-bar-container");

const magnifierEl = document.querySelector(".magnifier");

magnifierEl.addEventListener("click", () => {
  searchBarContainerEl.classList.toggle("active");
});
body {
  margin: 0;
  display: flex;
  justify-content: center;
  height: 100vh;
  align-items: center;
  background-color: aliceblue;
}

.search-bar-container {
  display: flex;
  align-items: center;
  background-color: aliceblue;
  padding: 5px;
  width: 300px;
  height: 50px;
  border-radius: 50px;
  box-shadow: 6px 6px 10px rgba(0, 0, 0, 0.2), -6px -6px 10px rgba(255, 255, 255, 0.7);
  margin: 10px;
  position: relative;
  transition: width 1.5s;
}

.magnifier {
  width: 25px;
  cursor: pointer;
  position: absolute;
  left: 20px;
}

.mic-icon {
  width: 30px;
  position: absolute;
  right: 10px;
  transition: width 0.4s;
  transition-delay: 1s;
}

.input {
  background-color: transparent;
  border: none;
  margin: 10px 50px;
  width: 100%;
  outline: none;
  color: rgb(100, 100, 100);
  transition: width 1s;
  transition-delay: 0.5s;
}

.active.search-bar-container {
  width: 50px;
}

.active .input {
  width: 0;
}

.active .mic-icon {
  width: 0;
}
<div class="search-bar-container active">
  <img src="https://cdn4.iconfinder.com/data/icons/evil-icons-user-interface/64/magnifier-512.png" alt="magnifier" class="magnifier" />
  <input type="text" class="input" placeholder="Search ..." />
  <img src="https://cdn1.iconfinder.com/data/icons/google-s-logo/150/Google_Icons-25-512.png" alt="mic-icon" class="mic-icon" />
</div>

How can I handle async loading ‘on the fly’ in React?

I’m writing an app which is essentially in React (it’s part of a framework, but React is the basis). The app needs to load a list from an API, and then display all the items from that list to the user.

The user can select up to 3 items from the list. When an item is selected, I load more information about that item, and display that to the user.

The issue I have is that the additional information which needs to be loaded requires quite a bit of processing before it can be displayed, so I want to store the result each time (so that if the user selects, for instance, Item 1, Item 2 and Item 3, and then deselects Item 2, and then reselects Item 2, it doesn’t have to reload and process the info for Item 2 all over again).

I have the following:

function App() {
  const [allItems, setAllItems] = React.useState(null);  // Name and id of every item
  const [itemsShown, setItemsShown] = React.useState([]); // id of shown items
  const [itemsInfo, setItemsInfo] = {};  // Full details of items

  // Initialise by getting list of items
  React.useEffect(() => {
    const getAll = async () => {
      const res = await Api.getItems();
      setAllItems(res);
    };

    getAll();
  }, []);

  const loadItem = async (itemId) => {
      // If item is already loaded, return without doing anything
      if(itemsInfo[itemId]) return;

      // Load item details - this function also processes the data to get it into
      //  the correct format
      const details = await Api.getItem(itemId);

      // Now save the processed data
      setItemsInfo({...itemsInfo, [itemId] : details})
      
  }

  // Handle the user changing the selection of items
  // This goes through the selector, and checks whether each item is selected
  // Those items that are selected are added to the 'itemsShown' variable
  const handleChangeSelection = (e) => {
    const newShown = [];
    for (let ii = 0; ii < e.target.options.length; ii++) {
      if (e.target.options[ii].selected && newShown.length < MAX_SELECTED) {
        // This item is selected, so add its id to shown items list
        newShown.push(e.target.options[ii].value);

        // If we don't have the full details for this item yet, load it
        if(!itemsInfo[e.target.options[ii].value]) {
            loadItem(e.target.options[ii].value)
        }
      }
    }
    setItemsShown([...newShown]);
  };

  // DISPLAY

  // Show a selector with the list of items as options
  // Whenever the selection changes, handleChangeSelection is called
  // Underneath that, show details of the selected items
  return (
    <div>
      <Selector
         options={allItems}
         onChange={handleChangeSelection}
      />
        {itemsShown.map((item) => (
           <ShowItem
              key={item.id}
              item={itemsInfo[item.id] ? itemsInfo[item.id] : null}
           />
          )}
    </div>
  );
}

export default App;

What I’m aiming for here is that the page initially loads all available items, getting the id and name for each one and displays them in a selector. When the user selects one or more items in the selector, the handleChangeSelection function loops over the selector to see what’s currently selected, and adds the id of each selected item to itemsShown. It also checks that we’ve already pulled in the full details of that item by checking for the key in itemsInfo; if not, it loads those details. Once they’re loaded, it updates itemsInfo with the full details, which are arranged in itemsInfo by key, so it will look like this:

{ key1 : {... item 1 details}, key2 : {... item 2 details}, etc... }

Meanwhile, the render method goes through all the itemsShown; for each one, it instantiates the ShowItem component; if the item details are known then it passes them in; otherwise it passes in null.

The problem I have is that the time taken for items to load varies, and sometimes they overlap. So it might start to load Item 1, and then start to load Item 2. Then Item 1 completes, and it updates the itemsInfo state variable to add item 1 details; meanwhile, before that’s complete, Item 2 loads, and updates the original itemsInfo variable (without Item 1 in it, because that hasn’t updated yet) to add Item 2.

I’m not sure how to handle this, because I don’t know when the user is going to click on an item, or how quickly they’re going to click. Technically they could click on an Item and then unselect it, but I still want the item to load because it will have started anyway.

How do I get this to work?

How to Properly Pass the Filename in NestJS?

I’ve encountered an issue with the encoding of file names. The Cyrillic characters are getting lost.

I have an Expo application. I can send files when creating a certain item (see the function below):

export const updateTaskApi = async (
  id: string,
  taskData: TTask,
  files: TDataFilePicker[] | null,
) => {
  const headers = await createHeaders();
  headers['Content-Type'] = 'multipart/form-data';
  console.log('headers', headers);
  const formData = new FormData();
  formData.append('taskData', JSON.stringify(taskData));
  if (files) {
    files.forEach((file) => {
      console.log(file);
      formData.append(
        'files',
        {
          uri: file.filePickerUri,
          type: file.filePickerType,
          name: file.filePickerName,
          fileName: file.filePickerName,
        } as any,
      );
    });
  }
  console.log(formData);
  return await axios.put(`${basicUrl}/tasks`, formData, {
    withCredentials: true,
    headers,
  });
};

The files are sent to the backend, but when I decompose them there, instead of names like Аватар.jpg, I get just .jpg and sometimes with empty characters in front.

Here’s the controller:

@Put()
@HttpCode(HttpStatus.OK)
@UseInterceptors(FilesInterceptor('files'))
async updateTask(
  @Body() body: TaskFormData,
  @Req() request: Request,
  @UploadedFiles() files?: Array<Express.Multer.File>,
) {
  await verifyAuthorization(request);
  console.log('Request headers:', request.headers);
  if (!body.taskData) {
    throw new BadRequestException('Task object data is missing');
  }
  console.log('files from general', files);
  const updateTask = plainToInstance(TaskDto, JSON.parse(body.taskData));

  await this.tasksService.validateTaskPreparationData(updateTask);

  return await this.tasksService.updateTask(
    updateTask._id,
    updateTask,
    files,
  );
}

In the array of files, I see something like this:


files from general [
  {
    fieldname: 'files',
    originalname: '.jpg',
    encoding: '7bit',
    mimetype: 'image/jpeg',
    buffer: <Buffer ff d8 ff e2 0b f8 49 43 43 5f 50 52 4f 46 49 4c 45 00 01 01 00 00 0b e8 00 00 00 00 02 00 00 00 6d 6e 74 72 52 47 42 20 58 59 5a 20 07 d9 00 03 00 1b ... 72888 more bytes>,
    size: 72938
  }
]  

It turns out that the originalname field comes with an error and has lost the Cyrillic text. Meanwhile, globally, the only things that could affect the request before it reaches the controller are validation (ValidationPipe) and cookieParser. Nothing else. I’ve racked my brain and can’t figure out what’s happening with the encoding and where it disappears.

I’ve already checked all the documentation, tried to find similar issues from other people, and changed the ways of sending files several times. Nothing helped.