How do i make my Javascript/html form processing print out?

Im writing a peice of code for a school project, I took code from a form i wrote for myself last year (that worked) and just wrewrote the questions and variable names. But now the processed data is not printing and i get this error :

Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')
    at showQuestions (script.js:139:29)
    at generateQuiz (script.js:204:3)
    at window.onload (script.js:6:2)

here is the code for my form page:

<!DOCTYPE HTML >
<html>
   <head>
      <title>Review!</title>
      <link rel= "stylesheet" type= "text/css" href= "style.css">
      <!--Links to the stylesheet-->
      <link rel="icon" type="image/x-icon" href="coolfavicon.png">
      <!--favicon, puts an icon on the head instead of the default-->
      <script src="script.js"></script>
      <meta charset="UTF-8">
   </head>
   <body>
      <div class="navbar">
         <a href="index.htm">Home</a>
         <a href="info.htm">Information</a> <!--navigaion bar to access all pages-->
         <a href="quiz.htm">Quiz!</a>
         <div class="dropdown">
            <button class="dropbtn">
               More information ▼<!--dropdown tag for different information pages-->
            </button>
            <div class="dropdown-content">
               <a href="history.htm">History of cars</a>
               <a href="Records.htm">Car world records</a>
               <a href="Purchase.htm">How to buy a car</a> 
            </div>
         </div>
         <div class ="countdown">
            <p>Coundown to Auckland Christmas car meet: <span id="demo" style="align:right"      ></span></p>
            <!--script countdown timer-->
         </div>
      </div>
      <div class="hero-image-info">
         <div class="hero-text">
           <u>Please fill out this form:</u>
           <br>
           <div class="funnydiv">
            <u>Rutherford College e-sports signup</u>
            <br>
            <br>
            </div>
            <form method="get" action   ="process.htm">
            <u><label for ="name">What is your name?</label><br></u>
            <input type="text" id="name" name="name" required placeholder="Name"><br><!--text input tags for Name-->
            <br>
            <u><label for ="email">What is your email adress?</label><br></u>
            <input type="text" size="20" id="email" name="email" required placeholder="email" ><br><!--text input tags for Email-->
            <br>
            <u><label for="outof5">Out of 5, How would you rate this website overall?</label><br></u>
            <br>
            <input type="radio" id="1" name="outof5" required value="1"> <span>1</span> 
            <br>
            <input type="radio" id="2" name="outof5" required value="2"> <span>2</span> <!--input tags for review-->
            <br>
            <input type="radio" id="3" name="outof5" required value="3"> <span>3</span> 
            <br>
            <input type="radio" id="4" name="outof5" required value="4"> <span>4</span> 
            <br>
            <input type="radio" id="5" name="outof5" required value="5"> <span>5</span> 
            <br>
            <u><label for="page">Personally, what was your favorite page on our website?</label><br></u>
            <br>
            <input type="radio" id="Home" name="page" required value="Home"><span>Home</span> 
            <br>
            <input type="radio" id="Information" name="page" required value="Information"><span>Information</span> 
            <br>
            <input type="radio" id="Records" name="page" required value="Records"><span>Records</span> 
            <br>
            <input type="radio" id="History" name="page" required value="History"><span>History</span><!--input tags for year at school-->
            <br>
            <input type="radio" id="Quiz" name="page" required value="Quiz"><span>Quiz</span>
            <br>
            <input type="radio" id="Purchasing" name="page" required value="Purchasing"><span>Purchasing</span>
            <br>
            <br>
            <u><label for="score">What did you score on our quiz?</label><br></u>
            <br>
            <input type="radio" id="0-4 (extremely low)" name="score" value="0-4 (extremely low)"> <span>0-4 (extremely low)</span>
            <br>
            <input type="radio" id="5-7 (low)" name="score" required value="5-7 (low)"> <span>5-7 (low)</span>
            <br>
            <input type="radio" id="8-10(medium)" name="score" required value="8-10(medium)"> <span>8-10(medium)</span><!--input tags for experience in said game-->
            <br>
            <input type="radio" id="11-13(high)" name="score" required value="11-13(high)"> <span>11-13(high)</span>
            <br>
            <input type="radio" id="14-15(very high)" name="score" required value="14-15(very high)"> <span>14-15(very high)</span>
            <br>
            <br>
            <input type="submit" name="submit" value="Submit" class="button"/>
            </form>
            
            <a class = "button" onclick="topFunction()" id="totopbutton" title="Go to top">Back to top</a> 
         </div>
         <div class ="footer">
            <p><a href="privacy.htm">‏‏‎ ‎‎‎‎‎‎‎Privacy Policy</a>‏‏‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‎Phone:0800 838 828‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎Email:[email protected]</p>         </div>
         <br>
      </div>
   </body>
