Next.js maintain route when navigating between screens

I have the following problem in Next.js. Im building a Dashboard.
This would be somewhat the root route:

/dashboard/

Here you can select from different Stores to get to the Dashboard of the different stores.
Now when I click on one of the stores, this is my route:

/dashboard/store/%STORE_ID%/

%STORE_ID% is something like 3iHnkdnfkD and I need it to communicate with my backend. Basically I use the ID as one of the keys to my database and wont to get it from the route when clicking on a page. Now, the route goes on… Lets say I have different products and each of them has an ID again:

/dashboard/store/%STORE_ID%/product/%PRODUCT_ID%

When navigating between these individual products, the %PRODUCT_ID% changes obviously and with it the route.
So, I have this route: /dashboard/store/3iHnkdnfkD as example;
The page would now consist of a table where I can click on the products to get a detailed page.
So I would use a NextLink and when I click on one of the products get its id to onclude in the route:

<NextLink href={`/dashboard/store/%STORE_ID%/product/${id}`}>
  <MyUnrelevantButton />
</NextLink>

Now, heres my problem: I need to know the STORE_ID% to navigate to the product, since otherwise, I would lose ref of the store. I know I would be able to retrieve the STORE_ID% from the route and than just pass it in again, but this is redundant and with more than a few NextLinks quite a lot of work. Is there any way to tell Next: Use the route I have right know and just add /product/%PRODUCT_ID% to it

Problem with JQuery Mobile button with onclick

I’m using jquery mobile on a raspberry pi with 7″ Touch display and chromium browser in kiosk mode.

I have serveral Buttons on my page

<button class="ui-btn" onclick="window.location.replace('index.html');">Seite neu laden</button>
<button class="ui-btn" onclick="system('reboot');">System neu starten</button>
<button class="ui-btn" onclick="system('shutdown');">System herunterfahren</button>
<button class="ui-btn" onclick="restart('zway');">Z-Way Server neu starten</button>
<button class="ui-btn" onclick="restart('homebridge');">Homebridge Server neu starten</button>

If i touch the first button the page will be reloaded, but if i touch the last button,
which should call a function, nothing happen.

If i replace the “onclick” (reload the page) from the first button with the “onclick” from the last button (call restart(‘homebridge’)), my function will be called and the homebridge-server will be restarted.

I dont really understand this behaviour. I also tried “ontouchstart” instead of “onclick”.

Do i miss something?

node server not running in browser or in postman in terminal its fine

this is the server.js code

require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const cookieParser = require('cookie-parser')


const app = express()
app.use(express.json())
app.use(cors())
app.use(cookieParser())


//Routes
app.use('api', require('./routes/authRouter'))

