How to create a new array based on the number of sub arrays in js

Here is my first array:

const withSub = [[31, 32, 34, 34], [32, 36], [12], [15, 38]];

Here is my second array:

const arr = ['f', 'b', 'c', 'd'];

The number of arrays in withSub is always equal to the number of arr arrays, while the number of subarrays in withSub may be different.

I want to create a function that generates a new array based on these two arrays in such a way that the number of each element in arr must be equal to the number of subarrays in withArr.

In this example the final array must be:

   ['f', 'f', 'f', 'f', 'b', 'b', 'c', 'd', 'd'];

How Do I Remove/Close A Div With JS?

It’s Working But When Clicked
Close Icon It’s Not Removing…..
I Don’t Know How Do I Do It!!!
Because I’m Doing Custom Alert Box And I’m Doing This…
Creating Div And Not Removed!!!

PPPLLLEEEAAASSSEEE!!!!!!!!!!!!!!!

I Want To Close/Remove The Div Element And The Div Is In The createElement(); Function…..
And I Tried W3Schools And Stack Overflow Questions……
But Still Not Working…..
I Don’t Know Why……………………………………………

Here’s My Code:

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>Custom Alert Box</title>
</head>
<body>
    <button onclick="alert('hello')">Try it</button>
    <script>
        alert = function(arguments) {
            var alertbox = document.createElement("div");
            var close = document.createElement("img");
            var text = document.createTextNode(arguments);
            alertbox.setAttribute("style", `
                border: 0.8px solid #002;
                border-radius: 4px;
                box-shadow: 0 2px 4px #454c4e;
                padding: 6px;
                height: 80px;
                `
            );
            close.setAttribute("style", `
                width: 18px;
                height: auto;
                float: right;
                `
            );
            close.setAttribute("src", "https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-close-512.png");
            close.setAttribute("alt", "close");
            close.setAttribute("onclick", alertbox.remove()); // The Close Icon That Removes/Closes The Div
            alertbox.appendChild(text);
            alertbox.appendChild(close)
            document.body.appendChild(alertbox);
        }
    </script>