</html> 

Here is the processing page:

<!DOCTYPE HTML >
<html>
   <head>
      <title>Information</title>
      <link rel= "stylesheet" type= "text/css" href= "style.css">
      <!--Links to the stylesheet-->
      <link rel="icon" type="image/x-icon" href="coolfavicon.png">
      <!--favicon, puts an icon on the head instead of the default-->
      <script src="script.js"></script>
      <meta charset="UTF-8">
   </head>
   <body>
      <div class="navbar">
         <a href="index.htm">Home</a>
         <a href="info.htm">Information</a> <!--navigaion bar to access all pages-->
         <a href="quiz.htm">Quiz!</a>
         <div class="dropdown">
            <button class="dropbtn">
               More information ▼<!--dropdown tag for different information pages-->
            </button>
            <div class="dropdown-content">
               <a href="history.htm">History of cars</a>
               <a href="Records.htm">Car world records</a>
               <a href="Purchase.htm">How to buy a car</a> 
            </div>
         </div>
         <div class ="countdown">
            <p>Coundown to Auckland Christmas car meet: <span id="demo" style="align:right"      ></span></p>
            <!--script countdown timer-->
         </div>
      </div>
      <div class="hero-image-index">
         <div class="hero-text">
                <br><br>
         <br><br><br><br>
                </p>processed data:</p>
                Your Name: <span id="name"></span>
                <br>
                Your email: <span id="email"></span>   <!--these lines print the variables that would have been entered on the previous form page-->
                <br>
                Website rating out of 5: <span id="outof5"></span>
                <br>
                Favorite page: <span id="page"></span>
                <br>
                Quiz score: <span id="score"></span>
                <br>
            <!--basic content-->
            <p>We hope you enjoy playing with us!</p>
            <a class = "button" onclick="topFunction()" id="totopbutton" title="Go to top">Back to top</a> 
         </div>
         <br>
         <br><br>
         <div class ="footer">
            <p><a href="privacy.htm">‏‏‎ ‎‎‎‎‎‎‎Privacy Policy</a>‏‏‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‎Phone:0800 838 828‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎Email:[email protected]</p>         </div>
         <br>
      </div>
   </body>
</html> 

And here is the javascript:

window.onload = function(){
    var quizContainer = document.getElementById('quiz');
    var resultsContainer = document.getElementById('results');
    var submitButton = document.getElementById('submit');

    generateQuiz(myQuestions, quizContainer, resultsContainer, submitButton);
    
    url = window.location.href;
    console.log(url)
    if( url.indexOf("privacy")> 0){
        showSlides();
    } 
    if(url.indexOf("process")> 0){
        processForm();
    }
    console.log(url)
    //helps to run javascript where it is needed (slides and processing)
}

//PROCESSING AND form

function processForm(){
    //getname
    value = get_url_parameter("name");
    document.getElementById("name").innerHTML = value;
    //getemail
    value = get_url_parameter("email");
    document.getElementById("email").innerHTML = value;
    //getoutof5
    value = get_url_parameter("outof5");
    document.getElementById("outof5").innerHTML = value;
    //getpage
    value = get_url_parameter("page");
    document.getElementById("page").innerHTML = value;
    //getscore
    value = get_url_parameter("score");
    document.getElementById("score").innerHTML = value;
    
}
var url_string = window.location.href;