const URI = process.env.MONGODB_URL
mongoose.connect(URI, {
    useCreateIndex: true,
    useFindAndModify: false,
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err => {
    if(err);
    console.log('Connected to mongodb')
})


const port = process.env.PORT || 5000
app.listen(port, ()=> {
    console.log('server up and running', port)
})

authRouter code

const router = require('express').Router()
const authCtrl = require('../controllers/authCtrl')

router.post('/register', authCtrl.register)

router.post('/login', authCtrl.login)

router.post('/logout', authCtrl.logout)

router.post('/refresh_token', authCtrl.generateAccessToken)


module.exports = router

authCntrl code

const Users = require('../models/userModel')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')

const authCtrl = {
     register: async (req,res) => {
         try {
            const { fullname, username, email, password, gender } = req.body
        console.log(req.body);
        res.json({msg: 'registered'})
     } catch (err) {
        return res.status(500).json({msg: err.message})
     }
 },
 login: async (req,res) => {
    try {
       
    } catch (err) {
       return res.status(500).json({msg: err.message})
    }
},
logout: async (req,res) => {
    try {
       
    } catch (err) {
       return res.status(500).json({msg: err.message})
    }
},
generateAccessToken: async (req,res) => {
    try {
       
    } catch (err) {
       return res.status(500).json({msg: err.message})
    }
}
}

 module.exports = authCtrl

auth router code

const router = require('express').Router()
const authCtrl = require('../controllers/authCtrl')

router.post('/register', authCtrl.register)

router.post('/login', authCtrl.login)

router.post('/logout', authCtrl.logout)

router.post('/refresh_token', authCtrl.generateAccessToken)


module.exports = router

package.json

{
  "name": "web",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "dev": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.0.0",
    "cookie-parser": "^1.4.5",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.11.13"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }
}

the thing is that everything seems like its okay but when i open localhost in the browser it doest show
and in postman too
in the terminal it says

server up and running 5000
Connected to mongodb

could be that the dependencies that im using are a bit outdated but im trying to follow a tutorial that was made in January of this year, so i dont want to change the dependencies or update them.

value are not set by the calling function in mocha framework

i have written random function to set some string values in accountname and this is in utilities/random.js. when I try calling this function in my test/sample.js this function is not setting the value of account name

random function

export const randomString = (n) => {
    let str = 'abcdefghijklmnopqrstuvwxyz9876543210';
    let tmp = '',
        i = 0,
        l = str.length;
    for (i = 0; i < n; i++){
        tmp += str.charAt(Math.floor(Math.random() * l));
    }
    return tmp;
}

calling it in test/sample.js

import { randomNum, randomString } from '../utils/random';     
let accountname = randomString(length);

enter image description here

How can I redraw markers in the GoogleMapReact component?

I have a problem with my react google maps component. Even when I switch between different routes and fetch new data, my component won’t refresh markers. I tried to create a state and change it in useEffect to see if the map is rendered again when changing events and it does. So I assume that something needs to be done with the renderMarkers function but I have no idea what, though. I tried console logging markers and they’re displayed only once during application’s first run.

Parent component:

const EventsPage: React.FC<Props> = ({ page_filter }) => {

    const { data: Events_data, isFetching } = useGetEventsQuery(page_filter.toLowerCase());

    return (
        <div className={classes.Main_container}>
            <h2 className={classes.Header}>
                {page_filter} Events:
            </h2>
            <Map data={Events_data} />
            <div className={classes.Events_container}>
                {isFetching && <Loader />}
                {Events_data?.length === 0 ?
                    (
                        <h2>No Events found in this category.</h2>
                    ) :
                    (
                        <Events data={Events_data} />
                    )
                }
            </div>
        </div>
    )
}

Map component (child):

const Map: React.FC<Props> = ({ data }) => {
  const events = data?.events;
  const center = { lat: 51.107, lng: 17.04 };
  const zoom = 14;

  const renderMarkers = (map: any, maps: any) => {
    events?.map(event => {
      const pos = { lat: Number(event.lat), lng: Number(event.lng) };
      let color = "";
      let path = "";

      if (event.type === "Basketball") {
        color = "#dd7e01";
        path = PathType.BASKETBALL
      } else if (event.type === "Volleyball") {
        color = "#2160d4";
        path = PathType.VOLLEYBALL
      } else if (event.type === "Football") {
        color = "#30bf1c";
        path = PathType.FOOTBALL
      } else if (event.type === "Chess") {
        color = "#a88253";
        path = PathType.CHESS
      } else if (event.type === "Tennis") {
        color = "#ceff19";
        path = PathType.TENNIS
      }

      let marker = new maps.Marker({
        position: pos,
        map,
        icon: {
          path: path,
          fillColor: color,
          fillOpacity: 1,
          strokeColor: color,
          scale: 1.15
        },
        title: `${event.type} by ${event.creator.username}. People: ${event.number_of_people}/${event.people_needed}`
      });

      console.log(marker);
    })
  }

  return (
    <div className={classes.Map_container} id={center.toString()}>
      <GoogleMapReact
        bootstrapURLKeys={{ key: {API.key} }}
        defaultCenter={center}
        center={center}
        defaultZoom={zoom}
        margin={[50, 50, 50, 50]}
        // onChange={}
        // onChildClick={}
        onGoogleApiLoaded={({ map, maps }) => renderMarkers(map, maps)}
        options={{
          backgroundColor: "#282C35",
          styles: [
            { elementType: "geometry", stylers: [{ color: "#282C35" }] },
            { elementType: "labels.text.stroke", stylers: [{ color: '#242f3e' }] },
            { elementType: "labels.text.fill", stylers: [{ color: "#746855" }] },
            {
              featureType: "administrative.locality",
              elementType: "labels.text.fill",
              stylers: [{ color: "#E4AD38" }],
            },
            {
              featureType: "transit",
              elementType: "labels.icon",
              stylers: [{ visibility: "off" }]
            },
            {
              featureType: "road",
              elementType: "labels.icon",
              stylers: [
                { visibility: "off" }
              ]
            },
            {
              featureType: "poi",
              stylers: [{ visibility: "off" }],
            },
            {
              featureType: "road",
              elementType: "geometry",
              stylers: [{ color: "#191919" }],
            },
            {
              featureType: "road",
              elementType: "geometry.stroke",
              stylers: [{ color: "#212a37" }],
            },
            {
              featureType: "road",
              elementType: "labels.text.fill",
              stylers: [{ color: "#9ca5b3" }],
            },
            {
              featureType: "road.highway",
              elementType: "geometry",
              stylers: [{ color: "#746855" }],
            },
            {
              featureType: "road.highway",
              elementType: "geometry.stroke",
              stylers: [{ color: "#1f2835" }],
            },
            {
              featureType: "road.highway",
              elementType: "labels.text.fill",
              stylers: [{ color: "#f3d19c" }],
            },
            {
              featureType: "transit",
              elementType: "geometry",
              stylers: [{ color: "#191919" }],
            },
            {
              featureType: "water",
              elementType: "geometry",
              stylers: [{ color: "#17263c" }],
            },
            {
              featureType: "water",
              elementType: "labels.text.fill",
              stylers: [{ color: "#515c6d" }],
            },
            {
              featureType: "water",
              elementType: "labels.text.stroke",
              stylers: [{ color: "#17263c" }],
            },
          ]
        }}

      />
    </div>
  )
}

Can Playwright do conditional test based on the browser that is running it?

I am learning how to use Playwright coming from a Selenium and Cypress background and testing out the tool to see how it performs on a simple test:

test.describe('IMDB:', () => {
    const movieName = 'Forrest Gump';

    await page.goto('https://www.imdb.com/');

    await page.fill('#suggestion-search', movieName);

    expect(await page.textContent('data-testid=search-result--const')).toContain(movieName);
  });
});

