Chartjs lines with two stacked lines are not displaying y-axis values ​correctly

I’m trying to create a js chart with lines that, when they have the same value, are not above each other, but when adding stacked: true, the values ​​on the y axis are incorrect

const yValues1 = [751, 1300, 1700, 1500, 2550, 3634];
const yValues2 = [750, 2300, 2700, 2890, 2550, 3634]; 

const options = {
  type: 'line',
  data: {
    labels: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
    pointRadius: 0,
    pointHitRadius: 0,
    datasets: [
      {
        label: '2023',
        data: yValues2,
        borderWidth: 2,
        borderColor: '#2196F3', // Cor da borda para o segundo dataset
      },
      {
        label: '2022',
        data: yValues1,
        borderWidth: 2,
        borderColor: '#EF6C00', // Cor da borda para o primeiro dataset
      },
    ]
  },
  options: {
    interaction: {
      mode: 'index',
      intersect: true,
    },
    stacked: false,
    pointBackgroundColor: 'transparent',
    tension: 0.4,
    plugins: {
      legend: {
        display: false
        },
    tooltip: {
         caretPadding: 60,
       backgroundColor: '#fef1ed',
       usePointStyle: false,
       titleColor: 'black',
       displayColors: false,
       titleMarginBottom: 5,
       titleFont: {
         size: 14,
       },
       borderWidth: 1,
       bodyColor: 'black',
       yAlign: 'bottom',
       //xAlign:'right',
       callbacks: {
         title: (context) => {
  // Obtém o valor do ponto atual
  const value = context[0].raw;

  // Formata o valor monetário com o símbolo da libra (£)
  const formattedValueWithSymbol = value.toLocaleString('en-GB', { style: 'currency', currency: 'GBP' });

  // Remove o símbolo da libra (£) do início do valor formatado
  const formattedValue = formattedValueWithSymbol.slice(1);

  // Retorna o valor formatado sem o símbolo da libra (£) no início
  return formattedValueWithSymbol;
         },
         label: (tooltipItem) => {
                    return ''
         },
       },
      //filter: function(tooltipItem, data) {
         //return tooltipItem.dataIndex !== 5
      //},
    },
      customBalloon: {
        backgroundColor: "#fef1ed",
      }
    },
    scales: {
      x: {
        stacked: true,
        offset: true,
         ticks: {
            color: ['#000000'],
            font: {
              weight: (value) => {
              return value.index === 5 ? 'bold' : 'normal'
              }
            },
            padding: 20
          },
        grid: {
          drawOnChartArea: false,
        },
      },
      y: {
        stacked: true,
        beginAtZero: true,
        title: {
          display: true,
          text: 'Values',
         },
         border: {
          display: false
        },
        ticks: {
            stepSize: 750,
        }
      }
    },
    responsive: true,
    maintainAspectRatio: true
  },
  plugins: [customBalloon]
}

// Criando o gráfico
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, options);

with stacked
enter image description here

no stacked
enter image description here

How to adjust this?

I hope to have lines that stay on the graph and are not above each other with equal values ​​and the y axis has the correct values

Simple question about HTML content and css

It happen alot with me, i set on my html code on a specific content display: none, to not show the inner content(child node), unless someone click on it, so, in my css i create another class, to display:block just to when someone clik on my content, i toggle or add this class and then, child node be showed, but it is not working, so i put !important on my css class and it work perfeclty fine, i would like to understand why.

here my html code, where class appear is such a class that i would like to no show, unless someone click on the radio.

<div class="outer_content">
            <form>  
                <p>Choose the triangle type:</p>  
                <input class="App" id="Eqi" type="radio" name="Type" value="equilateral">Equilateral<br>  
                <div class="Appear" style="display: none;"></div>
                <input class="App" id="Rec" type="radio" name="Type" value="rectangle"> Rectangle <br>  
                <div class="Appear"></div>
                <input class="App" id="Iso" type="radio" name="Type" value="isosceles">Isosceles <br>
                <div class="Appear" ></div>  
           </form>
</div>

here my css code, where on .appear .drop, when someone clik on my radio, i would like to show my class appear and change the display:none to block, but it work ONLY when i typed !important(which already has been added)

.Appear {
    width: 100%;
    
    transition: padding 0.5s;
  }
  .Appear.drop {
    display: block !important;
    height: 20px;
    padding-top: 2px;
  }

here my js code to perform my code.

let EquiConst = document.querySelector("#Eqi");
let RectConst = document.querySelector("#Rec");
let IsoConst = document.querySelector("#Iso");


let NewW = document.querySelectorAll(".Appear");



var radioButtons = document.querySelectorAll('input[type="radio"]');


