zTree to explore files

Is there an easy way to convert a list of files, with full path, into ztree nodes?

For example

Folder_1/Folder_1_1/File_1_1_a.txt
Folder_1/Folder_1_1/File_1_1_b.txt
Folder_1/Folder_1_1/Folder_1_1_1/File_1_1_1_a.txt
Folder_2/Folder_2_1/File_2_1_a.txt
Folder_2/Folder_2_1/File_2_1_b.txt

I want to convert into this

-Folder_1
    |-Folder_1_1
        |-File_1_1_a.txt
        |-File_1_1_b.txt
        |-Folder_1_1_1
            |-File_1_1_1_a.txt
-Folder_2
    |-Folder_2_1
        |-File_2_1_a.txt
        |-File_2_1_b.txt

Why do I receive a console error saying I need to define props even though they are defined in the parent and the child?

I am building a website using Vue JS 3 and Laravel and when I try and implement my Index.vue component I receive these errors:

[Vue warn]: Missing required prop: “label”
[Vue warn]: Missing required prop: “isDisabled”

I am pretty sure they are defined correctly in both the parent:

Vue.component('biometricos', {
  props: {
    label: {
      required: true,
      type: String,
      default: '',
    },
    className: {
      type: String
    },
    isDisabled: {
      required: true,
      type: Boolean,
      default: false
    },
    hours: Boolean,
    minutes: Boolean,
  }
});

and child:

props: {
  label: {
    required: true,
    type: String,
    default: '',
  },
  className: {
    type: String
  },
  isDisabled: {
    required: true,
    type: Boolean,
    default: false
  },
  hours: Boolean,
  minutes: Boolean,
},

It might make sense to declare a label like this

<Component label="YourLabelHere" isDisabled="false"></Component>

But I don’t ever call the component in this way. Plus I don’t think this should be necessary with all of my declarations anyways.

Any ideas on why this might be happening are much

How return false from with regex when string contains an empty space

I have been trying to get the following regex to return false if the string has an empty space for the past 3 days. I have read about 24 Stack Overflow postings among other web resources. I’ve take 3 tutorials.

I have been able to return true when there’s at least a number and a letter, and a string between 8 and 24 characters. I have not been able to return false when there is an empty space.

I know that [^S] is supposed to solve the issue, but I haven’t been able to get it to work.

Here’s my function.

      function validatePassword(password) {
         const pattern = /^(?=.*d)(?=.*[a-zA-Z])^(?=.*s+$).{8,24}$/;
         return pattern.test(password);
      }

      console.log(validatePassword("AlmostBald1 2"));

I have read about 24 Stack Overflow postings among other web resources. I’ve take 3 tutorials.

I have been able to return true when there’s at least a number and a letter, and a string between 8 and 24 characters. I have not been able to return false when there is an empty space.

I have tried adding this piece to my current regex pattern. Examples below:

const pattern = /^(?=.*d)(?=.*[a-zA-Z])^(?=.*s+$).{8,24}$/;
const pattern = /^(?=.*d)(?=.*[a-zA-Z])[^S].{8,24}$/;

I have read (to name a few):
https://regexone.com/lesson/excluding_characters
Detect if string contains any spaces
Regular expression for not allowing spaces in the input field
https://regex101.com/r/zG6Gbz/1
https://www.tutorialspoint.com/validating-a-password-using-javascript#:~:text=To%20validate%20a%20password%20using,the%20password%20matches%20the%20pattern.

Cascading dropdown in React

I’m developing a web app feature where the City dropdown values should filter based on the selected Province. The problem is that when a user selects a Province, the City dropdown jumps to the first city of that province, but still displays all cities, including those from other provinces. I want the City dropdown to only show cities belonging to the selected province. Check out the live codesandbox here. Filtering logic is in /src/components/shared/header > Header.tsx.

Header component (attempted filtering logic lives here):

