Why my chart is injected with some random padding inside my canvas?

I can’t figure out why I’m not able to remove this random padding injected inside my line chart in Chart.js (file attached).

Here is a part of my chart configuration :

myChart.current = new Chart(canvasRef.current, {
      type: "line",
      data,
      options: {
        tension: 0.6,
        scales: {
          x: {
            display: false,
          },
          y: {
            display: false,
          },
        },
        plugins: {
          legend: {
            display: false,
          },

Thank you very much for your help 🙂 !
[1]: https://i.stack.imgur.com/lNi5p.png

JavaScript React: Opening multiple popouts too quickly causes window to return as a proxy

I have a component called Popout.js which receives parameters from my App.js to open a popout.

Each popout is then pushed to an array, this array is later iterated through and each popout is closed if the parent window is closed.

This array is saved and updated inside a Redux state.

The functionality for these components work fine, unless you try opening too many popouts too quickly. I have the popoutsArray logged each time the array is updated. If popouts are opened too quickly, some items in the array which previously logged as Windows are now logged as Proxies, and subsequently my program crashes.

What is causing this and how can I fix it?

Redux:

export const popoutSlice = createSlice({
    name: "app",
    initialState: {
        compose: false,
        users: false,
        tags: false,
        rooms: false,
        documents: false,
        popoutLeftOpened: JSON.parse(
            localStorage.getItem("popoutLeftOpened") ?? "{}"
        ),
        dimensions: JSON.parse(localStorage.getItem("dimensions") ?? "{}"),
        popoutsArray: [],
    },

        setPopoutsArray: (state, action) => {
            const newWin = action.payload;
            console.log(newWin);
            state.popoutsArray = [...state.popoutsArray, newWin];
            console.log(state.popoutsArray);
        },

Popout.js:

import { useEffect, useState } from "react";

import { useDispatch } from "react-redux";

import {
    setPopoutLeftOpened,
    setPopoutsArray,
} from "../../features/popoutSlice";

function Popout({ popout, setting, show }) {
    const dispatch = useDispatch();
    const [popoutWindow, setPopoutWindow] = useState(null);

    function openWindow() {
        dispatch(
            setPopoutLeftOpened({ name: setting, popoutLeftOpened: true })
        );
        const settings = JSON.parse(
            localStorage.getItem(setting + "-dimensions")
        );
        let features = "width=800, height=500, left=300, top=200";
        const dim = settings;
        if (dim != null) {
            features =
                "width=" +
                dim.width +
                ", height=" +
                dim.height +
                ", left=" +
                dim.left +
                ", top=" +
                dim.top;
        }
        var url = window.location.protocol + "//" + window.location.hostname;
        if (url.includes("localhost")) {
            url += ":" + window.location.port;
            url += popout;
        }

        const newWindow = window.open(url, "_blank", features);

        dispatch(setPopoutsArray(newWindow));

        var timer = setInterval(function () {
            if (newWindow.closed) {
                clearInterval(timer);
                dispatch(
                    setPopoutLeftOpened({
                        name: setting,
                        popoutLeftOpened: false,
                    })
                );
            }
        }, 1000);

        return newWindow;
    }

    useEffect(() => {
        if (show) {
            if (popoutWindow === null) {
                setPopoutWindow(openWindow());
            }
        } else {
            if (popoutWindow !== null) {
                console.log("closed the popout? 1");
                dispatch(
                    setPopoutLeftOpened({
                        name: setting,
                        popoutLeftOpened: false,
                    })
                );
                popoutWindow.close();
                setPopoutWindow(null);
            }
        }
    }, [show, popoutWindow]);

    useEffect(() => {
        return () => {
            setPopoutWindow((popoutWindow) => {
                if (popoutWindow !== null) {
                    dispatch(
                        setPopoutLeftOpened({
                            name: setting,
                            popoutLeftOpened: false,
                        })
                    );
                    popoutWindow.close();
                }
                return null;
            });
        };
    }, []);

    return null;
}

export default Popout;

Console when popouts opened at a normal speed:

Console showing popoutsArray

Console when popouts are spammed/opened too quickly (and program crashes):

Console when popouts are spammed and return as a Proxy

If you need more information please let me know, or if this is a repeated question let me know and the question will be modified or deleted.

How do you get text from span tag in React (onClick)?

I’m new to React, but not to programming. In the following code, desc never changes state, and I believe this is because the tag isn’t entirely compatible with the value and onChange attribute/event handler im trying to use with it.

What im trying to do is get the text information from the span tag when you press the className=’submit’ button. I saw some videos where people suggested the method i have in place now, where you constantly update the state onChange, however this seems janky to me and if theres a better way where you get the text only onClick once instead of constantly updating, please let me know.

Also, I’m using a span with the contentEditable attribute because of CSS styling reasons, I want a borderless box that expands itself and the container its in instead of the text going off the page to the right. I attached a screenshot of what I mean.

ScreenshotOfCard

    const [title, setTitle] = useState('');
    const [desc, setDesc] = useState('');

        return (
            <div className='card-container'>
                <div className='card'>
                    <h1 className='card-title'>
                        <input className='titletext' value={title} onChange={e => setTitle(e.currentTarget.value)} placeholder='Who do you need?'></input>
                    </h1>
                    <p className='card-desc'>
                        <span className='textarea' value={desc} onChange={e => setDesc(e.currentTarget.value)} contentEditable></span>
                    </p>

                    <button className='submit' onClick={event => {
                        /*
                            Add job to the database (async)

                            Add new card with information submitted in the list right below
                        */
                        event.preventDefault();
                        console.log(title);
                        console.log(desc);
                        
                    }}></button>
                </div>
            </div>
        );
}

function with documentation that gives me error promise returned from `findByTestAttr` query must be handled

I’m trying to document my code but when I create a function with document standard /** */
I’m having errors like

promise returned from `findByTestAttr` query must be handledeslinttesting-library/await-async-query)

I don’t know what is the problem. Could anyone explain to me why that happens?

Here is the code.

/**
* Returns node(s) with the given data-test attribute.
* @param {ShallowWrapper} wrapper - Enzyme shallow wrapper.
* @param {string} val - Value of data-test attribute for search.
* @returns {ShallowWrapper}
*/
export const findByTestAttr = (wrapper, val) => {
  return wrapper.find(`[data-test="${val}"]`);
};

And I’m calling it here:

test("renders without errors", () => {
  const wrapper = mount(<App />);
  const appComponent = findByTestAttr(wrapper, "component-app");
  expect(appComponent).toHaveLength(1);
});

Expressjs base API delete method show error can not get error?

I’m new is Express.js; I try to build an API without any database. All routes work correctly but the post and delete API is not working.
When I hit delete URL in the browser, I find an error.
delete URL error

My app.js routes page look like

import express from "express";
import logger from "morgan";
import bodyParser from "body-parser";

//  get routes
import indexRouter from "./routes/index.js";
import postRouter from "./routes/post.js";
import tagRouter from "./routes/tags.js";
import commentRouter from "./routes/comment.js";
import authorRouter from "./routes/author.js";

// post routers
import postMethodRouters from "./routes/postMethodRouters.js";

//  delete routers
import deletePostRouters from "./routes/delete.js";

var app = express();

app.use(logger("dev"));
app.use(bodyParser.json());
// app.use(express.urlencoded({ extended: false }));

//  get method
app.use("/api/v1/", indexRouter);
app.use("/api/v1/post", postRouter);
app.use("/api/v1/tags", tagRouter);
app.use("/api/v1/comments", commentRouter);
app.use("/api/v1/authors", authorRouter);

//  post method
app.use("/createPost", postMethodRouters);

//  delete method
app.use("/api/v1/", deletePostRouters);

var listener = app.listen(8080, function () {
  console.log("Listening on port " + listener.address().port);
});

My delete.js routes look like

import express from "express";

var router = express.Router();

router.delete("/delete/:id", function (req, res) {
  res.status(200).send("DELETE request to homepage");
});

export default router;

My post.js routers look like

import express from "express";

import getBlog from "../API/Post/singleGenrater.js";

var router = express.Router();


router.post("/", function (req, res) {
  
  res.send("POST request to homepage");
});
export default router;

Check checkbox by index in another list

I have an unordered list with div elements and a hidden checkbox list, each with the same number of items.

How can I check an item in list 2 when I click a div in list 1 with the same index?

<ul class="product-list">
  <li>
    <div>Red</div>
  </li>
  <li>
    <div>White</div>
  </li>
  <li>
    <div>Blue</div>
  </li>
</ul>

<ul class="product-checkbox>
  <li>
    <input type="checkbox">Red
  </li>
  <li>
    <input type="checkbox">White
  </li>
  <li>
    <input type="checkbox">Blue
  </li>
</ul>

So here if I click Red in the first UL, Red gets checked in the second UL.

I can get the index of the LI in the first but not apply that index to check the box

$(document).on('click', '.product-list li', function() {
    var index = $(this).index();

    if ($('.product-checkbox #checkbox index').prop('checked')) {
        $('.product-checkbox #checkbox index').prop('checked', false);
    } else {
        $('.product-checkbox #checkbox index').prop('checked', true);
    }            

});        

Collapsed Sidebar with jquery load page [duplicate]

I would like to build for my website a mega menu like this model: https://jsfiddle.net/pcatydqh/

But I would like to use jquery to load this menu from my popupMenu.php file, I have this jquery code below to load it:

$('body').on('click','.openbtn',function(){
  var xmlhttp;
  if(window.XMLHttpRequest)
  {
      xmlhttp = new XMLHttpRequest();
  }
  else
  {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
      if(this.readyState==4 && this.status==200)
      {         
      document.getElementById("mySidebar").style.width = "300px";             
      document.getElementById("mySidebar").innerHTML=xmlhttp.responseText;
      document.getElementById("main").style.marginLeft = "300px";
      }
  }
  xmlhttp.open("GET","../scripts/popupMenu.php",true);
  xmlhttp.send();

});

When I click on my menu button (class=”openbtn”), it open and display my menu (there is no problem) but I can’t open the sub-links into my div class=”dropdown-container” by clicking on my button class=”dropdown-btn”, it doesn’t work, how to fix this problem?

Thank you in advance for your help.

Paul

Vue.js run method to fit text in div when view enters

I’m new to Vue and Ionic so I’m learning as I go.

I want to fit some text into a certain DIV i have on my page. But I cannot seem to make it work.

I want with page load to run a certain function so it can check whether or not the text need to be fitted.

I have found the following function:

dynamically changing the size of font size based on text length using css and html

const input = document.querySelector('input');
const output = document.querySelector('.output');
const outputContainer = document.querySelector('.container');

function resize_to_fit() {
  let fontSize = window.getComputedStyle(output).fontSize;
  output.style.fontSize = (parseFloat(fontSize) - 1) + 'px';
  
  if(output.clientHeight >= outputContainer.clientHeight){
    resize_to_fit();
  }
}

function processInput() { 
  output.innerHTML =this.value;
  output.style.fontSize = '100px'; // Default font size
  resize_to_fit();
}

input.addEventListener('input', processInput);

Now I have incorporated this into my app the following way:

...
<ion-text class="outputContainer">
  <div class="output" style="word-break: break-all; word-wrap: break-word;">{{key}}</div>
</ion-text>
...

export default {
    components: {
        IonPage,
        IonContent,
        IonNavLink,
        IonIcon,
        IonText
        
    },
    created(){
      return this.$store.getters.getStorageKey;
    },
    setup() {
      return {
          cog
      };
    },

    mounted() {
      this.resize_to_fit(".output", ".outputContainer");
    },
    computed: {
      aandoening(){
        return this.$store.getters.key;
      }
    },
    methods:{
      resize_to_fit(divOutputClassName, divOutputContainerClassName) {

        const output = document.querySelector(divOutputClassName);
        const outputContainer = document.querySelector(divOutputContainerClassName);

        let fontSize = getComputedStyle(output).fontSize;
        output.style.fontSize = (parseFloat(fontSize) - 1) + 'px';
        
        if(output.clientHeight >= outputContainer.clientHeight){
          //this.resize_to_fit(".output", ".outputContainer");
        }
      }
    }
}

You see I have commented out that last line because I got an error in the Vue console:

Uncaught (in promise) RangeError: Maximum call stack size exceeded

When I remove that line it doesn’t work, nothing gets changed, font-size doesn’t get changed.

I am pretty new to this so I’m probably doing things wrong, but I cannot seem to figure it out. If someone could help me, that would be great. Thanks.

Unable to avoid mousewheel scrolling the whole page when capturing the mousewheel in youtube (Javascript)

I’m trying to get a simple Chrome plugin to skip forward and backwards in youtube when the mousewheel is scrolled vertically.
That is working fine, but unfortunately the page also scrolls up and down when I use the mousehweel. I am trying to cancel the propagation of the mousewheel event with no success.

I have tried to no avail:

e.preventDefault();

return false;

e.stopImmediatePropagation();

Here is the code, as you can see I’ve tried many things.
There are only two JS files:

const playerdata = {
  "www.youtube.com" : {
    "keyCodes" : [39, 37],
    //"keyCodes" : [76, 74],
    "elem" : document
  }
}


var curPlayer = playerdata[location.host]

function triggerKeydown(forward) {
    //try {
          var elem;
          var e = new Event('keydown');
          
          e.keyCode = forward ? curPlayer.keyCodes[0] : curPlayer.keyCodes[1];
          if (typeof curPlayer.elem == "string") {
            elem = document.querySelector(curPlayer.elem)
          } else {
            elem = curPlayer.elem
          }
          //$(window).scrollTop(); // error on $
          
            
          e.preventDefault();
          elem.dispatchEvent(e);
          //e.preventDefault();
          //e.stopImmediatePropagation();
    //} catch(ex) {
        //alert(ex); // no error
    //}
    //e.preventDefault();
    //e.stopImmediatePropagation();
    //return false;
    
}

document.addEventListener("wheel", function(e) {
    //e.preventDefault();
  if (e.deltaX == 0 && e.deltaZ == 0) {
    if (e.deltaY > 0) {
      //e.preventDefault();
      triggerKeydown(false);
    } else if (e.deltaY < 0) {
      //e.preventDefault();
      triggerKeydown(true);
      
    }
  }
});

function injectScript(file_path, tag) {
    var node = document.getElementsByTagName(tag)[0];
    var script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', file_path);
    node.appendChild(script);
}

injectScript(chrome.extension.getURL('video-seek-mousewheel.js'), 'body');



Does navigator.mediaDevices.getUserMedia work on hybrid apps?

basic question here that I have been unable to get an answer from.

Does navigator.mediaDevices.getUserMedia work in a hybrid app?

Let me expand on this a bit.

I have a hybrid app currently that I am trying to transition to use mainly web apis, while for the most part everything is working as expected I am unable to get the camera to be accessable in an ‘app’ form.

When I run the code

navigator.mediaDevices.getUserMedia

I get back one of two errors (depending on the hybrid framework I use)

  1. Dom message stating permission is denied
  2. Dom message stating video stream is not ready

Now, item one would indicate that the user has not ‘allowed’ permissions to the actual camera but the catch is, I never get prompted to grant permissions in-app.

For number two, that would seem to indicate that the stream is already in use (have seen some stating this too can be related to permissions so I’m leaning toward that assumption)

So I guess back to the question at hand and that is, is this even possible in a hybrid app? I have seen many of similar questions with similar Dom messages but non seem to have an answer in the sense of is it even possible? I have seen some mention setting the ‘feature-policy’ headers but in the context of a hybrid app, running a localhost how or where is this set?

Anyhow, just wanted to ask and see if anyone else has been successful in doing this or do we need to use the native plugins for this?

Thanks again!

How set expiration date to an localStoarge item in Javascript?

I am working on making premium access to my website. While doing so I want the login that had set the localStorage item as 1 to expire and get deleted after a month. I searched the web, but got confused as I am still learning JavaScript and jQuery. Can you help me out with implementing the expiration? Here’s the line of code that is setting the localStorage:

localStorage.setItem('ispremium', '1');

And my website is on Blogger platform, if that matters!

Strange behavior of ^= assignment operator chains in javascript

I was playing with the XOR trick for swapping values of variables, it works fine if I write it in 3 (or 2) lines, but not when I write it in 1 line, which shows some strange behavior of the ^= operator. What is going on here? Why are the 1-line and 3-line versions not equivalent?

let a = 55, b = 31;
console.log('values to swap:', a, b);

// swap with XOR trick
a ^= b;
b ^= a;
a ^= b;
console.log('swap in 3 lines', a, b);
// output: 31 55

// swap in 1 line
a = 55; b = 31;
a ^= b ^= a ^= b;
console.log('swap in 1 line', a, b);
// output: 0 55

// swap in 2 lines
// chaining only 2 ^= operations works as expected
a = 55; b = 31;
console.log('b ^= a ^= b returns ', b ^= a ^= b);
a ^= b;
console.log('swap in 2 lines', a, b);

I tested it in Chrome and Safari, got same results.

I can’t fetch data from Firebase to Vue

I’m following a Youtube tutorial to learn more about storing data in Firebase and then interacting with it in Vue. https://www.youtube.com/watch?v=Htt8AKeF1Kw (at 5:00 is the problem I’m facing)

Basically I follow everything there but the data doesn’t show on my vue project and when I open console I see: onUnmounted is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.

I’m loading ‘animes’ from Firebase with the following code on firebase.js

export const loadAnimes = () => {
const animes = ref([])
const close = animeCollection.onSnapshot(snapshot => {
    animes.value = snapshot.docs.map(doc => ({
        id: doc.id, ...doc.data()
    }))
    onUnmounted(close)  
    return animes
})

From this then I pass it to a component

Get return from .mjs script to Python

I need to execute .mjs script about 200 times with another parameters (changableParametr):

import { Connection, PublicKey } from "@solana/web3.js";
import { Metadata } from "@metaplex-foundation/mpl-token-metadata";

const connection = new Connection("https://api.mainnet-beta.solana.com");

(async () => {
   let mintPubkey = new PublicKey(changableParametr);
   let tokenmetaPubkey = await Metadata.getPDA(mintPubkey);

   const tokenmeta = await Metadata.load(connection, tokenmetaPubkey);
   console.log(tokenmeta);
   })();

How get result to Python? I thought to use multiprocessing. Maybe expand this .mjs script to make .json file, because i need only one string from result. What is the easiest method to do this?

render page after for loop is finished node.js

I’m having an async problem, and I’ve followed a lot of articles online to try and get this issue fixed, but it hasn’t done anything.

 async function getNumOfSessionForTrainerClientList(req, res, rows, allowedToAddMoreClients, alertMessage) {
     
      let sessionData2 = []
      var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
      mysqlconn.connect(async function(err) {
          if (err) {
            console.error('Database connection failed: ' + err.stack);
            return;
          }
        for (var i = 0; i < rows.length; i++) { 
        mysqlconn.query(getNumOfSessionForTrainerClientList, [rows[i].USERNAME, req.session.username], async function(err, sessionData) {
            if (err) {
                console.log(err);
            } else {
                for (var x = 0; x < sessionData.length; x++) {
                    sessionData2.push(sessionData[x].SESSION_STATUS)
                    console.log(sessionData2)
                }


            }
           
        })
}


})
await res.render('trainerclientlist.ejs', {data: rows, trainerFirstName: req.session.firstname, trainerLastName: req.session.lastname, allowedToAddMoreClients: allowedToAddMoreClients, profilePhoto: req.session.profilePhoto, alertMessage: req.session.selectedalertmessage, sessionData: sessionData2})
console.log(sessionData2)

}

what happens is that console.log(sessionData2) happens AFTER the page is rendered, await res.render('trainerclientlist.ejs', {data: rows, trainerFirstName: req.session.firstname, trainerLastName: req.session.lastname, allowedToAddMoreClients: allowedToAddMoreClients, profilePhoto: req.session.profilePhoto, alertMessage: req.session.selectedalertmessage, sessionData: sessionData2}). How can i fix this?