//use code from Azoof Ahmed on https://stackoverflow.com/questions/77956842/any-idea-about-why-my-background-color-is-not-workin/77957267#77957267
//but added just a simple feature on work in all my 3 elements
function handleChange(e) {
  if(e.target.value === 'equilateral') {
    NewW[0].classList.add("drop");
   
  } else {
    NewW[0].classList.remove("drop");
  }

  if(e.target.value === 'rectangle') {
    NewW[1].classList.add("drop");
  } else {
    NewW[1].classList.remove("drop");
  }               
  
  if(e.target.value === 'isosceles') {
    NewW[2].classList.add("drop");
  } else {
    NewW[2].classList.remove("drop");
  }
}

// trigger handler with all radio buttons
radioButtons.forEach(function(radioButton) {
    
        radioButton.addEventListener('change', handleChange);
    
    
});


//append child to my div appear for put some data in there

let sideEqui = document.createElement("input")
let child1 = NewW[0].appendChild(sideEqui);

i’m just lookin for a explantion about it, im newbie

Call a Asp.NET PageModel from a javascript

I have an Asp.NET web app and I am quite new to it. On the main page, in the Index.cshtml, I have an html table on which I would like do something when a user click on a row of the table. I have read on the handler, which seems easy to use on a button (you put it in a form ), but not trivial on any javascript callback… So, I have created my javascript callback in which a call the server. For an obscure reason, the GET request works fine, put not the POST request… Did I miss something? Maybe there is a better way to achieve this…
Here is the .cshtml file:

@page
@using Microsoft.AspNetCore.Authentication.Cookies
@using Microsoft.AspNetCore.Authorization
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

@attribute [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]

<h1>Journals</h1>

@if (Model.journals == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <tbody>
            @foreach (var journal in Model.journals)
            {
                <form method="post">
                <tr onclick="RazorFunction('test')">
                    <td>@journal.name</td>
                    <td>@journal.type.ToString()</td>
                </tr>
                </form>
            }
        </tbody>
    </table>
}

@section Scripts
{
    <script>
        function RazorFunction(msg) {
            fetch('?handler=Add&msg=' + encodeURIComponent(msg)); // This works and call the OnGetAdd function
            
            fetch('?handler=Add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'msg=' + encodeURIComponent(msg),
            }); // This does not work and return an error status of 400.
            

        }

    </script>
}

And here is the Index.cshtml.cs file:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Security.Claims;
using WebApplication1.Model.Data;
using WebApplication1.Service;

namespace WebApplication1.Pages
{
    public class IndexModel : PageModel
    {
        private readonly JournalService journalService;

        public List<JournalMembership> journals;

        public IndexModel(JournalService journalService)
        {
            this.journalService = journalService;
        }

        public async Task OnGetAsync()
        {
            int user_id = int.Parse(User.FindFirst(ClaimTypes.UserData).Value);
            journals = await journalService.getJournalMembershipsAsync(user_id);

        }

        public void OnGetAdd(string msg)
        {
            Console.WriteLine("OnGetAdd!!!!!! : " + msg);
        }

        public void OnPostAdd([FromBody] string msg)
        {
            Console.WriteLine("OnPostAdd!!!!!! : " + msg);
        }
    }
}

Is this even something a human can understand

You know I learned programming its basics I have 4 years of experience and what this code does not make any sense to me can anyone explain to me like 5 year old, what this code does I am trying to traverse through nested folders

c:UsersWelcomeDesktopDlangtest1test2test3test4

const fs = require("fs");
const path = require("path");

let dir = __dirname;

let iterate = function(dir) {
  const stack = [dir];

  while (stack.length > 0) {
    let currentDir = stack.pop();

    fs.readdirSync(currentDir).forEach((item) => {
      let fullPath = path.join(currentDir, item);

      if (fs.statSync(fullPath).isDirectory()) {
        console.log(fullPath); // Output the directory path
        stack.push(fullPath);   // Push subdirectories onto the stack
      } else {
        console.log(fullPath); // Output the file path
      }
    });
  }
};

iterate(dir);
 

// expected test1/test2/test3/tes4

Discord.js v14: Handling multiple simultaneous interactions

I’m wondering what the best approach is for handling multiple simultaneous interactions at the same time?

For example, I have built a library of slash commands for our Discord bot. A few of them take a while to process data, others respond really quickly.

I’m not too concerned about the interactions that respond quickly because the odds of someone running a simultaneous slash command before a response is given is fairly slim, however ..