</body>
</html>```

Flask request object returns None

I know that this question has been asked a few times but none of the answers seem to solve my issue. I’m trying grab some input from my html page and use it in my python/flask file. When I print out the request.form.get() variable to try and figure out what was happening it returns None (which is not what I want). I’ve tried using request.form[], request.value.get(), request.args.get(), using a XMLHttpRequest in a js file to send the data to the python file and the result was the same as when I used request.form.get() with each. I’ve also tried using separate views to receive the form data. When I tried request.form[] in my flask file and tried to make this a post request I got a "POST /truth2 HTTP/1.1" 400 -. One post said that this might be thanks to an incorrect key being used for the request object but if that’s what’s going on I’m not sure how to correct it. Any help with this is greatly appreciated and thank you for thanking the time to read this.

HTML

            <div class="P2truth_container">
              <form method="post" action="/">
                <input id="truth2" name="Player2T"></input>
                <button class="sub_btn2">Liar</button>
              </form>
            </div>
            <div>
              <form>

Python

@app.route('/truth2', methods=['POST', 'GET'])
def truth2Get():
    if request.method == 'POST':
        P2truth = request.form.get('Player2T')
        print('fixed', P2truth)
        storedP2 = session['Player2T'] = P2truth
        print(storedP2)
    return render_template('index.html', P2truth=P2truth)

Other view in Python

@app.route('/P1Liar', methods=['POST', 'GET'])
def P1Liar():

    if request.method == 'POST':
        truth2 = session.get('Player2T')
        print(truth2)
    
    elif request.method == 'GET':
        truth2 = request.form.get('Player2T')
        print(truth2)

    Next_card = session.get('New_card')
    print(Next_card)

    # truth2 = session.get('truth2')
    
    truth3 = request.form.get('name', 'truth3')
    truth4 = request.form.get('name', 'truth4')

    try:
        

        print("truth2: ", truth2)
        if truth2 != None:
            print("truth2: ", truth2)
            if truth2 != Next_card:
                print("NC: ", Next_card)
            
                print("T2: ", truth2, "Next_card: ", Next_card)
                secondhand.extend(pile)
                print("P2: ", secondhand)
                print("P1: ", firsthand)
                print("P3: ", thirdhand)
                print("P4: ", fourthhand)
                pile.clear()

                print(pile)

                return render_template('index.html', secondhand=secondhand)
        
            else:
                firsthand.extend(pile)
                pile.clear()
                print(pile)
                print("P1: ", firsthand)
                print("P2: ", secondhand)
                print("P3: ", thirdhand)
                print("P4: ", fourthhand)
                return render_template('index.html',firsthand=firsthand)
                
        if truth3 != None:
            if truth3 != Next_card:
                print(Next_card)
            
                thirdhand.extend(pile)
                print("P2: ", secondhand)
                print("P1: ", firsthand)

                print(pile)
                return render_template('index.html', pile=pile)
        
            else:
                firsthand.extend(pile)
                print(pile)
                print("P1: ", firsthand)
                print("P2: ", secondhand)
                return render_template('index.html', pile=pile)

        if truth4 != None:
            if truth4 != Next_card:
                print(Next_card)
        
                thirdhand.extend(pile)
                print("P2: ", secondhand)
                print("P1: ", firsthand)

                print(pile)
                return render_template('index.html')
        
            else:
                firsthand.extend(pile)
                print(pile)
                print("P1: ", firsthand)
                print("P2: ", secondhand)
                return render_template('index.html')
        
    except ValueError:
        return ("nothing")

Javascript

const P2Liar = document.getElementById("truth2");
const P2Liarbtn = document.querySelector(".sub_btn2")
P2Liarbtn.addEventListener("click", function(e) {
    e.preventDefault()
    console.log(P2Liar.value);

    const xhr = new XMLHttpRequest();
    const method = 'POST'
    const url = '/truth2'
  

    xhr.open(method, url)
    
    xhr.send()

});

how to pass argument in async waterfall inital function

I am using async waterfall like this

const profileRichness = () => {
    async.waterfall([
        getTargetUsers,
        filterUser,
        
    ], (err) => {
        if (err) errorlogger(uuid(), err, "email", "abc", "acc", "acd");
        else console.log('Done');
    });
}

Fn that I am calling

const getTargetUsers = (callback,condition) => {
    user.getUsers(condition, (err, result) => {
        if (err)
            callback(err);
        else {

            if (result.length)
                callback(null, result);
            else
                callback('No user found');
        }
    });
}

const filterUser = (users, callback) => {
    users = users.filter(user => {
        if (!user.age || user.profile < 80) return user;
        else return false;
    }).filter(user => user);
    callback(null,users);
}

Problem is whatever I am trying to pass in first function of waterfall it returns error that “callback is not a function” what is exactly going on

How to use filter(), map() to work with values fo an array? JavaScript

My task is:

Implement the function duplicateStudents(), which gets the variable
“students” and filters for students with the same matriculation
number. Firstly, project all elements in students by matriculation
number. After that you can filter for duplicates relatively easily. At
the end project using the following format: { matrikelnummer:
(matrikelnummer), students: [ (students[i], students[j], … ) ] }.

Implement the invalidGrades() function, which gets the variable “grades”
and filters for possibly incorrect notes. For example, in order to
keep a manual check as low as possible, the function should determine
for which matriculation numbers several grades were transmitted for
the same course. Example: For matriculation number X, a 2. 7 and a 2.
3 were transmitted for course Y. However, the function would also take
into account the valid case, i. e. for matriculation number X, once a
5,0 and once a 2,3 were transmitted for course Y.

In this task you should only use map(), reduce(), and filter(). Do not
implement for-loops.

function duplicateStudents(students) {
  return students
    // TODO: implement me
}

function invalidGrades(grades) {
  return grades
    .map((s) => {
      // TODO: implement me

      return {
        matrikelnummer: -1/* put something here */,
        grades: []/* put something here */,
      };
    })
    .filter((e) => e.grades.length > 0)
}

The variables students and grades I have in a separate file. I know it might be helpful to upload the files too, but one is 1000 lines long, the other 500. That’s why I’m not uploading them. But I hope it is possible to do the task without the values. It is important to say that the values are represented as an arrayenter image description here

xAxis doit afficher 24 heures

Bonjour,
Je suis en train de faire un graphique highcharts sur 24 heures. Je voudrais que xAxis affiche les 24 heures avec un intervalle de 1 heure qui commencerais à la date du jour à 0h et se terminerais à la date du jour + 1 jour à 0h. Mon graphique change de date de jour tout les jours à 0h. Pour déterminer la date dé début et la date de fin, j’ai créé deux variables PHP $début $fin. je pense que ça doit être possible en javascript, mais je ne sais pas comment faire. A savoir que me données sont extraites d’une base de données.

function comArr(unitsArray) {
  var outarr = [];
  for (var i = 0; i < DHT.length; i++) {
    outarr[i] = [DHT[i], unitsArray[i]];
  }
  return outarr;
}

$(function() {
  Highcharts.setOptions({
    lang: {
      months: ['Janvier', 'Fvrier', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
      weekdays: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
      shortMonths: ['Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Juin', 'Juil', 'Août', 'Sept', 'Oct', 'Nov', 'Déc'],
      decimalPoint: ',',
      resetZoom: 'Reset zoom',
      resetZoomTitle: 'Reset zoom  1:1',
      contextButtonTitle: 'Menu contextuel du graphique',
      viewFullscreen: 'Voir le graphique en plein écran',
      downloadPNG: "Télécharger au format PNG image",
      downloadJPEG: "Télécharger au format JPEG image",
      downloadPDF: "Télécharger au format PDF document",
      downloadSVG: "Télécharger au format SVG vector image",
      printChart: "Imprimer le graphique",
      loading: "Chargement en cours...",
      rangeSelectorFrom: "Du",
      rangeSelectorTo: "Au"
    }
  });

  chart = new Highcharts.Chart({
      chart: {
        renderTo: 'temperature',
        zoomType: 'x',
        type: 'spline',
        marginRight: 10,
        marginBottom: 60,
        plotBorderColor: '#346691',
        plotBorderWidth: 1,
      },

      title: {
        text: '<?php  echo " Radiation solaire du ". $date; ?>',
        align: 'center',
      },

      subtitle: {
        text: 'Source : Météo Jarny',
        align: 'center',
      },

      credits: {
        text: '© Météo Jarny',
        href: ''
      },

      legend: {
        align: 'center',
        verticalAlign: 'center',
        x: 0,
        y: 515,
        borderColor: 'royalblue',
        borderWidth: 1,
        borderRadius: 5,
        backgroundColor: {
          linearGradient: [0, 0, 0, 20],
          stops: [
            [0, '#FFFFDD'],
            [1, '#CAEEFF'],
          ]
        },
        layout: 'horizontal',
        shadow: true,
      },

      time: {
        getTimezoneOffset: function(timestamp) {
          var zone = 'Europe/Paris',
            timezoneOffset = -moment.tz(timestamp, zone).utcOffset();
          return timezoneOffset;
        },
        timezone: 'Europe/Paris',
        //timezoneOffset:0
        useUTC: false,
      },

      xAxis: {
        type: 'datetime',
        tickInterval: 3600 * 1000,
        alternateGridColor: '',
        gridLineColor: '#BDBDBD',
        gridLineWidth: 0.5,
        startOnTick: false,
      },

      yAxis: {
        title: {
          text: null,
        },
        labels: {
          formatter: function() {
            return this.value + ' W/m²';
          },
        },
        plotLines: [{
          value: 0,
          width: 1.5,
          color: '#FFFF00'
        }]
      },

      tooltip: {
        animation: true,
        shared: true,
        crosshairs: true,
        enabled: true,
        followPointer: true,
        split: true,
        valueDecimals: 1,
        borderColor: 'royalblue',
        borderWidth: 1,
        backgroundColor: '#2E2E2E',
        dateTimeLabelFormats: {
          day: "%A %e %B %Y",
          hour: "%A %e %B %Y à %Hh %Mmn",
          millisecond: "%A %e %B %Y à %H:%M:%S.%L",
          minute: "%a %e %B %Y à %Hh %Mmn",
          month: "%B %Y",
          second: "%A %e %B %Y à %Hh %Mmn %Ss",
          week: "Semaine depuis %A %e %b %Y",
          year: "%Y",
        },
        headerFormat: '<table cellspacing="2" cellpadding="0" style="font-size:12px"><tr><td colspan="4" class="TD_Header_Tooltip">{point.x:%A %e %B %Y à %Hh %Mmn}</td></tr>',
        xDateFormat: "%A %e %B à %Hh %Mmn",
      },

      plotOptions: {
        series: {
          marker: {
            enabled: false
          }
        }
      },

      series: [{
        name: 'Radiation solaire',
        type: 'areaspline',
        color: '#FF0000',
        lineWidth: 0.5,
        fillColor: {
          linearGradient: [0, 0, 0, 250],
          stops: [
            [0, 'rgb(255, 0, 0)'],
            [1, 'rgb(255,255,0)']
          ]
        },
        data: comArr(solar),
        tooltip: {
          pointFormatter: function() {
            var s = '<tr><td align="left"><br /><span style="color:' + [this.color] + '">u25CF </span>' + [this.series.name] + '</td>'
            s = s + '<td align="center">: </td>'
            s = s + '<td align="right"><b>' + Highcharts.numberFormat(this.y, 1, ",", " ") + '</b></td>'
            s = s + '<td align="left"> W/m²</td></tr>';
            return s;
          },
        },
      }, ]
    },

    function(chart) { // on complete
      chart.renderer.image('', 8, 8, 102, 50)
        .add()
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Show Client Added According to Date Barchart Chart.js (I need perfect code optimization for it )

I need proper solution as the code that I have written is seems to be hard coded as multiple filter method is use for same scenario. Please help me to sort out as I am new to react. The output is dynamically rendered in bar chart.

 const ClientActivityChart = () => {
      const [clients, setClients] = useState([])
      const getClients = async () => {
        try {
          const res = await fetch('http://localhost:4000/api/addClients', {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
            },
            credentials: 'include',
          })
          const data = await res.json()
          console.log(data)
          const filterJan = data.filter((item) => {
            let date = new Date(item.date)
            const month = date.toLocaleString('default', { month: 'long' })
            return month === 'January'
          })
          const filterFeb = data.filter((item) => {
            let date = new Date(item.date)
            const month = date.toLocaleString('default', { month: 'long' })
            return month === 'February'
          })
          const filterMarch = data.filter((item) => {
            let date = new Date(item.date)
            const month = date.toLocaleString('default', { month: 'long' })
            return month === 'March'
          })
          const filterApril = data.filter((item) => {
            let date = new Date(item.date)
            const month = date.toLocaleString('default', { month: 'long' })
            return month === 'April'
          })
         const filterJune = .........

          var dataItem = [
            filterJan.length,
            filterFeb.length,
            filterMarch.length,
            filterApril.length,
            filterMay.length,
            filterJune.length,
            filterJuly.length,
            filterAug.length,
            filterSep.length,
            filterOct.length,
            filterNov.length,
            filterDec.length,
          ]
          console.log(dataItem)
          setClients(dataItem)
        } catch (err) {
          console.log(err)
        }
      }
      useEffect(() => {
        getClients()
      }, [])

Here’s a output.
enter image description here

How to properly use response.end () in Node JS when reading a file asynchronously

I am to Node JS decided to create a simple routing where the file is read based on the url.

My problem is that I don’t quite understand how to use response.end correctly.

This is my code without using response.end

http
  .createServer(function (req, res) {
    if (req.url === "/students") {
      fs.readFile("./templates/students.html", function (err, data) {
        if (!err) {
          res.write(data);
        }
      });
    } else {
      res.write('Page not found.')
    }
  })
  .listen(3000);

When I apply response.end inside a file read, then the else condition with an empty url stops working (as expected)

enter image description here

Otherwise, only the else condition works, and reading the file does not work when added at the end of url /students

enter image description here

This has always been a problem for me, I don’t understand how to use response.end correctly. It’s always confused me. How can I solve this problem?

How to plot SineWave using y(t)=Asin(2pi ft+phi ) this formula..?

I am new in java world.I am trying to plot sine wave graph and I have written code too.My code is giving output but When my frequency value is 50 it form only 1 or 2 wave and when my frequency is 4 or 10 it form many waves .how to resolve this problem please help me.here is my code.
After the execution i want to save the entered value in excel file please help me to solve this problem.

here`public class SineFrame extends javax.swing.JFrame{


 
 //1d array to store the amplitude data, time data is represented or derived from the index of array
 double[] amplitude;
 
 int center;
 
 double H_STEP_SIZE = 1d;
int t=101;
int amp=100;
double phase=0.07;
int hSize=600;
int vSize=600;
int frequency=100;
 
 
 public SineFrame(){
   
  //this.t = t;
 // this.amp = amp;
  //this.phase = phase;
  //to check integer overflow when multiplied with horizontal step size
  amplitude = new double[t*(int)H_STEP_SIZE < t?Integer.MAX_VALUE:t*(int)H_STEP_SIZE]; 
  setDefaultCloseOperation(EXIT_ON_CLOSE);
  center = vSize/2;
  setSize(hSize,vSize);
  //calculate the co-ordinates based on input params to draw the wave
  calculateCoords(t,amp,phase,frequency);
 }
 

 private void calculateCoords(int t, int amp, double phase,double frequency) {
  for(int i=0;i<amplitude.length;i++)
   amplitude[i] = amp * Math.sin(2*Math.PI*frequency*t+phase*(i/H_STEP_SIZE));  
 }

 @Override
 public void paint(Graphics g){
        Graphics2D g2 = (Graphics2D) g;
        Point2D prev,cur;
        double y;
        Line2D lin;
        Font font =  new Font("Times", Font.BOLD, 25);
        FontRenderContext frc = g2.getFontRenderContext();
      //  TextLayout layout = new TextLayout("A = "+amp+"; Phase = "+Phase+"; t = "+t, font, frc);
        //layout.draw(g2, 10f, 50f);        
        cur = new Point2D.Double(10,center);
        //iterate thru' the calculated co-ordinates and draw lines between adjacent points
        //to generate the sine wave
        for(int i=0;i<amplitude.length;i++){
         prev = cur;
         y = getCoOrdsFromAmplitude(amplitude[i]);
         cur = new Point2D.Double(10+(i/H_STEP_SIZE), y);
         System.out.println("Co-ordinates--{x="+cur.getX()+"},{y="+cur.getY()+"}");
         lin = new Line2D.Double(prev,cur);
         g2.draw(lin);
        }

        
 }
        
 private double getCoOrdsFromAmplitude(double amp){
  return center + amp;
 }
 
/* public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SineFrame().setVisible(true);
            }
        });
 }
 */
}

