Show only those percentage in piechart which is greater than 5% in Chart JS

I am learning web dev and chart js, and working with pie chart. my chart looks like below; As we can see smaller percentage value is not at all visible and is making our website bad. how can we eliminate smaller percentage. I am attaching my work how I got below pie chart. kinly looking for help. Thanks.

 

<!DOCTYPE html>
<html>
  <head>
    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
     -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
  </head>
  <body>
  <canvas id="myChart1" width="90" height="90" style="width:100%;max-width:650px"></canvas>
  <script>
        function getColors(length) {
        let pallet = ["#0074D9", "#FF4136", "#2ECC40", "#FF851B", "#7FDBFF", "#B10DC9", "#FFDC00", "#001f3f", "#39CCCC", "#01FF70", "#85144b", "#F012BE", "#3D9970", "#111111", "#AAAAAA"];
        let colors = [];
  
        for (let i = 0; i < length; i++) {
          colors.push(pallet[i % (pallet.length - 1)]);
        }
  
        return colors;
      }
      var xValues = ['Multimeter', 'UniBox', 'Toby', 'Cables', 'Test','nokia','samsung','Jio','honda'];
      var yValues = [2, 100, 223, 84, 197,3,8,7,50];
      var barColors = getColors(xValues.length);
      var ctx = document.getElementById("myChart1").getContext('2d');
     var myChart = new Chart(ctx, {
     type: 'pie',
     data: {
      labels: xValues,
      datasets: [{
        backgroundColor: barColors,
        data: yValues
      }]
     },
    options:{
      tooltips: {
        enabled: true
      },
      plugins: {
        datalabels: {
          formatter: (value, ctx) => {
    
            let sum = ctx.dataset._meta[0].total;
            let percentage = (value * 100 / sum).toFixed(2) + "%";
            return percentage;
    
    
          },
          color: '#fff',
        }
      },
      "legend": {
        "display": true,
        "labels": {
          "fontSize": 20,
        }
      },
      title: {
        display: true,
        fontColor: 'rgb(255, 0, 0)',
        fontSize: 25,
        text: "Current Inventory Received"
      }
    }
  });
  </script>
</body>

</html>

enter image description here

The reduce fuction sum isn’t reducing the elements in an array to a single element?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p id="demo"></p>
    <script language="javascript" type="text/javascript">
        let newton = ["1"," 2"," 3"," 4"," 5"];

        let newton2 = newton.reduce(sum);

        function sum(total,value){
            return(total+value);
        }
        document.getElementById("demo").innerHTML = newton2;
    </script>
</body>
</html>

So…I have used the reduce function (sum) and its not summing the elemenets in the array and displaying it in a single element, Rather its displaying the elements in the array again.

i want to get data from async function butt it returns me a promise [duplicate]

first function used to get data form django server and return to second fucnction butt it return promise

async function gname(sender){
      const u={
        user:sender,
    };
    
    const s=await Axios.post("http://127.0.0.1:8000/api/getname",u).then((res)=>{return res.data});
    return s;
    }

second function

    function getName(sender){
     const nme=gname(sender);
     return nme;
    }

now the second function should return data but it returns promise i want to show this name inside a div butt it shows up an error!

NextJS – Flask stream webcam through openCV

I would like to be able to show the user’s webcam with some openCV features (face recognition…) when they go on my NextJS website.

I tried to use a video stream that I render in an image component in the frontend :

<img src={`http://localhost:4001/video_feed/${id}`} alt="video" />
from flask import Flask, Response
from flask_cors import CORS

import cv2

app = Flask(__name__)
CORS(app, support_credentials=True)


def gen(cam):
    while True:
        success, frame = cam.read()  # read the camera frame
        if not success:
            break
        else:
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()
            yield (b'--framern'
                   b'Content-Type: image/jpegrnrn' + frame + b'rn')  # concat frame one by one and show result


@app.route("/", methods=["GET"])
def index():
    return "<p>Server is running!</p>"