I’ve noticed however that when I run a slash command that takes a while to fetch a response, and then I run the same girthy slash command before the response has been given via interaction.reply, interaction.editReply or interaction.followUp , Discord.js seems to forget which interaction that it is meant to be replying to and throws an exception when trying to reply with a response for the first interaction.

The question is, if running multiple slash commands and handling multiple interactions at once, how would you guys go about approaching it?

I’ve tried to write a global flag to check when an interaction is pending, for example:

let interactionProcessing // Within a global scope

...


// Further down, within the slash command functionality
if(interactionProcessing) {
  return;
}

interactionProcessing = true;

// Logic here that processes the output

interaction.reply({content: theLogicsOutput}); // The issue here is, that it seems to have lost the definition for the initial interaction and throws an exception

interactionProcessing = false;

return;

I’m just curious to see if anyone else has encountered this issue and if they have any advice in honesty.

How do I render Raw JS customElements from external lib in Vue/Vite?

I have a library where I register a bunch of components…

function CREATE_ELEMENT(name, object, params) {
    customElements.get(name) ||
    customElements.define(name, object, params);
}
CREATE_ELEMENT('jrg-splash', SplashComponent, {});

const CUSTOM_ELEMENTS = [
    ...
    "jrg-splash",
];

export {CREATE_ELEMENT, bus, CUSTOM_ELEMENTS}

Now I want to use these components in my Vite project to start with in my vite.config.js I add

plugins: [
        vue({
            template: {
                compilerOptions: {
                    isCustomElement: tag => tag.startsWith('jrg-')
                }
            }
        }),
        vueJsx(),
    ],

And then I try adding the component. In my main.js I add

import '../../jrg-ui/target/jrg-ui.esm.mjs';

However, although I can render the components in the index.html file

<div class="other" style="height: 100%; width: 100%; padding-top: 64px;">
  <jrg-splash class="scroll-area"></jrg-splash>
  <div id="app"></div>
</div>

I cannot render inside custom components. For example if I add a splash page in the HomeView.vue component like…

<script setup>
import {RouterLink, RouterView} from 'vue-router'
</script>

<template>
  <header>
    <img alt="Vue logo" class="logo" height="125" src="@/assets/logo.svg" width="125"/>

    <div class="wrapper">

      <nav>
        <RouterLink to="/">Home</RouterLink>
        <RouterLink to="/about">About</RouterLink>
      </nav>
    </div>
  </header>
  <RouterView></RouterView>
  <jrg-splash></jrg-splash>

</template>

I get RouterView will render but not the splash page. What do I need to do to get registered custom components to render when using Vue/Vite?

Also to clarify I use this custom element lib in raw HTML/JS projects with no Vue as well so I should be able to also import this into non-vue projects as well. Therefore moving the createElements stuff into the Vue project like

import { CREATE_ELEMENT, bus, CUSTOM_ELEMENTS } from '../../jrg-ui/target/jrg-ui.esm.mjs';

import {createApp} from 'vue'
import {createPinia} from 'pinia'

import App from './App.vue'
import router from './router'

// Define your custom elements here
CUSTOM_ELEMENTS.forEach((element) => {
    if (!customElements.get(element)) {
        CREATE_ELEMENT(element, object, params);
    }
});

const app = createApp(App)

app.use(createPinia())

Won’t work. I also have confirmed the import is only happening 1 time

Is it possible to retrieve objects in use from memory of a Next.js/React app?

I am building an web-based editor and I came across a live website that has a similar approach to my idea. I want to see the structure of objects they are using to create components, or to see the React states/onChange handlers. Is it possible to see the implementations of these functions in the bundle/react dev tools or the memory heap snapshot?

Using React Dev Tools I can see a ton of ContextProviders, some have values, some functions, but the functions only have their names displayed

How to dive deep into how the values are being used in the website? Is it possible to find its corresponding consumer kind of how you can hover an HTML element in the tree and see it highlight in the website?

Here is a sample view from react dev tools

Find “.json” file from the 2nd level using regrex and node js

I am trying to get the “.json” file from the second level nesting from the folderPath.

So suppose this is my folderPath= "/user/admin/" and I want to find if the second level nesting after contains a “.json” file or not

So I wrote a code but it is not helping to find the 2nd level “.json”

function checkIfLastTwoLevelsAreJson(folderPath, filePath) {
    const fullPath = folderPath+ filePath;
    const regex = /(?:/[^/]+){2}/[^/]+.json$/; // Matches exactly two levels followed by .json
    return regex.test(fullPath);
}

const folderPath = "/user/admin";
const filePath1 = "en-us/dummy.json";
const filePath2 = "en-us/hello/dummy.json";
const filePath3 = "en-us/test/hello/dummy.json";

