“TypeError: n.push is not a function” using DataviewJS and Chart.js in ObsidianMD

Running into an issue trying to pull out values from the frontmatter of weekly notes in ObisdianMd and render a chart using DataviewJS and Chart.js.

The frontmatter for each weeks note looks like this…

---
Year: 2023
Week: 10
Time: 22:44
Tags: weekly_journal
Word: "Bullshit"
Mind:
  - 1
  - 2
  - 2
  - 1
  - 3
  - 4
  - 0
Body:
  - 1
  - 2
  - 2
  - 1
  - 3
  - 4
  - 0
Alias: "Stressed and tired"
---

Specifically I am pulling out the Mind and Body arrays, calculating the average of each, and plotting the results on a line chart (X = week, y=average).

Everything works as expected apart from when I attempt to define the y dataset on the graph using the calculated average from the arrays. This is when I encounter the TypeError: n.push is not a function error.

This code renders a chart correctly for the average weekly mind score when using dummy data (I have cut out a lot of the chart config options for clarity)…

const pages = dv.pages(`#weekly_journal and -"3000 - Templates"`)
const data = pages.map(b => average(b.mind))
const labels = pages.map(b => b.week)

const chartData = {
    type: 'line',
    
    data: {
        labels: labels,
        datasets: [
            {
                label: 'Mind',
                labelColors: true,
                data: [1, 2, 3],
                backgroundColor: [`rgba(255,255,255,0.9`],
                borderColor: [`rgba(210,105,30 ,0.3`],
                borderWidth: 2,
                borderDash: [3,5],
                tension: 0,
                pointStyle: `rectRounded`,
                stepped: false,
            },
        ],
        
    },

this.container.classList.add('chart-container')
window.renderChart(chartData, this.container)

function average(arr) {
    if (arr.length === 0) {
        return 0;
    }
    const sum = arr.reduce((a, b) => a + b);
    const avg = sum / arr.length;
    return Math.round(avg);
}

However, when I replace the line data: [1, 2, 3] with the data: data, expecting it to use the average calculated by const data = pages.map(b => average(b.mind)) it throws the TypeError: n.push is not a function error.

outputting the data const to the console confirms that it is an array…

values: Array(2)
0: 11
1: 10
length: 2

I am guessing it has something to do with the array data but beyond that I am stuck.

Priority in CSS when both id and tag are selected? [duplicate]

If the priority of the id selector in css is the highest, why are the background colors of the two p’s (test1 and test2) are same blue?

enter image description here

I have tried to change the order of selectors in the style code block and ways to express the id selector. like p #123 {} and #123 p {} .

I want to know the principle and how to use the id selector correctly in this case.
Thank you very much.

Loading Sentry from CDN with `defer` attribute, and avoiding Uncaught ReferenceError when initializing

I am loading Sentry from CDN with the defer attributed as per Using Defer in the Sentry docs.

I have a subsequent script tag, that initializes Sentry using Sentry.init, as per the Usage & Configuration docs.

This results in an Uncaught ReferenceError: Sentry is not defined as Sentry.init is executed before Sentry has time to load due to the deferred attribute.

What is the best way to initialize Sentry when using the defer attribute, so that errors that may occur in other scripts (which are also using defer) are not lost?

The code extact:


<script defer
            src="https://browser.sentry-cdn.com/7.42.0/bundle.tracing.replay.min.js"
            integrity="sha384-1l6jGKe2vLyGsLU9U92iHngOrra5b0R13LKJan+gGw9ZdY7iK2ayrwusH0QaMjWI"
            crossorigin="anonymous">
</script>

<script>
Sentry.init({
  dsn: "https://[email protected]/123456",
  release: "{{ SENTRY.dsn }}", //from Django Context
  integrations: [new Sentry.BrowserTracing()],
  tracesSampleRate: {{ SENTRY.traces_sample_rate }} //from Django Context,
});
</script>

// all other script tags are after Sentry and have a defer attributed (as per the docs).

Should I just extract the initialization logic into a separate JS file and then load it right after the Sentry CDN script tag also using defer, or are there better solutions?

Can I use an object in the parentheses of “`require()“` in Javascript/React?

I have a really simple app, that has a button.
When you press the button, the app plays a sound.
When I set the path of the file for the sound, I use require(`./assets/${array[0].bgm}.mp3`).
However, I get an error.

How can I make it work?

my app

Here is an array, where I’m going to get the name bgm for the path:

array.js

const array = [
  {
    id: 1,
    name: "Ken",
    bgm: "bgm",
  },
];

export default array;

Here is app.js.

import * as React from "react";
import { Text, View, StyleSheet, Button } from "react-native";
import { Audio } from "expo-av";
import SoundPlayer from "./SoundPlayer";

export default function App() {
  return (
    <View style={styles.container}>
      <SoundPlayer />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    backgroundColor: "#ecf0f1",
    padding: 10,
  },
});

