Show random picture with Javascript in HTML

I have a code which shows randomly a url to a picture.
I want to add the random shown url to the part where the picture is created.

How can I extract the url from javascript and use it in html? Test.jpg should be replaced with the random generated url.

<!DOCTYPE html>
<html>
  <head>
    <title>Der Titel des Dokuments</title>
  </head>
  <body>
      
      <h2>HTML Image</h2>
<img src="test.jpg" width="460" height="345">


      
      <div id="textbox"></div>
      
<script language="JavaScript">
var myimages = [{
  image: "https://cdn.prod.www.manager-magazin.de/images/ca3dd5d1-0001-0004-0000-000000088705_w920_r1.778_fpx42.51_fpy49.99.jpg",
  probability: 0.1
}, {
  image: "https://p6.focus.de/img/fotos/id_40323993/porsche-cayman-heck.jpg?im=Crop%3D%280%2C20%2C1600%2C800%29%3BResize%3D%28800%2C400%29&impolicy=perceptual&quality=medium&hash=69314e722c29162f49edafd9b16362ceb1a704219e2a128272824e5d8d585019",
  probability: 0.1
}, {
  image: "https://i.auto-bild.de/ir_img/1/7/6/3/5/7/9/Alle-Auto-Neuheiten-2019-1200x800-bbcf8a2e46bd3f1f.jpg",
  probability: 0.25
}, {
  image: "https://cache.pressmailing.net/thumbnail/story_hires/64940fdd-8ec9-4854-98f9-e7f7467414b7/image.jpg",
  probability: 0.55
}];

function getImage() {
  var rand = Math.random();
  var probabilitiy_sum = 0;
  for (var i = 0; i < myimages.length; i++) {
    probabilitiy_sum += myimages[i].probability;
    if (rand <= probabilitiy_sum) {
      return myimages[i].image;
    }
  }
  return myimages[myimages.length].image;
}

// Just for testing:
for (var i = 0; i < 1; i++) {
  document.getElementById("textbox").innerHTML += getImage() + "<br />";
}
</script>
        
  </body>
</html>

Comparing 2 arrays and fetch values to see if array 1 is greater than array 2

I am still in the midst of learning React and Javascript and have came to a roadblock with my current project.

Project goal
I am trying to map through two array of objects, and check if a certain property matches.
if recommendedSkillTree.skills.skill === currentSkills.skill, I would then like to check if recommendedSkillTree.skills.level > currentSkills.level.
if the above condition matches, or if currentSkills.skill do not have the skills in the recommendedSkillTree Data, the skill will then show up in a red text. Else, green text.

What I have done
I have tried mapping between the 2 arrays to check if currentSkills.skill === recommendedSkillTree.skills.skill.

  const skillMatch = recommendedSkillTree.filter((skillRecommended) =>
    currentSkills.some((skillCurrent) => skillRecommended.skill === skillCurrent.skill)
  );