What to use: Provide canvas frontend using backend api

I am thinking about a web page providing some 2d-like animations based on backend data.
The animations/action change frequently based on the backend data. .

Currently I am thinking about using React and combine with canvas
So my thinking was to provide the data via some end point as json and using react to build the frontend.But using canvas in react found me only a few links.
[1]: https://thibaut.io/react-canvas-components

The most similar question I found on stack was this
[2]: Mixing HTML5 Canvas and Python. But the answers are almost a decade old. Can someone provide me some basic approach / links so I am not starting totally off?

Thank you in advance!

cheers! hobo

Store form in localstorage, retrieve it later for submit

In a wordpress website I want that when someone fills a product form (select attributes etc) and clicks buy now, if is not logged in then he is redirected to login form. On succesfull login I want to get the submitted form contents from localstorage, fill the form and then submit the form automatically.

Is that possible?

I found that I can store the submitted form like this (but how I can refill the form automatically?):

$(document).ready(function()    {  
    $('form').submit(function(e) {    
        e.preventDefault();
        var formFields = $(this).serialize();
        localStorage.setItem('myForm', formFields);    
        //data = localStorage.getItem('myForm');  //retrieve it later
     });
});

Prevent SQL Injection on search bar, Using Node.js and mysql

I have already tried many ways to prevent it using escape method, name-placeholder, node-mysql etc, or even look at similar post here in stackoverflow but none seems to help. I did my own research on ORM, parameterized statements and lots of websites but still not working. Here is my code.