Here is another file that contains require()

import * as React from "react";
import { Button } from "react-native";
import { Audio } from "expo-av";

import array from "./array";

export default function SoundPlayer() {
  const [sound, setSound] = React.useState();

  async function playSound() {
    console.log("Loading Sound");
    if (sound) {
      console.log("Unloading Sound");
      await sound.unloadAsync();
    }
    const { sound: newSound } = await Audio.Sound.createAsync(
      require(`./assets/${array[0].bgm}.mp3`) // This doesn't work.

      //require("./assets/bgm.mp3") //This just works.
     
    );
    setSound(newSound);

    console.log("Playing Sound");
    await newSound.playAsync();
  }

  React.useEffect(() => {
    return sound
      ? () => {
          console.log("Unloading Sound");
          sound.unloadAsync();
        }
      : undefined;
  }, [sound]);

  return <Button title="Play Sound" onPress={playSound} />;
}

However, this throws an error:

error: SoundPlayer.js: SoundPlayer.js:Invalid call at line 17: require("./assets/" + _array.default[0].bgm + ".mp3")

I need some help.
How would you solve this problem?
Thank you in advance.

(JS DOM) creating new elements in divs

So, I was trying to make a web app which acts like bot which uses a the textarea element as input. While referring to the JS DOM docs provided by W3Schools, I saw that my code was not working. I’m also new to JS DOM, so please forgive me if i’m the stupidest person you’ve ever met. (which i probably am)

Code:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link href="https://bot.valueyu.repl.co/style.css" rel="stylesheet" type="text/css" />
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <script src="script.js"></script>
</head>

<script>
  function reply() {
    const rplyBox = document.getElementById('rplyBox')
    const input = document.getElementById('msgBox').value;
    if (input === "help") {
      const embed = document.createElement("div");
      embed.classList.add("w3-round-xxlarge", "w3-margin-top", "w3-margin-bottom", "w3-margin-right", "w3-margin-left")
      const title = document.createElement("h1")
      title.createTextNode("Help");
      const desc = document.createElement("h3")
      desc.createTextNode("All of my commands!");
      const field1 = document.createElement("h6")
      field1.createTextNode("e");
      embed.appendChild(title);
      embed.appendChild(desc);
      embed.appendChild(field1);
      rplyBox.appendChild(embed);
    }
  }
</script>

<body style="background-image: url('https://bot.valueyu.repl.co/bg.mp4'); background-repeat: no-repeat; background-size: cover;">
  <div class="main">
    <t>bot.valueyu</t>
    <p>bot.valueyu is a bot made by Aarav Saini/Valueyu. For commmands type "<span
        class="w3-text-white">help</span>".</p>
    <hr>
    <textarea class="w3-round-large w3-bar" id="msgBox"></textarea>
    <br>
    <br>
    <br>
    <button id="submit" onClick="reply()" class="w3-round-xxlarge w3-button">Send</button>
    <hr>
    <div class="w3-bar w3-white w3-round-large" id="rplyBox">

    </div>
  </div>
</body>

</html>

Any help would be much appreciated.

Dont stop second video Youtube iframe api

Why, when I create a second player, I can no longer pause it, although when I first create a player in the this.player variable, I can pause it. At the same time, for some reason, when creating the second player, pauseVideo () does not work, although we call it on a variable that is simply overwritten and has this method.This is my code.

  constructor(selectorBtn, selectorBlock) {
    this.button = document.querySelectorAll(selectorBtn);
    this.block = document.querySelector(selectorBlock);
    this.close = this.block.querySelector(".close");
  }

  createPlayer(url) {
    this.player = new YT.Player("frame", {
      height: "100%",
      width: "100%",
      videoId: `${url}`,
    });

    this.block.style.display = "flex";
  }
  closePlayer() {
    this.close.addEventListener("click", () => {
      this.block.style.display = "none";
      this.player.pauseVideo();
      console.log("knock");
    });
  }

  init() {
    let tag = document.createElement("script");
    tag.src = "https://www.youtube.com/iframe_api";
    let firstScriptTag = document.getElementsByTagName("script")[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    console.log("hi from init");

    this.button.forEach((btn) => {
      btn.addEventListener("click", () => {
        const url = btn.dataset.url;
          this.createPlayer(url);
          this.closePlayer();
      });
    });
  }
}