.
.
.
  return (
   <div>
     {recommendedSkillTree.map((item, i) => (
            <div key={item.id}>
              <div
                style={{
                  color: !skillMatch[i] ? "red" : "green", 
                }}
              >
                {item.skill}
              </div>
            </div>
          ))}
   </div>


By doing so, I am able to churn out an output where skills that are present in currentSkills are shown in green, and those that are not in it are shown in red.

Next I would like to go one step deeper, and tried to compare the skill level of the present skills, and if they fall short of the recommended level, the text would then show in red.

  const levelGap = recommendedSkillTree.map((recommendedLevel) =>
    currentSkills.some((levelCurrent) => recommendedLevel.level > levelCurrent.level)
  );

By doing so, I would be expecting an output of

[true, false, true, true, true, true, true, true, true]

instead I’ve got:

[true, true, true, true, false, true, true, false, false]

I am unable to see which part have went wrong. Would greatly appreciate if any seniors in this field would guide me along.

Data 1

const recommendedSkillTree = [
  {
    id: "1",
    role: "Paladin",
    skills: [
      {
        id: "1",
        skill: "Attack",
        level: "3",
      },
      {
        id: "2",
        skill: "Block",
        level: "3",
      },
      {
        id: "3",
        skill: "Taunt",
        level: "3",
      },
      {
        id: "4",
        skill: "Heal",
        level: "4",
      },
      {
        id: "5",
        skill: "Group Heal",
        level: "2",
      },
      {
        id: "6",
        skill: "Double Attack",
        level: "4",
      },
      {
        id: "7",
        skill: "Ultimate",
        level: "3",
      },
      {
        id: "8",
        skill: "Defense Up",
        level: "2",
      },
      {
        id: "9",
        skill: "Attack Up",
        level: "2",
      },
    ],
  },
];
export default recommendedSkillTree;

Data 2

const currentSkills = [
  {
    id: "1",
    skill: "Attack",
    level: "2",
  },
  {
    id: "2",
    skill: "Block",
    level: "3",
  },
  {
    id: "3",
    skill: "Taunt",
    level: "2",
  },
  {
    id: "4",
    skill: "Heal",
    level: "3",
  },
  {
    id: "5",
    skill: "Final Slash",
    level: "3",
  },
];
export default currentSkills;

Thank you in advance for your time, and I do apologize if my way of asking questions are not up to community standard as this is my first time posting on here.
I do not really have anyone around me to ask questions on since I am fully self-taught and no one around me is in the tech field. Thank you so much.

Loop with delay in Postman test script

My API has two endpoints, one for starting a process and a second to check if that process has finished.

There can only be three states returned by the second endpoint: running, success or failure. Running is a temporary state, and once the process finishes, it will be marked as success or failure permanently.

How can I write a test script that keeps sending a request to the second endpoint (1 second delay) until it stops responding with running?

I’ve tried using pm.sendRequest but with no success. Since it is an async/callback function, it doesn’t work well when calling it recursively. I’ve also tried some setTimeout / setInterval hacks but with no success. And also, unfortunately, postman doesn’t support async / await syntax.

NextJS 12 and webpack 5 unknown property ‘fs’

I have upgraded from Next10 to Next12 (webpack5), also from React16 to React17. This is how our next.config.js looks like

next config here

When running a dev server this error comes up and I’m not sure how to work around it:

error on dev server

If I remove the fs: 'empty' from the config next12 does not seem to find other files in their respective location:

error when remove fs

Part of the package.json I believe its relevant to this looks as follow:

package json

How to remove multiple classes from different div with jQuery

I’ve three dropdowns.. When i click on the div with the data-column=”1″ ( Momentum Jeans Shorts ), I want the current dropdown to remove the “active” & “disable” class for the data-column=”1″ (Momentum Shorts) and also add the “disable” & “active” class on the selected div which is the data-column=”1″ ( Momentum Jeans Shorts )..

On my second dropdown, I would want the data-column=”1″ (Momentum Shorts) to not have the “disable” & “active” class. data-column=”2″ ( Momentum Jeans Shorts ) would have the “disable” class.

I’ve tried to work on this many hours but I cant seems to get the algorithm right.. I’ve attached a screenshot of the dropdowns, and hopefully you get what I’m trying to achieve

$(function() {
            $(".compare-filter-item").on("click",function() {
                const column_value = $(this).attr("data-column");
                const selected_data_product = $(this).attr("data-product");

                $('.compare-filter-item[data-product="' + selected_data_product + '"][data-column="' + column_value + '"]').parent().parent().find(".active.disable").removeClass("active disable");


                $("[data-product='" + selected_data_product + "']").addClass("disable");
                $(this).addClass("active");

                const myarray = $(`.compare-all .compare-products [data-product="${selected_data_product}"]`).map(function() {
                return $(this).html();
                });

                $(`.compare-main .compare-products [data-column="${column_value}"]`)
                .each(function(i) { $(this).html(myarray[i]) });
            });
        });

enter image description here
enter image description here

Aggregate using project and divide issue

I am trying to figure out how to calculate a golf leaderboard using javascript and aggregate, but am having some issues.

Here is what I am trying to do:

const pipeline = [
  { match: { oomId: oomId, holes: 0 } },
  { group: { 
    objectId: '$userId',
    played: { $sum: 1 },
    puts: {$sum: '$puts'},
    gir: {$sum: '$gir'},
    girHcp: {$sum: '$girHcp'},
    hits: {$sum: '$hit'},
    holesHit: {$sum: '$holesToHit'},
    points: {$sum: '$points'},
    strokes: {$sum: '$strokes'}
  } },
  { project:{ 
      puts: {$divide: {'$puts', '$played'}},
      gir: {$divide: {'$gir', '$played'}},
      girHcp: {$divide: {'$girHcp', '$played'}}
  }}
];

I get this error: Unexpected string

I might be looking at this the wrong way, but not sure how though… Hoping for help 🙂

how do i choose a modal to display my form and redirect to an external url on submit form?

I have started to create a form with Apps Script, using materializecss to create a menu with 3 different layouts.
#1 – when I embed my url to the New Google Sites, it doesn’t use the layout (modal), I need to know how to select one of the 3 sidebar options.
#2 – After submit, the form data is posted to the spreadsheet, but it doesn’t redirect to a different page.

I am a beginner in this, I refuse to sign up to webhooks like Google is forcing us to because I don’t want to share my user’s data. Your help is much appreciated.

function doGet(request) {
return HtmlService.createTemplateFromFile(`form`).evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function include(filename){
var url="https://docs.google.com/spreadsheets/d/1sRKhZY27YVY4xMLJs9qAn_lAumaUKT1AH1SgeBrKk_E/edit#gid=0";
var ss= SpreadsheetApp.openByUrl;
var ws=ss.getSheetByName("data");
}
function onOpen(){
  var ui=SpreadsheetApp.getUi();
  ui.createMenu("My Menu")
  .addItem("Sidebar form", "showInsidebarform")
  .addItem("Modal Dialog form", "showInmodaldialogform")
  .addItem("Modeless Dialog form", "showInmodelessdialog")
  .addToUi();
}
//OPEN THE FORM IN SIDEBAR
function showInsidebarform() {
var userform=HtmlService.createTemplateFromFile("form").evaluate().setTitle("Subscribe");
SpreadsheetApp.getUi().showSidebar(userform); 
}
//OPEN THE FORM IN MODAL DIALOG
function showInmodaldialogform() {
 var userform=HtmlService.createTemplateFromFile("form").evaluate();
SpreadsheetApp.getUi().showModalDialog(userform, "Subscribe");
}
//OPEN THE FORM IN MODELESS DIALOG
function showInmodelessdialog() {
var userform=HtmlService.createTemplateFromFile("form").evaluate();
SpreadsheetApp.getUi().showModelessDialog(userform, "Subscribe");
}
function appenData(data){
  var ws=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("data");
  ws.appendRow([data.name,data.email]);
}
<!DOCTYPE html>
   <html>
    <head>
    <!--Import Google Icon Font-->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>

    <body>
<div class="container">
  <div class="row">
    
           <div class="input-field col s12">
    <i class="material-icons prefix">account_circle</i>
    <input id="name" type="text" class="validate">
    <label for="name">First Name</label>
    </div>
    
        <div class="input-field col s12">
    <i class="material-icons prefix">email</i>
    <input id="email" type="text" class="validate">
    <label for="email">email</label>
   
        <div class="input-field col s12">
    <button class="btn waves-effect waves-light" id="btn">Submit
    <i class="material-icons right">send</i>
    </button>
    </div>

  </div><!--end row-->
</div>
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
var nameBox=document.getElementById("name");
var emailBox=document.getElementById("email");

document.getElementById("btn").addEventListener("click",addRecord);

function addRecord(){
  var name=nameBox.value;
   var email=emailBox.value;
 
  if(name.trim().length==0||email.trim().length==0){
 M.toast({html: 'Name and email are required'})
  }
  else{
var data={
  name:nameBox.value, 
   email:emailBox.value,
};
}
google.script.run.appenData(data);
nameBox.value="";
emailBox.value="";

self.location="https://www.theapothecary.app/homedoctor"

};

      </script>


    </body>
  </html>

Im posting my full code here, it has credits to: https://www.youtube.com/watch?v=4SqsK3Vh42Q&lc=UgzHk8aEXCtiDyh8e0B4AaABAg.9ZmDWeons-P9ZmyFFSUhEJ

Writing equivalent Python Code in Javascript (Beginner Question)

I want to be able to write an equivalent code using Javascript (mainly because I think there’s more interactive web features, and the graphic look nice on D3.js, Charts.js). However, as a complete beginner at JavaScript, I don’t know what might be the best way of going to do that. Is some particular framework useful if I want to plot some interactive graphics using math equations? I hear about Node.js, React, etc. and this is very confusing to me. Thank you.

import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interactive

x = np.linspace(0, 2*np.pi, 100) # 100 points from 0 to 2pi

def plotter(A, B):
    y = A*np.sin(B*x)
    plt.plot(x, y)
    plt.grid()
    plt.ylim(-3,3)
    plt.show()

interactive(plotter, A=(-3, 3, 0.1), B=(1, 5, 0.5))

how to change the color of line graph border on hover chartjs?

I am trying to change the color of the border line on the hover.
when line is hover then gray the other dataset color
and just show the color of the highlighted dataset border

1- this when the first dataset 1 is hover other line graph is gray

enter image description here

2- this is when dataset 2 is hover other line graph is gray

enter image description here

    import {
    Chart as ChartJS,
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
    Legend,
} from 'chart.js';
import { Line } from 'react-chartjs-2';
import faker from 'faker';

export const options = {
    responsive: true,
    interaction: {
        mode: 'dataset',
    },

    plugins: {
        legend: {
            position: 'top',
        },
        title: {
            display: true,
            text: 'Chart.js Line Chart',
        },
    },
};
const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
console.log(labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })));
export const data = {
    labels,
    datasets: [
        {
            label: 'Dataset 1',
            data: [100, -87, 200, 120, 150, 134, 43],
            borderColor: 'rgba(145,147,148,0.7)',
            backgroundColor: 'rgba(255, 99, 132, 0.5)',
            pointHoverBackgroundColor: 'red',
            hoverBorderColor: "red",
            hoverBackgroundColor: "#FC496BFF"
        },
        {
            label: 'Dataset 2',
            data: [20, -357, 5, 10, 131, 134, 43],
            borderColor: 'rgb(252,73,107)',
            hoverBorderColor: "blue",
            backgroundColor: 'rgba(255, 99, 132, 0.5)',
        },

        {
            label: 'Dataset 3',
            data: [30, -197, 25, 139, 96, 134, 43],
            borderColor: 'rgba(145,147,148,0.7)',
            hoverBorderColor: "blue",
            backgroundColor: 'rgba(53, 162, 235, 0.5)',
        },
    ],
};