module.exports.getOneDesignData = function (recordId) {
    console.log('getOneDesignData method is called.');
    console.log('Prepare query to fetch one design record');
    userDataQuery = `SELECT file_id,cloudinary_file_id,cloudinary_url,design_title,design_description 
        FROM file WHERE file_id= ?` + recordId;

    return new Promise((resolve, reject) => {
        pool.getConnection((err, connection) => {
            if (err) {
                console.log('Database connection error ', err);
                resolve(err);
            } else {
                connection.query(userDataQuery, (err, results) => {
                    if (err) {
                        reject(err);
                    } else {
                        validationFn.sanitizeResult(results)
                        resolve(results);
                    }
                    connection.release();
                });
            }
        });
    });

}

Flaky endpoints with Next.js app deployed to Vercel

I deployed a next.js app to Vercel and am experiencing flaky endpoints.

The 5 endpoints are defined in pages/api/... and work perfectly in localhost – and are also called infrequently in localhost.

In the deployment, the endpoints sometimes returns a Internal error, status 500. I am using middleware and am wondering if that could be causing the issue.

import cache from 'express-redis-cache';

const c = cache();

const run = (req, res) => (fn) => new Promise((resolve, reject) => {
  fn(req, res, (result) =>
      result instanceof Error ? reject(result) : resolve(result)
  )
})