I call this class like this

let videoplayer=new Video('.showup .play','.overlay')
videoplayer.init()

How to maintain enums (and adding new values) in a very large codebase

In a very large and old codebase, suppose we’re using a database column status with enum values as NEW, IN_PROGRESS, COMPLETED, REJECTED.

Now this status is used in multiple conditions in code like

if (status == `NEW` || status ==  `IN_PROGRESS`) {
  // do something
}

or might be in some SQL statement like

WHERE status NOT IN ("REJECTED")

Now if we want to add a new enum value to status eg. “CANCELLED”, then we’d have to handle all the places where status was used in the code.

Considering that the codebase can be somewhat distributed, large and quite old, it would prove to be very difficult for this sort of change. How can we improve this such that it would be easier to maintain these sort of changes?

ScrollIntoView() not working correctly on Opera and Chrome

I made script where on scroll it jumps to another div(with animation). I just removed normal scrolling function by adding overflow: hidden; into the body and add function where I used ScrollIntoView(). Everything is working fine on mozilla, but no longer on Opera and Chrome.

This is the view of the page at the beginning:
This is the view of the page at the beginning

And this is the view of the page after scrolling:
this is the view of the page after scrolling

<!DOCTYPE html>
<html>
    <head>    
        <script src="jquery-3.6.3.min.js"></script>
        <style>
            html, body {
                height: 100%;
            }

            body {
                margin: 0 auto !important;
                background-color: #1e1e1e;
                overflow: hidden;
            }

            .main {
                float: left;
                width: 100%;
                height: 100%;
                position: relative;
                background: url("main.jpg") no-repeat center center;
                -webkit-background-size: cover;
                -moz-background-size: cover;
                -o-background-size: cover;
                background-size: cover;
            }

            .start {
                float: left;
                width: 100%;
                height: 100%;
                position: relative;
                background: url("main.jpg") no-repeat center center;
                -webkit-background-size: cover;
                -moz-background-size: cover;
                -o-background-size: cover;
                background-size: cover;
            }

            .cennik {
                float: left;
                width: 100%;
                height: 100%;
                position: relative;
                background: url("main.jpg") no-repeat center center;
                -webkit-background-size: cover;
                -moz-background-size: cover;
                -o-background-size: cover;
                background-size: cover;
            }

            .uslugi {
                float: left;
                width: 100%;
                height: 100%;
                position: relative;
                background: url("main.jpg") no-repeat center center;
                -webkit-background-size: cover;
                -moz-background-size: cover;
                -o-background-size: cover;
                background-size: cover;
            }

            .student {
                float: left;
                width: 100%;
                height: 100%;
                position: relative;
                background: url("main.jpg") no-repeat center center;
                -webkit-background-size: cover;
                -moz-background-size: cover;
                -o-background-size: cover;
                background-size: cover;
            }

            .kontakt {
                float: left;
                width: 100%;
                height: 100%;
                position: relative;
                background: url("main.jpg") no-repeat center center;
                -webkit-background-size: cover;
                -moz-background-size: cover;
                -o-background-size: cover;
                background-size: cover;
            }
        </style>
    </head>

    <body>

        <div class="main" id="main"></div>

        <div class="start" id="start"></div>

        <div class="cennik" id="cennik"></div>

        <div class="uslugi" id="uslugi"></div>

        <div class="student" id="student"></div>

        <script>
                var scrollableElement = document.body; //document.getElementById('scrollableElement');

                scrollableElement.addEventListener('wheel', checkScrollDirection);



                function checkScrollDirection(event) {
                    var hash = window.location.hash.substr(1);

                    if (checkScrollDirectionIsUp(event)) {
                        switch(hash) {
                            case 'main':
                                break;
                            case 'start':
                                document.getElementById('main').scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'end' });
                                window.history.pushState({}, '', '#main');
                                var hash = 'main';
                                break;
                            case 'cennik':
                                document.getElementById('start').scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'end' });
                                window.history.pushState({}, '', '#start');
                                var hash = 'start';
                                break;    
                            case 'uslugi':
                                document.getElementById('cennik').scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'end' });
                                window.history.pushState({}, '', '#cennik');
                                var hash = 'cennik';
                                break;
                            case 'student':
                                document.getElementById('uslugi').scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'end' });
                                window.history.pushState({}, '', '#uslugi');
                                var hash = 'uslugi';
                                break;
                            default:
                                break;
                        }
                    } else {
                        switch(hash) {
                            case 'main':
                                document.getElementById('start').scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'end' });
                                window.history.pushState({}, '', '#start');
                                var hash = 'start';
                                break;
                            case 'start':
                                document.getElementById('cennik').scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'end' });
                                window.history.pushState({}, '', '#cennik');
                                var hash = 'cennik';
                                break;
                            case 'cennik':
                                document.getElementById('uslugi').scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'end' });
                                window.history.pushState({}, '', '#uslugi');
                                var hash = 'uslugi';
                                break;    
                            case 'uslugi':
                                document.getElementById('student').scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'end' });
                                window.history.pushState({}, '', '#student');
                                var hash = 'student';
                                break;
                            case 'student':
                                break;
                            default:
                                document.getElementById('start').scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'end' });
                                window.history.pushState({}, '', '#start');
                                var hash = 'start';
                                break;
                        }
                    }
                }

                document.body.addEventListener("touchmove", function (e) {

                    console.log(prevScrollPos - e.changedTouches[0].clientY);
                    prevScrollPos = e.changedTouches[0].clientY;

                });

                function checkScrollDirectionIsUp(event) {
                    if (event.wheelDelta) {
                        return event.wheelDelta > 0;
                        
                    }
                    return event.deltaY < 0;
                    
                }

                
            </script>

    </body>
