Javascript Class, with one parameter passed to array;

I am trying to invoke a class with the code below:

class matchDetails {
        constructor(game, kit, player){
            this.game       = game;   // This remains static;
            this.kit        = color;  // This remains static;
            this.player     = new Array(player);
        }
        addMatchDetails(){
            // return "Coventry";
        }
    }
    
    ab = new matchDetails(23, 'red', 11);

On the constructor I want this.player to be an array where I can push additional values but I cannot fathom out how to code it.

Text content overflow its element tag

Here’s the code. It’s in Angular if that has something to do with it. The actual text height is overflowing the element that contains it.

html

<p id="website-title">Poll App</p>

css

#website-title {
    text-align: center;
    // font-family: "Roboto-Mono";
    font-size: 50px;
    margin: 0;
    position: absolute;
    top: 50%;
}

result
result

I want the element to be the height of the content. Any ideas? thx.

How to get all objects and count booleans (JS)

Let it be like this for example:

let data = {
    first: {
        surname: 'Miller',
        age: 37,
        gender: male,
        stealer: true
    },
    second: {
        surname: 'Connor',
        age: 28,
        gender: male,
        stealer: true
    },
    third: {
        surname: 'Smith',
        age: 13,
        gender: female,
        stealer: false
    }
}

How can I get everything at once and count booleans of false, without the need to manually enter each one individually?

Using lookup in mongodb to write a union query

Can someone please help me to make a union query:

I have all of the jobs that were created between a time period.

[{
    _id: '61be471835364400005ee66a',
    created: '2021-12-18T20:39:52.279Z',
    company: '61be44cb8c18cd0000be2048'
  }]

I got this doing an aggregate query:

const jobs = await Job.aggregate([
    {$match: ...},
    {$project: ...},
]);

I have a collection of companies, and am trying to get the COMPANY name to be pulled over into the query, rather than having to get it client side. I have the _id already in the aggregate query result. I have been trying to do this:

 const jobs = await Job.aggregate([
    {$match: ...},
    {$project: ...},
    {$lookup: {
    from: 'Company',
    localField: 'company',
    foreignField: '_id',
    as: 'result'
    };
]);

I was thinking that this would 1) get the Company that has an _id that matches our ‘company’ object ID above and 2) save that in the result field. There is nothing there, despite the object id being a match! Could someone please help walk me through how this should work? I could do it very easily I think in SQL.

Cannot synchronize functions to parse data and then visualise it

I have written this code to parse a csv file and then use this data to render a bar chart. I have tried to account for asynchronous functions using async/await, but for some reason my code is not working. When I run it the chart loads but the bars only render when I resize the window. Please could someone point out what I am doing wrong?

function parseData (dataFile){
    var barLabels = []
    var barData = []
    d3.csv(dataFile).then(function(datapoints) {
        for (i=0; i < datapoints.length; i++){
            barLabels.push(Object.values(datapoints[i])[0]);
            barData.push(Object.values(datapoints[i])[1]);
        }        
    });
    return [barLabels, barData];
}

function makeChart(dataX, dataY, canvasID){ 
    var ctx = document.getElementById(canvasID)
    var chart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: dataX,
            datasets: [
            {
                label: "Carbon Footprint of Leading European Apparel Brands in 2019",
                data: dataY,
                              
            }]
        }, 

    });

    
}


async function renderChart(file){
    let chartData = await parseData(file);
    makeChart(chartData[0], chartData[1], 'chart')
}

renderChart('carbon-footprint-of-apparel-brands-2019.csv')

How can you the return the largest Height value out of multiple divs using jQuery or JavaScript

I am trying to return / output the largest Height value out of multiple divs within an alert using jQuery or JavaScript. I’ve tried a few examples but I think I’m going about it the wrong way. I decided to use Math.max but I think that incorrect.

My code

    $(".go-buttn").click(function(){
        var sum = 0;
        var x = document.querySelectorAll(".col-lg-6.col-md-12.col-sm-12 .block");
        var maxValueInArray = Math.max.apply(Math, x);
        alert($(maxValueInArray).height());
    });


    <button class="go-button">Click me </button>

    <div> //This first div should return the tallest value in height
        <p>
        test 
        </p>
        <p>
        test 
        </p>
        <p>
        test 
        </p>
    </div>

    <div>
        <p>
        Test  
        </p>
    </div>

    <div>
        <p>
        Test  
        </p>
    </div>