const handler = async (req, res) => {
  const middleware = run(req, res);
  await middleware(cors());
  await middleware(c.route({
      expire: 30
  }))
  /** validate req type **/
  if (req.method !== 'GET') {
    res.status(400).json({});
    return;
  }
...

I also tried removing the express-redis-cache for one of the endpoints:

import Cors from 'cors';
import axios from 'axios';

// Initializing the cors middleware
const cors = Cors({
    methods: ['GET', 'HEAD'],
})

function runMiddleware(req, res, fn) {
    return new Promise((resolve, reject) => {
      fn(req, res, (result) => {
        if (result instanceof Error) {
          return reject(result)
        }

        return resolve(result)
      })
    })
  }

const handler = async (req, res) => {
    console.log('raised call', req);
    await runMiddleware(req, res, cors);

But they are all flaky — seems like every other call works. Its between status 500 and it working.

Another followup to this is – I used react hooks to make sure API calls were only made when necessary. Is there a reason why so many repeat calls are being made when these calls are not made on localhost? For instance, I have 4 endpoints that only need to get called once each per page load but in the deploy they are getting called many times.

How can ı do vue 3 compositon api router refresh page

After confirming in vue 3 compositon api

router.push('/IssueList');

Here, I want my and components to refresh when they come to the IssueList page.

I’m redirecting to the page, but it doesn’t refresh the issuelist page. How can I do that?

The codes on my IssueList page are as follows.

<template>
  <div>
    <div class="card">
      
      <h5>Konu Listesi</h5>
      <Button label="Yeni Konu Oluştur" class="p-button-success p-button-outlined mb-2" icon="pi pi-plus"
              @click="newIssue"></Button>
      <TabView ref="tabview1">
        <TabPanel header="Bana Gelenler">
          <issue-incoming></issue-incoming>
        </TabPanel>
        <TabPanel header="Benim Yazdıklarım">
          <issue-send  ></issue-send>
        </TabPanel>
      </TabView>
    </div>
  </div>

</template>

ask from the command prompt to input data to all the entities, and it should give the option to add more than one entry at a time

<script>
  class Course {
    constructor(title, stream, type, start_date, end_date) {
      this.title = title;
      this.stream = stream;
      this.type = type;
      this.start_date = start_date;
      this.end_date = end_date;
      }
   }                                                                                                                                                                                                                                                                                        
  let newCourseInstance = new Course(
    window.prompt("Title:"),
    window.prompt("Stream:"),
    window.prompt("Type:"),
    window.prompt("Start date:"),
    window.prompt("End date:")
    );

Hello everyone!! i just want to ask something about an assignment that i should do. The application must ask from the command prompt to input data to all the entities, and it should give the option to add more than one entry at a time. Do you know how to do this iterration? Thank you for your time!!