function get_url_parameter(parameter) {
    //get the passed url string
    var url_string = window.location.href;
    //split at the question mark in the url vor values passed
    var all_parts = url_string.split("?");
    //split the second part into the passed perameters
    var passed_values = all_parts[1].split("&");
    //return array for radio buttons
    var return_array = []
    //cycle through all passed values
    for (i=0;i<passed_values.length;i++){
        section_parts = passed_values[i].split("=")
        //match the first part of the url with the passed perimiter
        if (parameter == section_parts[0]){
            //put it into our array
            return_array.push(section_parts[1])
        }
    }
    //return array
    return return_array;
}

Ive checked all of the variables, and it looks exactly the same as my working code (apart from variable names) and im very confused as to why it is not printing out the processed information.

This is what i see on the processing page

This is the working view from last year

Trouble setting up eslint_d in neovim for Javascript projects

So I’ve had my lsp setup with neovim for a minute now, but I’ve just started working on a javascript project and I realize I have no idea how to setup eslint_d. I’ve scoured the internet for answers but I haven’t really seen anything that’s a “eslint for dummies” type of deal.

I use Mason along with nvim-lspconfig and nvim-lint mainly to do my language server stuff and linting.

What I’m confused about is, if I have eslint_d installed through Mason, do I still need to run an ‘npm init’ command in my directory? Or ‘npm i eslint’ or something like that? I had it linting properly before, except for the fact that it wouldn’t read custom types. I have a types folder in my working directory that’s symlinked to a types folder outside, and in my tsconfig.json I have “./types” in my typeRoots, yet it says these types are undefined and undeclared. Listing them as readonly globals does nothing as well.

Could someone just give me the step by step on how I’m supposed to set up projects using eslint_d through Mason?

is there a way to add the video the static page in tauri application?

when i try to load a video from the video tag in html it works in the dev but not in build in tauri app
enter image description here
this is the image of the file tree
now the code that load the video

<video
    src="./assets/video/textify.mp4"
    id="video"
    muted
    autoplay
></video>

when i try google it its says that i need to add the location of the video to the resource in the tauri.config.json i did that but it did not work

How to disable the “Upload Image” button in unlayer using vue-email-editor?

I’m using vue-email-editor (a Vue wrapper for unlayer) to integrate an email editor in my Vue 3 project. Everything works fine, but I want to disable the “Upload Image” button that allows users to upload their own images. I’ve been unable to find a solution in the documentation or source code.

Here’s my current setup:
I’ve initialized the editor with the following configuration:

<template>
  <div>
    <EmailEditor
      ref="emailEditor"
      :appearance="emailEditorConfits.appearance"
      :options="emailEditorConfits.options"
      :tools="emailEditorConfits.tools"
      :project-id="emailEditorConfits.projectId"
      @ready="editorLoaded"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { EmailEditor } from 'vue-email-editor';

const emailEditor = ref(null);

const emailEditorConfits = {
  appearance: {
    panels: {
      tools: { dock: 'right' }
    }
  },
  options: {
    features: {
      userUploads: false,
    },
    imageUploader: {
      shouldRender: {
        dropzone: false,         // Disable dropzone for image uploads
        uploadButton: false,     // Disable the upload button
        userUploads: true,       // Keep user uploaded images visible
        stockImages: true,       // Enable stock images
        moreImages: true,        // Enable more images
      },
    },
  },
  tools: {},
  projectId: <abc-123>,
};

const editorLoaded = () => {
  emailEditor.value.registerProvider('userUploads', function (params, done) {
    const images = [
      {
        id: Date.now(),
        location: 'https://picsum.photos/id/1/500',
        width: 500,
        height: 500,
        contentType: 'image/png',
        source: 'user'
      }
    ];
    done(images);
  });
};
</script>