</html>

As I see, the problem here is the animation. Without animation it works perfect but as you can imagine, it looks ugly.
I tried to change ScrollIntoView() to ScroolTop but animation wasn’t working for me.
Also tried to make in in jquery but I don’t think I doing it correctly.

How to : click button to open shopping basket available in another html file

I have an index.html with navigation bar, another html file for shopping basket and basket.js/ basket.css files. When you click on button basket in index.html you show the Basket.html file.how can i make it work?

I tried the following:

index.html:

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="css/basket.css">
    <title>Product List</title>
</head>
<body>
<div class="navbar" style="overflow:hidden; background-color:#009650; position:fixed; top:0; width:100%;" >
    <button id="basket-button" onclick="window.location.href='/Basket.html'"> Basket </button>
<script src="js/Basket.js"></script>
</body>

Basket.html:

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="css/basket.css">
    <title>Basket</title>
</head>
<div class="basket" id="shopping-basket">
    <div class="item">
        <div class="buttons">
            <span class="delete-btn"></span>
            <span class="like-btn"></span>
        </div>

        <div class="image">
        
        </div>

        <div class="description">
            <span>product name</span>
        </div>
        <div class="quantity">
            <button class="plus-btn" type="button" name="button">
            </button>
            <input type="text" name="name" value="1">
            <button class="minus-btn" type="button" name="button">
            </button>
        </div>
        <div class="total-price"></div>
<script src="js/Basket.js"></script>

Basket.js:


window.onload = () => {
  document.getElementById("basket-button").onclick = function() {myFunction()};
  function myFunction() {
    document.getElementById("shopping-basket").classList.toggle("show");
  }
}