Javascript/node – Filter data pulled from API to only read specific values

I am pulling all customer information via an API and printing it in the console.

I am doing this with

 if (this.readyState === 4) {
    console.log('Body:', this.responseText);
 }
};

which gives all of the following data (changed for obvious reasons)

{"id":2,"userIdent":"11","randomInfo":null,"isLead":false,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"1234 Happy Rd","street2":null,"city":"Smile City","countryId":249,"stateId":22,"zipCode":"12345","fullAddress":"1234 Happy Rd, Smile City, MI","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":2,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2022-03-07T00:00:00-0500","leadConvertedAt":null,"companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"boop":[],"accountBalance":0.0,"accountCredit":0.0,"accountOutstanding":0.0,"currencyCode":"USD","organizationName":"My Company","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#ef6c00","addressGpsLat":11.22,"addressGpsLon":-22.11,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":true,"hasSuspendedService":false,"hasServiceWithoutDevices":false,"referral":null}

I only want to pull the value associated with, for example, “userIdent” which would be 11, but I’m not sure how to do this when I’m pulling the data from the api.

How to know how many times this code is executed?

How many times is showMe() called when the following code is executed?

let timerId = setTimeout(showMe, 3000);

function showMe() {
  let div1 = document.getElementById("div1");
  div1.style.display = "block";
  timerId =

    setTimeout(showMe, 3000);
}

a. indefinitely

b.1

c.2

d.3

I thought it would be 1 but I attempted to run the code and it didn’t run

Prevent reload page when click on button take you to the same page link?

I would like to prevent an HTML button that acts like a link take you to the same page from reload the page

For Example: prevent reload the website when click on logo if you are in Homepage.

How can I do this?

Full code: https://codepen.io/Muh-Ail/pen/oNpLKXM?editors=0010

   let activeBtn = document.querySelector(".active-btn");
    let currentLocation = location.href;

    if (activeBtn.href === currentLocation) {

        activeBtn.preventDefault();

    }

Office.js outlook add-in issue

I’m trying to get the Body in Outlook and then update/set it with categories. My issue is this – when I debug it – it works fine. But when I don’t debug from function to function – it gets all the way to the last function and just stops – updateBody(). What’s really strang is if I remove the breakpoints on each function and just set a breakpoint on last function – never gets hit, but console will write out “Starting update body”. All the console.logs are writing out data as expected. Not sure what is going on. Appreciate any help! Thanks.

"use strict";
var item;
var response;
var tags;
var updatedBody;

Office.initialize = function () {
    $(document).ready(function () {
        // The document is ready
        item = Office.context.mailbox.item;
        debugger;
        getBodyType();

    });
}

function getBodyType() {
    item.body.getTypeAsync(
        function (resultBody) {
            if (resultBody.status == Office.AsyncResultStatus.Failed) {
                write(resultBody.error.message);
            } else {
                response = resultBody;
                console.log('Successfully got BodyType');
                console.log(response.value);
                getCategories();

            }
        });

}

function getCategories() {
    tags = "";
    // Successfully got the type of item body.
    // Set data of the appropriate type in body.
    item.categories.getAsync(function (asyncResult) {
        if (asyncResult.status === Office.AsyncResultStatus.Failed) {
            console.log("Action failed with error: " + asyncResult.error.message);
        } else {
            var categories = asyncResult.value;
            console.log("Categories:");
            categories.forEach(function (item) {
                var tag = item.displayName;
                tags += '#' + tag.replace(/s/g, "") + ' ';
            });
            console.log('Successfully got tags');
            console.log(tags);
            getBody();

        }
    });
}

function getBody() {
    var body = "";
    updatedBody = "";
    console.log("Starting get body");
    if (response.value == Office.MailboxEnums.BodyType.Html) {
        item.body.getAsync(
            Office.CoercionType.Html,
            { asyncContext: "This is passed to the callback" },
            function (result) {
                //Replace all the # tags and update again. 
                body = result.value.replaceAll(/#(w)+/g, "").trimEnd();

                var domParser = new DOMParser();
                var parsedHtml = domParser.parseFromString(body, "text/html");

                $("body", parsedHtml).append("<div>" + tags + "</div>");
                var changedString = (new XMLSerializer()).serializeToString(parsedHtml);
                if (changedString != "") {
                    updatedBody = changedString;
                }
                console.log(updatedBody);
                updateBody();
            });
    }
}

function updateBody() {
    console.log("Starting update body");
    item.body.setAsync(
        updatedBody,
        { coercionType: Office.CoercionType.Html },
        function (result2) {
            console.log("Body updated");
        });
}

Javascript weird behavior on first load

I recently started using turbolinks on my project and created a preloader, i’m facing an issue where sometimes javascript doesn’t get fired in my preloader.js file.

Example:

$(function() {
    window.addEventListener("load", function load(event){
        doneLoad()
    })

    gsap.set('html, body', {
        overflowY: 'hidden'
    })

    $(document).on('turbolinks:click', function(){
        startLoad()
    });

    $(document).on('turbolinks:load', () => {
        setTimeout(() => {
            doneLoad()
        }, 500)
    });


    function startLoad() {
        setTimeout(() => {
            window.scrollTo(0, 0);
        }, 500);
        

        gsap.timeline()
        .set('html, body', {
            overflowY: 'hidden'
        })
        .set('.turbo__loader', {
                    visibility: 'visible'
                })
        .to('.turbo__lines', {
            stagger: .3,
            height: "100%",
            duration: .5
        })
        .to('.turbo__logo, .__loader', {
            opacity: 1, 
            duration: .3
        }, '-=.3')
    }

    function doneLoad() {  

        console.log('Done Loading'); //<----Always fires

            gsap.timeline() //<----Doesn't always work
            .set('html, body', {
                overflowY: 'unset'
            })
            .set('#app, #__footer', {
                visibility: 'visible', 
            }, 'add')
            .add('do')
            .to('.turbo__lines', {
                stagger: .3,
                height: '0%'
            })
            .to('.turbo__logo, .__loader', {
                duration: .3, 
                opacity: 0
            }, 'do')
            .to('.turbo__loader', {
                visibility: 'hidden'
            }) 
    }

});

console.log in the doneLoad() function is always firing but gsap.timeline not always, I’m not seeing any errors, what could be the issue here? It only happens at the first load after that i never faced an issue.