Wait for completion of callback function in HTTP request before continuing with for loop

I’m trying to run an HTTP request 3 times in node.js using the inbuilt HTTPS library, with each run having a different set of options. In order to move on to the next set of options after the completion of one execution, I”m using a for loop that increments once each run, for a total of 3 runs. However, instead of waiting for each run to finish before proceeding in the loop, it skips the first two calls completely and runs it 3 times with the third set of options. I’ve looked all over for an answer, anyone have any ideas/solutions?

    for(let i = 0; i < 3; i++) {
        option = i;
        console.log("Calling with option " + i)
        await http.request(options[i], res => {
            let resp = '';
            res.on('data', function(chunk) {
                resp += chunk;
            });
            res.on('end', async function () {
                let data = await JSON.parse(resp);
                if(option === 0) { //Bloxlink handler
                    console.log("Case 1: Bloxlink")
                    if(data.status === "error") {
                        returndata += "Bloxlink returned no users"
                    } else {
                        returndata += "nBloxlink returned user with ID " + data.primaryAccount + " and username " + await noblox.getUsernameFromId(parseInt(data.primaryAccount)) + "."
                    }
                } else if(option === 1) { //RoWifi handler
                    console.log("Case 2: RoWifi")

                    if(data.success === false) {
                        returndata += "RoWifi returned no users"
                    } else {
                        returndata += "nRoWifi returned user with ID " + data.roblox_id + " and username " + await noblox.getUsernameFromId(data.roblox_id) + "."
                    }
                } else if(option === 2) { //Eryn handler
                    console.log("Case 3: Eryn")
                    if(data.status === "error") {
                        returndata += "Eryn returned no users"
                    } else {
                        returndata += "nEryn returned user with ID " + data.robloxId + " and username " + data.robloxUsername + "."
                    }
                }
                console.log(returndata);
            });
            res.on('error', function () {
                channel.send('One or more APIs returned an error. The operation has been terminated.')
            });
        }).end();
        channel.send("Run " + i + " finished: " + returndata);
        console.log(returndata);
    }

I am trying to pass different link on a same variable using different buttons with html and js

For my new project, I am trying to pass a link in a variable. I have buttons (multiple buttons let’s say 50 buttons). So what it has to do is on button 1 click it should pass to var link = button1link.html and on button 2 click it should pass a variable to var link = button2link.html. making a specific function to each button is quite a long process so, In short, a specific button click should pass a specific link to var link . please help me out with it.
Thanks 😀

 <button id="button1"  onclick= "seturl();">click here </button>
var link = "linkOfButton1.html"

popover click off to close (AND open another popover, if a different node is clicked)

See this codepen for a demo of the popovers when you click on a blue node.

I am trying to make the popover close functionality work like the following

  • If I click “off” (in some non-interactive space, the background page), close popover.
  • If I click another node when an existing popover is open, the existing popover will close and the new popover associated with the just-clicked node will open.

I’ve followed an implementation where an invisible “tooltip-overlay” appears, which supports the click-off to close functionality. But that won’t let me click on other nodes without first hiding the overlay.

clicking a node fires clicknode function, which displays the “tooltip” and the “tooltipBg”

  function clicknode(event, nodes) {
  const[x, y] = d3.pointer(event);
  tooltipBg.style("display", "block");
  tooltip
    .style("left", `${event.pageX}px`)
    .style("top", `${event.pageY}px`)
    .transition().duration(1).style("visibility", "visible")
    .transition().duration(300).style("opacity", 1)
    .style("display", "block");
     loadTooltipContent(nodes);
}

Thanks for any help you might have.

Getting TemplateSyntaxError in Jinja 2

I am creating a to-do list using Flask and I have a base.html page, using this for the actual tags to organize the website

Getting the error

jinja2.exceptions.TemplateSyntaxError

jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'endblock'. You probably made a nesting mistake. Jinja is expecting this tag, but currently looking for 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.

My code:

{% extends 'base.html' %}

{% block head %}

{% endblock %}