basket.css:


   .basket{ display: none;}
   .basket.show {display:block;
                 position: absolute;
                 left:80%;
                 margin-top: 30px;
                 padding: 5px;
                background-color: #43484D;}

   .basket.hide {
      display:none;
    }             

Trying to use material-ui icons but getting white screen

I am trying to use material-ui icons, but when I use them, they show a white screen.
npm install @mui/material @emotion/react @emotion/styled
npm install @material-ui/icons
i have installed this material ui website
how can we solve this

i tried installing core icons from material ui still same error

set stepSize for radar chart

I have used this radar chart.js

  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>

    var options = {
          elements: {
            line: {
              borderWidth: 3
            }
          },
          scales: {
            r: {
              grid: {
                lineWidth: 4
              },
              angleLines: {
                lineWidth: 6
              },
              suggestedMin: 0,
              suggestedMax: 100,
            },                
          },            
        };

        var ctx = document.getElementById('myChart');

    var ChartData = {
      labels: [
        'Eating',
        'Drinking',
        'Sleeping',
        'Designing',
        'Coding',
        'Cycling',
        'Running'
      ],
      datasets: [{
        label: 'My First Dataset',
        data: [65, 59, 10, 21, 56, 55, 40],
        fill: true,
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderColor: 'rgb(255, 99, 132)',
        pointBackgroundColor: 'rgb(255, 99, 132)',
        pointBorderColor: '#fff',
        pointHoverBackgroundColor: '#fff',
        pointHoverBorderColor: 'rgb(255, 99, 132)'
      }, {
        label: 'My Second Dataset',
        data: [28, 48, 40, 19, 36, 27, 10],
        fill: true,
        backgroundColor: 'rgba(54, 162, 235, 0.2)',
        borderColor: 'rgb(54, 162, 235)',
        pointBackgroundColor: 'rgb(54, 162, 235)',
        pointBorderColor: '#fff',
        pointHoverBackgroundColor: '#fff',
        pointHoverBorderColor: 'rgb(54, 162, 235)'
      }]
    };

  var myRadar = new Chart(ctx, {
    type: 'radar',
    data: ChartData,
    options: options
  });
</script>

I want to set the stepSize for ticks, so I included this in r section

  var options = {
          elements: {
            line: {
              borderWidth: 3
            }
          },
          scales: {
            r: {
              grid: {
                lineWidth: 4
              },
              angleLines: {
                lineWidth: 6
              },
              suggestedMin: 0,
              suggestedMax: 100,
            },

              ticks: {
                stepSize: 20, // the number of step
                }, 
           
          },             
        };

but it doesn’t work and gives th fllowing error

Cannot determine type of ” axis. Please provide ‘axis’ or
‘position’ option.

how can i set stepSize for radar chart v.4.2.1?

how to store boolean value in mongodb using express js

i’m trying to store a boolean in mongodb but it always returns false
here’s my database

const UserSchema = new Schema({
  name: String,
  password: {
    type: String,
    required: true
  },
  isAdmin: {
    type: Boolean,
    default: false
},

this how i post the request using postman

{ 
    "name": "aj",
    "password":"aj",
    "admin": true
}

this the result i get in my database

isAdmin:false
name:"aj"
password:"$2a$10$wBfElJ3YbZoOk3Bz/tyFc.uzZGuzStDppDCINZ8mZexZKumnDMmoW"

please how can i set it admin to true or false when registering

Why is my Javascript function returning “undefined”? [duplicate]

I’m working on a Discord bot with Javascript, and I’ve been trying to implement a new command.
However, I can’t get one function to work properly.

The function here is used to get a value from a .json file and return the value as a string, however, it doesn’t work.

function readmood(moodvaleur) {
    fs.readFile(moodpath, 'utf8', (err, jsonString) => {
        if (err) {
            console.log('Error reading the JSON file:', err);
            return;
        }
        try {
            const moodlist2 = JSON.parse(jsonString);
            console.log(moodlist2);
            console.log(moodvaleur);
            console.log(moodlist2[moodvaleur]);
            const final = moodlist2[moodvaleur];
            return final;
        }
        catch (err) {
            console.log('Error parsing JSON string:', err);
        }
    });
}

I don’t know what could be wrong since the console.logs inside the function show me that I’m able to retrieve the json list, and the value that I want (and it tells me that it is a string too), but once I try to use the function for real (console.log(readmood(value)), it’s just “undefined”.

If someone could please help me understand what I’m missing here, I would be very grateful !

What does it store

What does chars[word] store in both the condition !chars[word] and chars[word]>max and how does it compare according to index

function repeat(str) {
  let chars = {}
  let arr = str.split('').reverse().join('')
  for (let word of arr) {
    if (!chars[word]) {
      chars[word] = 1
    } else {
      chars[word]++
    }
    console.log(chars)
    let max = 0
    let repeatedword = ''
    for (let word of arr) {
      if (chars[word] > max) {
        max = chars[word]
        repeatedword = word
      }
    }
    console.log(repeatedword)
  }
} function repeat ("hello how are you hello world I'm hello")