What I’ve Tried:

  1. I’ve attempted to disable the “Upload Image” button by setting shouldRender.uploadButton and shouldRender.dropzone to false within the imageUploader configuration, but the button and dropzone are still visible.
  2. I’ve looked through the unlayer documentation and vue-email-editor issues but haven’t found a way to specifically disable the “Upload Image” button.
  3. I’ve checked the node_modules code of ImageUploader, and the relevant part seems to allow customization through shouldRender, but it doesn’t seem to work as expected.

Question:

How can I disable the “Upload Image” button in unlayer when using the vue-email-editor package? Is there any way to fully hide this button or the entire user-upload option?

I appreciate any guidance or examples on how to achieve this!

Add dynamic styles to AG Grid row groups

I’m having trouble adding dynamic styles to row groups on an AG Grid table because I need each row group to have its own custom background color in hex that comes from an API.

I’ve tried using AG Grid’s autoGroupColumnDef with cellStyle, but since AG Grid only stores the value that will be displayed, I can’t access it.

To illustrate what I want, I made a drawing.
Image

Here is my code:

var levels = "";

if (data != null && data != undefined && data.d != '[]') {
    levels = JSON.parse(data.d)[0].levels;
}

var columnDefs = [{
        headerName: "CT1",
        field: "category1",
        rowGroup: true,
        filter: true,
        rowGroupIndex: 1,
        hide: true
    },
    {
        headerName: "CT2",
        field: "category2",
        rowGroup: true,
        filter: true,
        rowGroupIndex: 2,
        hide: true
    },
    {
        headerName: "CT3",
        field: "category3",
        rowGroup: true,
        filter: true,
        rowGroupIndex: 3,
        hide: true
    },
    {
        headerName: "CT4",
        field: "category4",
        rowGroup: true,
        filter: true,
        rowGroupIndex: 4,
        hide: true
    },
    {
        headerName: "CT5",
        field: "category5",
        rowGroup: true,
        filter: true,
        rowGroupIndex: 5,
        hide: true
    },
    {
        headerName: "CT6",
        field: "category6",
        rowGroup: true,
        filter: true,
        rowGroupIndex: 6,
        hide: true
    },
    {
        headerName: "CT7",
        field: "category7",
        rowGroup: true,
        filter: true,
        rowGroupIndex: 7,
        hide: true
    },
    {
        headerName: "CT8",
        field: "category8",
        rowGroup: true,
        filter: true,
        rowGroupIndex: 8,
        hide: true
    },
    {
        headerName: "CT9",
        field: "category9",
        rowGroup: true,
        filter: true,
        rowGroupIndex: 9,
        hide: true
    },
    {
        headerName: "CT10",
        field: "category10",
        rowGroup: true,
        filter: true,
        rowGroupIndex: 10,
        hide: true
    },
    {
        headerName: "C",
        field: "descriptionC",
        rowGroup: true,
        filter: true,
        rowGroupIndex: 11,
        hide: true
    },
    {
        headerName: "C",
        field: "descriptionC",
        rowGroup: true,
        filter: true,
        hide: true
    },
    {
        headerName: "color1",
        field: "color1",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "color2",
        field: "color2",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "color3",
        field: "color3",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "color4",
        field: "color4",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "color4",
        field: "color5",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "color6",
        field: "color6",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "color7",
        field: "color7",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "color8",
        field: "color8",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "color9",
        field: "color9",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "color10",
        field: "color10",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "ID1",
        field: "idCategory1",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "ID2",
        field: "idCategory2",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "ID3",
        field: "idCategory3",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "ID4",
        field: "idCategory4",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "ID4",
        field: "idCategory5",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "ID6",
        field: "idCategory6",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "ID7",
        field: "idCategory7",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "ID8",
        field: "idCategory8",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "ID9",
        field: "idCategory9",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "ID10",
        field: "idCategory10",
        aggFunc: "avg",
        hide: true
    },
    {
        headerName: "",
        field: "edit",
        width: 50,
        cellClass: 'text-center',
        sortable: true,
        hide: masterOnlyView == "1",
        cellClassRules: {
            "gridIconEdit": function(params) {
                return params.node.key != null && params.node.field != "descricaoCIP"
            },
            "text-center": function(params) {
                return params.node.key == null || params.node.field == "descricaoCIP"
            }
        }
    }
];
var obj = JSON.parse(data.d);