console.log(checkIfLastTwoLevelsAreJson(folderPath, filePath1)); // true
console.log(checkIfLastTwoLevelsAreJson(folderPath, filePath2)); // false
console.log(checkIfLastTwoLevelsAreJson(folderPath, filePath3)); // false

but here is the problem I am getting everything true it should have given me the first true and the rest false as the “.json” file containing at third or fourth level.

Can someone help me so I can get true only if the “.json” file is present in the 2nd level not in other levels?

SQLite .get() in Javascript is executing last [duplicate]

The problem

I am trying to create a login page for a website and need to get the hashed password out of a SQLite database to compare. However, whenever I call the .get method, the rest of the code executes before getting the password out of the database. I have tried:

  • Making the function async and adding “await”
  • Returning the password from a callback function
  • Saving the password directly to a variable
  • Making the .get method “await” (I know sqlite doesn’t support async functions but I got desperate

All of the solutions return the same result, which is an empty object until all of the other code is executed.

Server.js (login function)

//will be used to authorize a login
router.post("/Login/auth", async (req, res) =>{
    const email = req.body.email;
    const password = req.body.password;
    const hashedPassword = await SPCP.checkLogin(email);
    console.log("HASHED: " + JSON.stringify(hashedPassword));
    const isValid = bcrypt.compare(password, "check");

    if (isValid){
        res.status(200);
        console.log("Password matches");
    }
    else {
        res.status(401);
        console.log("Wrong password");
    }
});

Database.js (get password out of database function)


//check the username and the password for the database
async function checkLogin(email){
    let password = "";
    sql = "SELECT password FROM users WHERE email = '" + email + "';"
    console.log("SQL STRING: " + sql);
    password = db.get(sql, (err, row) =>{
        console.log(row);
        password = row.password;
    });
    console.log("AFTER .GET " + JSON.stringify(password));
    return password;

}

The results

SQL STRING: SELECT password FROM users WHERE email = '1111';
AFTER .GET {}
HASHED: {}
Password matches
{
  password: 'hashedPassword'
}

If any additional information is needed please let me know.

Cant return from inside a map

I’m trying to return two results from within a map to the containing function, but it always returns an undefined result, I think maybe happens because it return to the arrow function instead of the main one but I’m not sure how to resolve it.

let nums          = [1, 2, 4, 5, 6, 7, 10, 21, 42, 3]
let target        = 22
let numerodearray = -1

calculator()

function calculator(i, j) 
  {
  nums.map((item) => 
    {
    numerodearray  = numerodearray + 1
    let loopmaximo = nums.length
    for (let i = numerodearray; i < loopmaximo; i++) 
      {
      let comparator = nums[i]
      if (item + comparator == target) 
        {
        console.log(item)
        console.log(comparator)
        return [item, comparator]
        }
      }
    })
  }

i was expecting that the function will receive those two values but it doesn’t and i am not sure why.

Mongoose: TypeError – Views.updateOne is not a function

I’m encountering an issue with my Mongoose model when trying to use the updateOne method. I’ve defined a Mongoose schema called viewSchema, and I’m trying to update a document using Views.updateOne. However, I’m receiving a TypeError stating that Views.updateOne is not a function.

Reproducible Example:

const Views = require('../models/views');

//function update to add +1 to the number of views fro this day
  const updateViews = async (req, res) => {
    try {
      // Get today's date
      const today = new Date();
      today.setHours(0, 0, 0, 0);
  
      // Get tomorrow's date
      const tomorrow = new Date(today);
      tomorrow.setDate(tomorrow.getDate() + 1);
  
      // Update the views for today
      const result = await Views.updateOne(
        { createdAt: { $gte: today, $lt: tomorrow } }, // Find document with today's date
        { $inc: { numberOfViews: 1 } }, // Increment the numberOfViews field by 1
        { upsert: true } // Create the document if it doesn't exist
      );
  
      // Send response
      res.json({ message: "Views updated", result });
    } catch (error) {
      // If an error occurs, send an error response
      console.error(error);
      res.status(500).json({ error: "Internal server error" });
    }
  };

I expect the updateViews function to successfully update the document with today’s date and increment the numberOfViews field by 1.

Minus floating point value returns wrong result javascript?

I have noticed when im doing a simple calculaiton like this in the browser console or in my javascript application i get the wrong value back. I can simply round the end result but this behaviour is really strange and causing unexpected issues in my program. Any help is appreaciated

ref image
Doing 1.1 – 1.2 results in -0.09999999999999987 instead of -0.1

I expected the result to be -0.1 but its a very long float value instead. I rounded the value to the nearest decimal but this doesnt work accurately in all cases.