export const Header = ({ data, isLoading, error }: HeaderProps) => {
  ...

  // Bring in global state
  const {
    provinceDropdownFilter,
    cityDropdownFilter,
  } = useFilterStore();

  const filteredData = data.map((group) => group.equipments).flat();

  ...

  const handleDropdownFilterProvince = (
    e: React.ChangeEvent<HTMLSelectElement>
  ) => {
    useFilterStore.setState({ provinceDropdownFilter: e.target.value });

    // Filter the data based on the selected province
    const filteredCities = filteredData
      .filter((item) => item.state === e.target.value)
      .map((item) => item.city);

    // Set the filtered city dropdown options
    useFilterStore.setState({ cityDropdownFilter: filteredCities[0] || "" });
  };

  const handleDropdownFilterCity = (
    e: React.ChangeEvent<HTMLSelectElement>
  ) => {
    useFilterStore.setState({ cityDropdownFilter: e.target.value });

    // Filter the data based on the selected city
    const filteredProvinces = filteredData
      .filter((item) => item.city === e.target.value)
      .map((item) => item.state);

    // Set the filtered province dropdown options
    useFilterStore.setState({
      provinceDropdownFilter: filteredProvinces[0] || "",
    });
  };

  ...

  return (
    <>
      ...
          <Dropdown
            data={data}
            value={provinceDropdownFilter}
            onChange={handleDropdownFilterProvince}
            filterType="state"
          />
          <Dropdown
            data={data}
            value={cityDropdownFilter}
            onChange={handleDropdownFilterCity}
            filterType="city"
          />
      ...
    </>
  );
};

Dropdown component:

export const Dropdown: React.FC<DropdownProps> = ({
  data,
  onChange,
  value,
  filterType,
}) => {
  ...

  // Map over the parent array as it has nested children arrays with all data containing.
  // Combine all chidren into one combined array
  const filteredData = data.map((group) => group.equipments).flat();

  // Filter the data based on the filterType
  const filteredOptions = filteredData.filter((i) => {
    if (filterType === "manufacturer") {
      return i.manufacturer;
    }
    if (filterType === "state") {
      return i.state;
    }
    if (filterType === "city") {
      return i.city;
    }

    return false;
  });

  ...

  return (
    <>
      <Select
        aria-label="Select"
        placeholder={getCustomPlaceholder(filterType) as string}
        value={value}
        onChange={handleFilters}
      >
        {Array.from(uniqueValues)
          .sort()
          .map((value) => (
            <option key={value} value={value}>
              {value}
            </option>
          ))}
      </Select>
    </>
  );
};

Creating and saving new tr elements with JS

I’m fairly new to coding, especially JS. I’m building a program meant to calculate input and put the result (along with the date) into a table. There should be a new entry in the table every time there is new input. Whenever the page is reloaded, the table’s data should be saved and retrieved.

The problem I’m having now is that only the first entry is saved. All the data in the table must be saved. Does anybody have a suggestion? Thanks.

Here’s my code:

// variables

const input = document.getElementById('input');

//buttons

const enter = document.getElementById('enter-value');
const log = document.getElementById("log-value");
const save = document.getElementById("save-value");
const done = document.getElementById("done-button");

//log areas

const itemHolder = document.getElementById('item-holder');
const totalMarker = document.getElementById("grand-total");

// messagges

const negativeValueMessage = document.getElementById('value-message-negative');
const positiveValueMessage = document.getElementById('value-message-positive');
const doneMessage = document.getElementById('done');

//other

const tool = document.getElementById('tool');
const date = new Date();

//input testing code

function checkInput (){
    input.addEventListener('input', function(){
        if(input.value < 0 ){
           negativeValueMessage.style.display = "block";
           positiveValueMessage.style.display = "none";
           enter.style.display = "block";
           enter.disabled = false;
           enter.style.opacity = "100%";
        }
        else if (input.value > 0) {
            negativeValueMessage.style.display = "none";
            positiveValueMessage.style.display = "block";
            enter.style.display = "block";
            enter.disabled = false;
            enter.style.opacity = "100%";
        }
        else {
            negativeValueMessage.style.display = "none";
            positiveValueMessage.style.display = "none";
            enter.disabled = true;
            if(enter.disabled){
                enter.style.opacity = '60%';
            }
        }
    });
}
checkInput();

// input reception