@app.route("/video_feed/<id>", methods=["GET"])
def video_feed(id):
    cam = cv2.VideoCapture(0)

    return Response(gen(cam), mimetype="multipart/x-mixed-replace; boundary=frame")


if __name__ == "__main__":
    app.run(debug=True, host="localhost", port=4001, threaded=True)

The problem is that it only shows my camera to the users (because I am running the flask app on my computer).

I would like it to get the incoming user’s webcam, play with openCV and return the modified video.

Is it possible ?

I also tried to use socket.io but it looked like I couldn’t go over 20 FPS which is far away from what I need (cause i wan’t the users to see themselves on the website clearly).

I want to do something like this on my website (real time image recognition) :

What I want to do

Thanks 😉

How to pass the onClick() event to a child component from a button in the parent component in React?

Let’s say I have two components Component1 and Component2. I have a button in Component1.

const Component1 = () => {
    return(
        <div>
        <button onClick={()=>someExportFunc()}>Export</button>
        <Component2 />
    </div>
    )
}

My Component2.jsx is something like this.

import {ChartComponent} from '@xyz/charts';

    
const Component2 = () => {
    let chartInstance = new ChartComponent();

    return (
                <ChartComponent
                id='chart1'
                ref={chart = chartInstance => chart}

                >

                </ChartComponent>
        )

}

Now the function someExportFunc() is defined inside the {ChartComponent} being imported in Component2.jsx.

Had I used the button inside Component2, it would have worked simply. As in,

import {ChartComponent} from '@xyz/charts'

    
const Component2 = () => {
    let chartInstance = new ChartComponent();

    return (
                <button onClick={()=>someExportFunc()}>Export</button>
               <ChartComponent
                id='chart1'
                ref={chart = chartInstance => chart}

                >

                </ChartComponent>
        )

}

But how can I make it work as a button in Component1?

I am guessing it has something to do with defining state of the button and then passing the state down, but I don’t exactly understand how the state of a button works. onClick() should be some instantaneous boolean, isn’t it? By instantaneous, I mean it would change as soon as the ‘click’ is over.

why i’m not getting any data from the cb function?

i’m new to react and i have a project that i need to do for school , but i still dont know how to access the cb function , nothing appears at the console

const App = () => {

  freshdesk.createTicket(
    {
      name: "tt",
      email: "[email protected]",
      subject: "tt",
      description: "test description",
      status: 2,
      priority: 1,
    },
    function cb (err, data) {
      console.log(err || data);
    }
  );  
 


  return (
     <Text>hello world</Text>
  );
};

export const run = render(
  <SpaceSettings>
    <App />
  </SpaceSettings>
);

tom-select how to keep order when using drag and drop plugin

I’m using tom-select for multiple select field with drag & drop plugin

Options provided to the select are alphabetically sorted, everything works fine when I choose some items, they are saved in db in the order I’v sorted them manually, as expected. Problem is that when I reload the page those selected items are shown in alphabetical order anyway. Is there any way to sort them custom way ?

how do i add a number limit in an input field?

How can i have a number limit? im trying to make it so that you can only type the number 1-100 in “app-benutzer” and 1-15 in “backend-benutzer” also is there a way to display these numbers in the input field without typing them so it would show the user that you can only type the number from 1-15.

html:
 <body>
    App-Benutzer: <input type="number" min="1" max="100" class='appuser'></input><br>
    Backendbenutzer: <input type="number" min="1" max="15" class='backenduser'></input><br>
    <button class='calcit'>Berechnen</button><br>
    <span class='summe'>0.00</span><br>
    <script src="./app.js"></script>
  </body>
js:
const btncalc = document.querySelector('.calcit');
const summetext = document.querySelector('.summe');