var gridOptions = {
    columnDefs: columnDefs,
    singleClickEdit: true,
    stopEditingWhenCellsLoseFocus: true,
    rowSelection: 'multiple',
    groupDefaultExpanded: levels - 1,
    animateRows: true,
    rowData: obj,
    defaultColDef: {
        filter: true,
    },
    autoGroupColumnDef: {
        pinned: 'left',
        minWidth: 1000,
        headerName: lblColunaDescricao,
        cellStyle: (cell) => {
            if (cell.node.field != "descricaoCIP") {
                return {
                    backgroundColor: 'green'
                }
            }
        },
        cellClassRules: {
            "cell-blue": function(params) {
                return params.node.field == "descricaoCIP"
            },
            "total-cell-left-no-bg": function(params) {
                return params.node.field != "descricaoCIP"
            }
        }
    },
};
var eGridDiv = document.querySelector('#myGrid');
eGridDiv.innerHTML = "";

let gridElement = new agGrid.Grid(eGridDiv, gridOptions);
fnGlobalSetGridOptions(gridElement, {
    gridOptions
});

The API return has a structure like this for each value, and then it is grouped by AG Grid:

{
    category1: "1. CATEG",
    category2: "1.1. SUB CATEG",
    category3: "1.1.1. SUB SUB CATEG FV",
    category4: null,
    category5: null,
    category6: null,
    category7: null,
    category8: null,
    category9: null,
    category10: null,
    codeC: "FV01.01.02",
    color1: "#1cd1d4",
    color2: "#e83030",
    color3: "#FFFFFF",
    color4: null,
    color5: null,
    color6: null,
    color7: null,
    color8: null,
    color9: null,
    color10: null,
    descriptionC: "FV01.01.02",
    idC: 13161,
    idCategory1: 49,
    idCategory2: 50,
    idCategory3: 52,
    idCategory4: 0,
    idCategory5: 0,
    idCategory6: 0,
    idCategory7: 0,
    idCategory8: 0,
    idCategory9: 0,
    idCategory10: 0,
    levels: 3
}

Can anyone help?

How to await reactions.cache.forEach in Discord.js v14 [duplicate]

My discord bot checks reactions of a discord message and after it processed info about all reactions and its users, it sends relevant info. How to make it so that console.log(‘after’) happens after every reaction has been processed? (Discord.js v14)

const messageReacted = await reaction.client.channels.cache.get(reaction.message.channelId).messages.fetch(reaction.message.id);

await messageReacted.reactions.cache.forEach(async(msg_reaction) => {
    const emojiName = msg_reaction._emoji.name
    const reactionUsers = await msg_reaction.users.fetch();
    let user_list = [];

    reactionUsers.forEach(user => {
        if(user.bot === false) {
            user_list.push(`<@${user.id}>`);
        }
    });

    /* Doing Stuff */
});


console.log('after');

DropZone – Replace / in dropped filename

Uploads with a slash in the filename are problematic in a number of ways. I need to change the / to a space, or eliminate it altogether.

This would be the most obvious, and it works for any other characters I’ve tested with, but the / always gets through.

renameFile: function(file) {
            return file.renameFile =file.name.replace("/","");
        }

I’ve tried escaping it with “/” quoted and unquoted plus several other variations. The slash always comes though.

Firebase Sign-In/Sign-Up Issues

I am trying to set up sign up and login functionality to my website but I am having some issues. I am running the website in live browser from vs code. I can see the email accounts that have been created within my firebase console. However, when I try to login to an account using on of those accounts on the website, it says that no account exists. If I then try to sign up using the same email, it says the account already exists. Im pretty new to this so the problem may be obvious but I cant seem to figure it out.