function useInput (){
    enter.addEventListener('click', function(){
        enter.style.display = 'none';
        log.style.display = 'block';
        inputDisalowed();
        log.addEventListener('click', function(){
            const addValues = Number(input.value) + Number(totalMarker.value);
            const total = addValues;
            totalMarker.value = total;
            function newInfo(){
                itemHolder.innerHTML += '<tr><td id="date">' + dateHolder + '</td><td id="amount">$' + totalMarker.value + '</td></tr>';
            }
            newInfo();
            log.style.display = 'none';
            save.style.display = 'block';
            save.addEventListener('click', function(){
                doneMessage.style.display = "grid";
                tool.style.display = 'none';
                const dateData = document.getElementById('date').innerText;
                const amountData = document.getElementById('amount').innerText;
                const dataArray = [dateData, amountData];
                localStorage.setItem('savedDate', (dataArray[0]));
                localStorage.setItem('savedAmount', dataArray[1]);
                localStorage.setItem('savedTotal', Number(totalMarker.value));
                done.addEventListener('click', function(){
                    reloadPage();
                });
            });
        });
    });
}
useInput();
retrieveOnReload();
const dateHolder = monthFixedValue() + '/' + date.getDate() + '/' + date.getFullYear();

function monthFixedValue (){
    return date.getMonth() + 1;
}
function inputDisalowed (){
    input.addEventListener('input', function(){
        alert("You have already input your value. Inputing again will always restart the proccess.");
        location.reload();
    });
}
function retrieveOnReload(){
    window.addEventListener('DOMContentLoaded', function(){
    const retrievedDate = localStorage.getItem('savedDate');
    const retrieveAmount = localStorage.getItem('savedAmount');
    itemHolder.innerHTML += '<tr><td id="date">' + retrievedDate + '</td><td id="amount">' + retrieveAmount + '</td></tr>';});
    totalMarker.value = Number(localStorage.getItem('savedTotal'));
};
function reloadPage() {
    window.location.href = window.location.href;
}
*{
    box-sizing: border-box;
    font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}