btncalc.addEventListener('click', function(){
    var backendanzahl= document.getElementsByClassName("backenduser")[0].value;

    var appanzahl= document.getElementsByClassName("appuser")[0].value;
    var mytext="Anzahl der Summe:" + (+backendanzahl * 35 + +appanzahl * 7.5) ;
    summetext.textContent = mytext;
});

Can I change a value of an Input using the innerHTML of the lable above?

I need to change the value of an input that is generated dynamically and its id attribute value is changing, so I can’t access it by its id. for some reasons, I can’t add new attribute or class to it, so there is no fixed selector I can use. there are multiple inputs so I wouldn’t be able to use [input] selector.

can I change the value of the input if the only thing I have fixed is the text of the label above it? which in my case is Fixed text?

<div>
  <label>Fixed text</label>
  <input type="date" id="287" />
</div>

React table not rendering

I have a function that creates a table like this

//Generate 1st part of table
const tbl1 = [
            <th key={`someKey`} className="title">
                sample
            </th>,
            <td></td>,
            <td></td>,
            <td></td>
            ...
        ];

// Generate 2nd part of table 
const tbl2= [/*same as 1st table*/]

// Generate 3rd part of table 

const tbl3= [/*same as 1st table*/]


return (
        <table id="table">
            <tr>{tbl1}</tr>
            <tr>{tbl2}</tr>
            <tr>{tbl3}</tr>
        </table>
        );


The table is not rendering giving me this error

Objects are not valid as a React child (found: object with keys {value}). If you meant to render a collection of children, use an array instead.

I am not sure where is the object that I inserted as a react child.

Using uPlot with svelte, does not render

I’m struggling to make uPlot work with svelte. I can’t find any minimal working example, so I’m crafting one myself and it does not render. Repro goes as follows:

npm create svelte repro

# y
# skeleton
# yes TypeScript
# yes ESLing
# yes Prettier
# yes Playwright

npm install
npm i uplot
npm run dev -- --open

And then I modify index.svelte to contain the following (best I could come up with, thanks to this answer In SvelteKit, how do you conditionally include a `<script>` block in `app.html`?)

<script lang="ts">

    import { browser } from '$app/env';
    import { onMount } from 'svelte';
    import "uplot/dist/uPlot.min.css"

    let uPlot;

    function redraw(uPlot) {

        if(!uPlot) return;

        let data = [new Float32Array([1, 2, 3, 4, 5]), new Float32Array([1, 3, 2, 5, 4])];

        const opts = {
            width: 600,
            height: 300,
            scales: {x: {time: false}},
            series: [{label: "x"}, {label: "y", stroke: "red"}],
        };

        new uPlot(opts, data, document.getElementById("uPlot"));
    }

    onMount(async () => {

        if (browser) {
            const uplotModule = await import('uplot');
            uPlot = uplotModule.default;
            console.log("uplot loaded", uplotModule, uPlot);
        }
    })

    $: redraw(uPlot)

</script>

<h1>Welcome to SvelteKit</h1>
<div id="uPlot"></div>

It does not render the plot 🙁 What am I missing?

Function doesn’t work when ipcRenderer is used

this is the first time I’m using electron so these could be some dumb questions but I didn’t find anything online about it.

So, I have this in my index.js file

<head>
    <script defer src="generate.js"></script>
</head>
<body>
    <label for="role">MY LABEL</label>
        <select name="abc" id="abc" class="abc">
            <option value="0"></option>
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
            <option value="4">Option 4</option>
            <option value="5">Option 5</option>
     <button onclick="generate()">Generate</button>
</body>

and this in my generate.js file

const ipcRenderer = require('electron').ipcRenderer;

const generate = () => {
    ipcRenderer.send('generate', document.querySelector('.abc').value)
}

In theory, whenever someone clicks on the button the generate function in the .js file should run, but it doesn’t. I tried some testing and, removing ipcRenderer, the function get’s highlighted (meaning it is in use) and the function works.
How do I solve this? If some other code is needed I’ll share it.

EDIT: When removing ipcRenderer, I tried the code using alert