loginButton.addEventListener('click', () => {
    authMenu.style.display = 'flex';
    createAccountMenu.style.display = 'none'; 
});

createAccountButton.addEventListener('click', () => {
    authMenu.style.display = 'none';
    createAccountMenu.style.display = 'flex';
});

backToLoginButton.addEventListener('click', () => {
    authMenu.style.display = 'flex';
    createAccountMenu.style.display = 'none';
});

authActionButton.addEventListener('click', async (event) => {
    event.preventDefault();

    const email = emailField.value;
    const password = passwordField.value;

    if (!email) {
        messageElement.textContent = 'Please enter your email.';
        return;
    }

    if (!password) {
        messageElement.textContent = 'Please enter your password.';
        return;
    }

    try {
        const methods = await fetchSignInMethodsForEmail(auth, email);

        if (methods.length === 0) {
            messageElement.textContent = 'Email is not registered. Please create an account.';
            return;
        }

        await signInWithEmailAndPassword(auth, email, password);
        messageElement.textContent = 'Signed in successfully!';
        authMenu.style.display = 'none';
    } catch (error) {
        messageElement.textContent = `Error: ${error.message}`;
    }
});

createAccountActionButton.addEventListener('click', async (event) => {
    event.preventDefault();

    const email = createEmailField.value;
    const password = createPasswordField.value;

    if (!email) {
        createAccountMessageElement.textContent = 'Please enter your email.';
        return;
    }

    if (!password) {
        createAccountMessageElement.textContent = 'Please enter your password.';
        return;
    }

    try {
        await createUserWithEmailAndPassword(auth, email, password);
        createAccountMessageElement.textContent = 'Account created successfully!';
        createAccountMenu.style.display = 'none';
    } catch (error) {
        createAccountMessageElement.textContent = `Error: ${error.message}`;
    }
});

I’m also not sure what other details you may need to help so if theres anything else please just let me know.

I’m looking for a sortable drag-and-drop tutorial using only vanilla JavaScript and no HTML5. The other questions I’ve seen link to outdated sites

I’m working within a very limited LMS that does not allow the HTML5 draggable property, and also does not allow JQuery. It’s nearly impossible to find a tutorial that doesn’t use draggable, and I want to learn the technique so that I can debug more effectively. The best answer will have two columns where an element on the left is paired with a specific drop-zone on the right.

I’m an intermediate vanilla JS user, if that’s relevant. I can upload a single JS file, not multiples.

I’ve spent hours looking for code that doesn’t use HTML5. The duplicate questions on Stack Exchange are all pretty old and refer to outdated links, which is why I’m asking again. Thanks in advance!

Optimizing a complex Google Sheets script for faster execution

I have a complex script that currently takes about 32 seconds to run. It handles various operations in Google Sheets, including updating multiple sheets based on user edits, applying formulas, and managing data validation rules.
The script includes functions like:
updateQuoteDetail,
updateQuoteSummary,
copyAllQuoteData,
hideOrShowSpecificSheets,

I’m looking for advice on how to optimize this script to reduce its execution time.

I’m open to restructuring the code if it leads to significant performance improvements. Any insights or suggestions would be greatly appreciated!
Thank you in advance for your help!”
This message outlines your current situation, specifies what kind of help you’re looking for, and invites the community to share their expertise. It should encourage knowledgeable members to offer their insights on optimizing Google Apps Script performance.

Best Regards,
Saher

This is the script:
Dropbox>txt.file

What I Tried:

  • Script Optimization: I attempted to optimize my Google Sheets script for performance.
  • Deleting Rows: I deleted every row in Google Sheets after row 80, hoping to reduce processing time, but this did not yield significant results.
  • Adjusting Ranges: I changed the ranges from “B14:R122” and “B14:R” to “B14:R80” to limit the data being processed, but this only provided a minor improvement.
  • Deleting Sheets: I removed some sheets.
  • Results: All these actions only reduced the execution time from 32 seconds to 25 seconds.