::-webkit-scrollbar{
    width:13px;
}
::-webkit-scrollbar-track{
    background: rgb(160,180,190);
    border-radius: 5px;
}
::-webkit-scrollbar-thumb{
    background: rgb(120,140,150);
    border-radius: 10px;
}
body {
    background-image: url(/Background.svg);
    display: grid;
    width: 100vw;
    justify-content: center;
    margin: 0;
    background-position: center;
    align-content: center;
    justify-items: center;
}
h1{
    border: 1px solid black;
    display: flex;
    justify-content: center;
    align-items: center;
    background-image: linear-gradient(
        rgb(150,170,180),
        rgb(120,140,150)
    );
    border-radius: .5vw;
    margin-bottom: 10px;
    width: 80vw;
    height: 70px;
    min-width: 400px;
    font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
    color: rgb(20,20,90);
    font-size: 40px;
    border: none;
    margin-top: -150px;
    margin-left: -20px;
}
main{
    display: grid;
    align-items: center;
    justify-items: center;
    background: linear-gradient(
        rgb(150,170,180) 20%,
        rgb(120,140,150) 
    );
    border-radius: .5vw;
    margin-top: 10px;
    padding: 20px;
    width: 80vw;
    min-width: 400px;;
}
.inputs {
    margin: 20px;
    width: 90%;
    display: flex;
    justify-content: center;
}
input {
    border: none;
    background-color: rgb(30,90,130);
    color: rgb(10,10,50);
    height: 35px;
    width: 220px;
    font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
    font-size: 15px;
    border-bottom: 2px solid rgb(20,80,100);
    border-radius: .2vw;
    margin-right: 3px;
    &::placeholder{
        color: rgb(100,140,180);
        font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
        font-size: 15px;
        font-weight: 900;
    }
}
#enter-value, #save-value, #log-value{
    border: none;
    border-radius: .2vw;
    background: rgb(20,80,180);
    font-size: 20px;
    font-weight: bolder;
    color: rgb(10,10,50);
    margin-left: 3px;
    &:hover{
        background: rgb(10,70,170);
    }
    &:active{
        background: rgb(20,80,180);
    }
}
#enter-value{
    display: none;
}
#save-value{
    display: none;
}
#log-value{
    display: none;
}
.value-message{
    color: rgb(30,40,100);
    display: none;
    margin-bottom: -20px;
}
label{
    text-align: center;
    font-weight: bolder;
    display: flex;
    align-items: baseline;
    font-size: 35px;
    
}
#grand-total{
    height: 40px;
    width: 150px;
    margin-bottom: 30px;
    margin-top: 0px;
    background: rgb(10,10,100);
    color: rgb(150,170,180);
    display: grid;
    align-content: center;
    text-align: center;
    font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
    border-radius: 2px;
    font-weight: bolder;
    font-size: 35px;
}
.table-window{
    height: 100px;
    width: 100%;
    display: grid;
    justify-items: center;
    align-items: center;
    overflow-y: scroll;
}
table{
    background-color: rgb(60,120,160);
    border-style: none;
    border-collapse: collapse;
}
.heading-row{
    background: rgb(100,160,200);
    height: 40px;
    width: 750px;
}
th{
    border: 0;
    width: 170px;
}
td{
    text-align: center;
    padding: 4px;
    width: 170px;
}
.th1,
.th2,
.th3{
    border-right: 2px solid rgb(170,170,255);
}
.td1,
.td2,
.td3{
    border-right: 2px solid rgb(170,170,255);
}
#done{
    position: absolute;
    display: grid;
    justify-items: center;
    display: none;
}
#done-img-holder{
    display: flex;
    justify-content: center;
    align-content: center;
    width: 100%;
    height: 100%;
}
#done-img-holder > img{
    width: 490px;
    display: grid;
    margin-top: -30px;
}
#done-info-holder{
    display: grid;
    justify-items: center;
    width: 400px;
    height: 170px;
    background: linear-gradient(
        rgb(180,180,190),
        rgb(140,140,150)
    );
    align-content: center;
    border-radius: .5vw;
}
#done-info-holder > p{
    font-size: 20px;
    color: rgb(10,70,160);
    font-weight: 900;
}
#done-info-holder > button{
    height: 50px;
    width: 130px;
    font-size: 30px;
    font-weight: 900;
    background: rgb(10,10,100);
    border: none;
    border-radius: 30px;
    color: rgb(120,140,150);
    &:hover{
        background: rgb(120,140,150);
        color: rgb(10,10,100);
    }
    &:active{
        background: rgb(10,10,100);
        color: rgb(120,140,150);
    }
}
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="veiwport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="FinanceTool.css">
    <title>Finance_Tool</title>
</head>
<body>
    <main id="tool">
            <h1 class="heading">Simple Finance Tool</h1>
        <p id="value-message-negative" class="value-message">Your number is negative. This will be calculated as a financial loss.</p>
        <p id="value-message-positive" class="value-message">Your number is positive. This will be calculated as a financial gain.</p>
        <div class="inputs">
            <input type='number' id="input" class="input" placeholder="Input financial loss or gain." min="0"/>
            <button type="button" id="enter-value">Enter</button>
            <button type="button" id="log-value">Log Change</button>
            <button type="button" id="save-value">Save Change</button>
        </div>
        <label for="grand-total">$<input id="grand-total" disabled/></label>
        <div class="table-window">
            <table id="item-holder">
                <tr class="heading-row">
                    <th class="th1">Date</th>
                    <th class="th4">Total After Change</th>
                </tr>
            </table>
            
            
        </div>
        
    </main>
    <div id="done">
        <div id="done-img-holder">
            <img src="/Finance Tool/check-circle-svgrepo-com.svg"/>
        </div>
        <div id="done-info-holder">
            <p>All done! You're entry is complete.</p>
            <button id="done-button">Done</button>
        </div>
    </div>
    <script src="FinanceTool.js"></script>
</body>
</html>

Also here’s a link to the code in codePen(note: due to a peculiarity of codePen, the code will not work properly in it, but you can copy it from codePen to your IDE).

codePenProjectLink

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: ''
});