It simply goes to IMDB, searches for a movie, and then asserts the movie is found.

I have also created a config file in which I have defined that I want to use multiple browsers:

const config: PlaywrightTestConfig = {
  timeout: 30000,
  use: {
      headless: false
  },
  projects: [
    {
      name: 'Desktop Chromium',
      use: {
        browserName: 'chromium',
        viewport: { width: 1280, height: 720 },
      },
    },
    {
      name: 'Desktop Firefox',
      use: {
        browserName: 'firefox',
        viewport: { width: 1280, height: 720 },
      }
    },
     {
      name: 'Mobile Chrome',
      use: devices['Pixel 5'],
    },
  ],
};

export default config;

However, when I run the test, due to the search bar being hidden behind a button on the mobile site. The Mobile Chrome test fails.

Is there a way I can do conditional testing to say if a particular device is being used, perform an extra step?

android webview not calling only peerjs functions

I am trying to use peerjs in android vie webview, but the problem is it not working, when I debugged and tried different approaches I got to know that normal js functions work with no problem, the problem only when I call a function which includes peerjs

permissions i took in manifest file

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

MAINACTIVITY

here are two buttons 1 calls to simple js function named callJs and other one calls peerjs function named testweb

public class MainActivity extends AppCompatActivity {

@SuppressLint("JavascriptInterface")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    WebView webView = findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);
    // Setting Allowed JS Bullet Window
    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

    webView.setWebChromeClient(new WebChromeClient(){
        @Override
        public void onPermissionRequest(PermissionRequest request) {
            request.grant(request.getResources());
        }
    });

    webView.addJavascriptInterface(new JavaScriptInterface(this),"AndroidFunction");

    webView.loadUrl("file:///android_asset/webViewTest.html");

    Button webTest1 = findViewById(R.id.webTest1);
    
    //calls normal js function
    webTest1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {

                        }
                    });
                }
            });
        }
    });

    Button webTest2 = findViewById(R.id.webTest2);
    //calls js function with peerjs
    webTest2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.evaluateJavascript("javascript:testWeb()", new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {

                        }
                    });
                }
            });
        }
    });


}

JAVASCRIPTINTERFACE

public class JavaScriptInterface {
MainActivity mainActivity;
public JavaScriptInterface(MainActivity mainActivity) {
    this.mainActivity = mainActivity;
}

@JavascriptInterface
public void showToast(String toast){
    Toast.makeText(mainActivity, toast, Toast.LENGTH_LONG).show();
}

js functions

<script src="./peerjs.js"></script>

<script type="text/javascript">
  function callJS() {
    AndroidFunction.showToast("Toast From javascript");
    alert("Android Called JS Of callJS Method");
  }

  function testWeb() {
    alert("testWeb Method called");
    var peer = new Peer(1234, {
      host: "192.168.****",
      port: 8000,
      path: "/strange",
    });

    peer.on("open", () => {
      AndroidFunction.showToast("Toast From testWebPeer");
    });
  }
</script>

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>

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);
            }
        });
 }
 */
}

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