What I Expected:
I expected the script to finish running in about 5 seconds.

Actual Outcome:
The script currently takes 25 seconds to complete, which is still longer than desired.

How to convert this “string” to a correct date?

Struggling to display a date in javascript that is retrieved from a postgres database and returned via python.

When I simply console.log the variable I get back from my GET request, it is in this format:

Thu, 12 Sep 2024 00:00:00 GMT

I’m simply attempting to display that as:

09/12/24

(I don’t know where the 00:00:00 GMT portion is coming from, but essentially I just want to discard that. It seems to be affecting my conversions for some reason.)

I AM using moment.js, but have not been able to get it to display the correct date. It always displays 1 day prior (9/11/24).

What would be the easiest method to simply display that returned datetime string as “09/12/24” (the time portion will never need to be accounted for)?

I want to make a JavaScript hue inverter (add or subtract 180°), but it isn’t working. How can I fix this?

In case you don’t know, a hue inverter takes a value between 0 and 360, adds 180 if the input is less than or equal to 180, and subtracts 180 if the input is greater than 180. I added some JavaScript to do that operation, but it isn’t working.

Here is the UI (there is no CSS yet): Click to see the image.

function invertHue() {
  const inputHue = Number(document.getElementById("hue-i").value);
  const outputHue = document.getElementById("hue-o").textContent;
  var result;

  try {
    if (inputHue <= 180 && inputHue > 0) {
      result = inputHue + 180;
      outputHue = result;
    } else if (inputHue > 180 && inputHue <= 360) {
      result = inputHue - 180;
      outputHue = result;
    } else {
      window.alert("The hue must be between 0 and 360.");
    }
  } catch (error) {
    window.alert("There was an issue.");
  }
}
<div class="input">
  <input type="text" id="hue-i" placeholder="Enter hue here...">
  <button id="invert-btn" onclick="invertHue()">Invert</button>
</div>
<div class="output">
  <p id="hue-o">Inverted hue will appear here...</p>
</div>

What is going wrong in the code?

(p.s. I am using VS Code for my editor.)

PHP script returns empty JSON on cloud server but works locally – How to debug?

I’m encountering an issue with my PHP script (obtener_rutas.php) that’s supposed to return JSON data for a routes application. The script works perfectly on my local server (XAMPP), but when deployed to my cloud server, it returns an empty JSON response.

Local server (works correctly):

  • The script returns the expected JSON data with route information.

Cloud server (problem):

  • The PHP script returns an empty JSON response: []

Here’s my obtener_rutas.php script:

<?php
ob_start();

function debug_log($message) {
    file_put_contents('debug.log', date('[Y-m-d H:i:s] ') . $message . "n", FILE_APPEND);
}

debug_log("Script started");
debug_log("SERVER: " . print_r($_SERVER, true));

error_reporting(E_ALL);
ini_set('display_errors', 0);
header('Content-Type: application/json');

function handleError($errno, $errstr, $errfile, $errline) {
    $error = array(
        'error' => 'PHP Error',
        'message' => $errstr,
        'file' => $errfile,
        'line' => $errline
    );
    debug_log("Error occurred: " . json_encode($error));
    echo json_encode($error);
    exit;
}

set_error_handler('handleError');