{% block body %}
<div class="content">
    <h1>Task Master</h1>

    <table>
        <tr>
            <th>Task</th>
            <th>Added</th>
            <th>Actions</th>
        </tr>
        {% for task in tasks %}
            <tr>
                <td>{{ task.content }}</td>
                <td>{{ tasks.date_created.date() }}</td>
                <td>
                    <a href="">Delete</a>
                    <br>
                    <a href="">Update</a>
                </td>
            </tr>
        (% endfor %)
    </table>

    <form action="/" method="POST">
        <input type="text" name="content" id="content">
        <input type="submit" value="Add Task">
    </form>
</div>
{% endblock %}

Javascript compare equality between arrays? [duplicate]

I’m trying to do the isPalindrome question on LeetCode. I know how to solve this question, but I’m just confused why the following code doesn’t work so that I can better understand the nuances of JS.
I would like to know why JS seems to think that even when reverse and forward.split(“”) are exactly the same, it should still return false.
The issue lies in the if (reverse == forward.split("")) line. I thought this issue is because JS can’t compare arrays, but a quick online search seems to suggest JS can.

var isPalindrome = function(s) {

let forward = s.replace(/[^0-9a-z]/gi, '').toLowerCase()

let reverse = forward.split("").reverse()
if (reverse == forward.split("")) {
    return true
}
return false

Mongoose .find() returns an empty array when searching by enum field

I have this schema:

const SoundSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    minFrec: {
        type: Number,
        required: true
    },
    maxFrec:{
        type: Number,
        required: true
    },
    minInt:{
        type: Number,
        required: true
    },
    maxInt:{
        type: Number,
        required: true
    },
    category: {
        type: String,
        lowercase: true,
        required: true,
        enum: ["Hogar", "Naturaleza", "Conversación", "Ocio", "Lugares", "Ciudad"]
    }
});

And I am trying to create this route to show all my items that match a certain category:

app.get("/sounds/:category", async (req, res) => {
const sounds = await Sound.find({ category: 'Ocio' }).sort({ name: 'asc'});
res.render("sounds/category", { sounds });
});

It does not work (returns an empty array) but it works if I filter by something without “enum” (name, minInt, etc).

I have done other routes that work, and I can find those items in mongo (db.sounds.find({category: "Ocio"})).

Why does audioContext muted the sound

I’m trying to do a visualiser like this: Visualiser Audio js

But with the file that is on my pc not one that the customer can choose.
Like here the file is on my pc.

<audio src="a.mp3" id="audioHTML" controls></audio>

I found this man doing it but it’s the customer who choose the file they want, so how can I do it ?

I tried this but the sound is muted and that’s my problem.
(when I delete ‘var context = new AudioContext();’ the sound is back but obviously there is not the visualiser)

'use strict'

var audio = document.getElementById("audioHTML");
  

function playAudio() {
    audio.play();

    var context = new AudioContext();
    var src = context.createMediaElementSource(audio);
    var analyser = context.createAnalyser();

    var canvas = document.getElementById("canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    var ctx = canvas.getContext("2d");

    src.connect(analyser);
    analyser.connect(context.destination);

   
    analyser.fftSize = 256;
    
    var bufferLength = analyser.frequencyBinCount;
    console.log(bufferLength);
    
   
    var dataArray = new Uint8Array(bufferLength);

    var WIDTH = canvas.width;
    var HEIGHT = canvas.height;

    var barWidth = (WIDTH / bufferLength) * 2.5;
    var barHeight;
    var x = 0;

    function renderFrame() {
      requestAnimationFrame(renderFrame);

      x = 0;

      analyser.getByteFrequencyData(dataArray);

      ctx.fillStyle = "#000";
      ctx.fillRect(0, 0, WIDTH, HEIGHT);

      for (var i = 0; i < bufferLength; i++) {
        barHeight = dataArray[i];
        
        var r = barHeight + (25 * (i/bufferLength));
        var g = 250 * (i/bufferLength);
        var b = 50;

        ctx.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
        ctx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);

        x += barWidth + 1;
      }
    }

    audio.play();
    renderFrame();
   }
#thefile {
  position: fixed;
  top: 10px;
  left: 10px;
  z-index: 100;
}

#canvas {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

audio {
  position: fixed;
  left: 10px;
  bottom: 10px;
  width: calc(100% - 20px);
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <link rel="stylesheet" href="style.css" />
</head>
    <body>

        <div id="content">
            <canvas id="canvas"></canvas>
            <button onclick="playAudio()">click</button>
            <audio src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3" id="audioHTML" controls></audio>
        </div>

        <script src="audioVisualiser.js"></script>
    </body>
</html>