try {
    debug_log("About to require connection files");
    require_once '../../inicio_sesion/conexion.php';
    require_once '../../inicio_sesion/config.php';  
    debug_log("Connection files included");

    if (!$conn) {
        throw new Exception('Database connection error');
    }
    debug_log("Database connection successful");

    $id = isset($_GET['id']) ? filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT) : null;

    function getImageUrl($baseUrl, $path) {
        return $baseUrl . '/paginasespecializadas/skitouring/' . $path;
    }

    debug_log("About to execute query");

    if ($id) {
        
        $query = "SELECT r.*, 
                         GROUP_CONCAT(DISTINCT ri.imagen_path) as imagenes,
                         rp.view_count, rp.download_count, rp.favorite_count, rp.complete_count, rp.popularity_score
                  FROM rutas r
                  LEFT JOIN ruta_imagenes ri ON r.id = ri.ruta_id
                  LEFT JOIN route_popularity rp ON r.id = rp.route_id
                  WHERE r.id = ?
                  GROUP BY r.id";
        
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 0) {
            throw new Exception('Route not found');
        }

        $ruta = $result->fetch_assoc();
        $ruta['imagenes'] = $ruta['imagenes'] ? explode(',', $ruta['imagenes']) : [];
        
        // Update image paths with BASE_URL and correct folder structure
        $ruta['imagenes'] = array_map(function($path) {
            return getImageUrl(BASE_URL, $path);
        }, $ruta['imagenes']);
        
        debug_log("Single route processed");
        echo json_encode($ruta);
    } else {
        
        $query = "SELECT r.*, 
                         GROUP_CONCAT(DISTINCT ri.imagen_path) as imagenes,
                         rp.view_count, rp.download_count, rp.favorite_count, rp.complete_count, rp.popularity_score
                  FROM rutas r
                  LEFT JOIN ruta_imagenes ri ON r.id = ri.ruta_id
                  LEFT JOIN route_popularity rp ON r.id = rp.route_id
                  GROUP BY r.id
                  ORDER BY rp.popularity_score DESC";  // Order by popularity

        debug_log("Executing all routes query");
        $result = $conn->query($query);
        debug_log("All routes query executed");

        if (!$result) {
            throw new Exception('Query error: ' . $conn->error);
        }

        $rutas = [];
        while ($row = $result->fetch_assoc()) {
            $row['imagenes'] = $row['imagenes'] ? explode(',', $row['imagenes']) : [];
            
            
            $row['imagenes'] = array_map(function($path) {
                return getImageUrl(BASE_URL, $path);
            }, $row['imagenes']);
            
            $rutas[] = $row;
        }

        debug_log("Number of routes fetched: " . count($rutas));
        echo json_encode($rutas);
    }

    debug_log("Query results processed and sent");

} catch (Exception $e) {
    http_response_code(500);
    $error = ['error' => $e->getMessage()];
    debug_log("Exception caught: " . json_encode($error));
    echo json_encode($error);
} finally {
    if (isset($stmt)) {
        $stmt->close();
    }
    if (isset($conn) && $conn instanceof mysqli) {
        $conn->close();
    }
    debug_log("Script ended");
}
?>

I’ve implemented logging to a debug.log file, but I’m not seeing any error messages or exceptions in the log on the cloud server.
What I’ve tried:

Checking the debug.log file for any error messages.
Verifying that the database connection details are correct for the cloud environment.
Ensuring that the file paths for conexion.php and config.php are correct on the cloud server.

Using react and useState is it possible to randomly decrement multiple instances of one component?

When I click the button both components are decremented at the same rate. I would like them to decrement by different values.
I am just learning React not sure if it is possible.

This is what I have so far.

const ParentComponent = () => {
  const [num, setNum] = useState(100);

  const handleClick = () => {
    if (num === 0) {
      return;
    }
    const decrement = Math.floor(Math.random() * 20) + 1;
    setNum(() => Math.max(num - decrement, 0));
  };

  return (
    <div>
      <ChildComponent value={num} />
      <ChildComponent value={num} />

      <button onClick={handleClick}>Random Decrement</button>
    </div>
  );
};
const ChildComponent = ({ value }) => <div>Num: {value}</div>;

Examples of lexical scoping in js other than nested functions?

I was trying to understand the lexical scoping. I gone through here and I found all examples are related to nested functions. Is lexical scope only related to nested functions and parent to child accessibility?

Are there any examples of lexical scoping in js other than nested functions and closures?

AND

Does function parameters also form lexical scoping? For example:

function greet(name) {
    console.log("Hello, " + name + "!");
}

greet("Alice"); // Output: "Hello, Alice!"
greet("Bob"); // Output: "Hello, Bob!"