How do I use tsParticles Gradient Updater for color gradient animation?

I’m working on a text-based adventure game using JavaScript, and I thought it would be cool to integrate tsParticles for particle effects in the background. My goal is to create subtle animations where the particle link color changes in response to certain game events (like when the player is about to enter a new location). I also want to adjust other properties, like particle size and direction, based on these events.

For now, I’m starting with a simple color gradient animation for the particle links. When exploring the documentation, I found a folder called “Gradient Updater” which sounds like it could be exactly what I need. However, as a beginner in JavaScript, I’m struggling to figure out how to use it. The README doesn’t go into enough detail, and I’m not sure where to begin.

So, my questions are:

  1. How can I use the tsParticles Gradient Updater to create a color gradient animation for the particle links?

  2. Is there a simple function I can import and use to get started? If so, how can I use it?

  3. How should I set this up in my project, including importing and configuring it?

Here’s my GitHub repository with the project if it helps: GitHub Repository

Any guidance or code examples would be really appreciated!

Const variable changing unexpectedly

So I kinda have a guess as to why this is happening, but I still need help figuring out how to work around this. Im pretty sure the issue is because im using async functions and crypto.randomBytes.

Here’s where my function is being called:

logInForm.tsx

createUserSession(user[0]).then(sessionId => {
  localStorage.setItem('session-id', sessionId);
  console.log(sessionId);
})

And here’s the function:

export async function createUserSession(user: User): Promise<string> {
    const sessionId = crypto.randomBytes(512).toString('hex').normalize();
    try {
        redisClient.set(`session:${sessionId}`, user, {
            ex: SESSION_EXPIRATION
        })
        return sessionId
    } catch (error) {
        return ''
    }
}

So when I call the function, it sets the session in my redis db correctly; but then the localStorage that uses the same variable doesn’t return the correct sessionId. Thanks to anyone in advance; I tried looking for similar questions but I think its just too specific.

Having a problem with decomposing my code [closed]

I’m building a small budget app dashboard using React. Currently, I have a large MyNavbar.jsx file, and as I’m trying to break it into smaller, more manageable components, I’m feeling a bit lost. I need help organizing my code and splitting it properly without breaking things. I’m especially unsure about how to structure the app components and pass data between them.

Here’s the code I currently have:

App.js

import React from 'react';
import './App.css';
import MyNavbar from './components/navbar/MyNavbar';
import MyChart from './components/main/leftSide/MyChart';

function App() {
  return (
    <div className="App">
      <MyNavbar />
    </div>
  );
}

export default App;

MyNavbar.jsx

import React from 'react'
import { useState } from 'react'
import cl from './Navbar.module.css'
import transactions from '../../transactions.json'
import MyChart from '../main/left side/chart/MyChart'

const MyNavbar = () => {

    const [month, setMonth] = useState(0)

    const monthes = [
        { name: 'January 2023', value: 0, year: 2023, month: '01' },
        { name: 'February 2023', value: 1, year: 2023, month: '02' },
        { name: 'March 2023', value: 2, year: 2023, month: '03' },
        { name: 'April 2023', value: 3, year: 2023, month: '04' },
        { name: 'May 2023', value: 4, year: 2023, month: '05' },
        { name: 'June 2023', value: 5, year: 2023, month: '06' },
        { name: 'July 2023', value: 6, year: 2023, month: '07' },
        { name: 'August 2023', value: 7, year: 2023, month: '08' },
        { name: 'September 2023', value: 8, year: 2023, month: '09' },
        { name: 'October 2023', value: 9, year: 2023, month: 10 },
        { name: 'November 2023', value: 10, year: 2023, month: 11 },
        { name: 'December 2023', value: 11, year: 2023, month: 12 },
        { name: 'January 2024', value: 12, year: 2024, month: '01' },
        { name: 'February 2024', value: 13, year: 2024, month: '02' },
        { name: 'March 2024', value: 14, year: 2024, month: '03' },
        { name: 'April 2024', value: 15, year: 2024, month: '04' },
        { name: 'May 2024', value: 16, year: 2024, month: '05' },
        { name: 'June 2024', value: 17, year: 2024, month: '06' },
        { name: 'July 2024', value: 18, year: 2024, month: '07' },
        { name: 'August 2024', value: 19, year: 2024, month: '08' },
        { name: 'September 2024', value: 20, year: 2024, month: '09' },
        { name: 'October 2024', value: 21, year: 2024, month: 10 },
        { name: 'November 2024', value: 22, year: 2024, month: 11 },
        { name: 'December 2024', value: 23, year: 2024, month: 12 },
        { name: 'January 2025', value: 24, year: 2025, month: '01' },
    ]

    const allTransactions = transactions;

    let currentMonth = monthes[month].month;
    let currentYear = monthes[month].year;

    const currentDate = new RegExp(`^${currentYear}-${currentMonth}-\d{2}$`);
    console.log(currentDate)//getting the date that i should search payments from

    const matchedTransaction = allTransactions.filter(t => currentDate.test(t.date));
    console.log(matchedTransaction);//whole objects which pass through filter above

    let dataForChart =  [["Category", "Amount"], ...matchedTransaction.map(el => [el.category, el.amount])];//needs to be summed
    console.log(dataForChart);

    const dataForChartSummed = dataForChart.slice(1).reduce((acc, [category, amount]) => {
        acc[category] = (acc[category] || 0) + Math.round(amount)
        return acc
    }, {})
    console.log(dataForChartSummed)//ready for chart but not array

    const dataForChartSummedArray = Object.entries(dataForChartSummed).map(([category, amount]) => [category, amount])
    console.log(dataForChartSummedArray);

    const changeMonthUp = () => {
        if (month < monthes.length - 1) {
            setMonth(month + 1)
            console.log(month)

        } else {
            setMonth(0)
            console.log(month)
        }
    }

    const changeMonthDown = () => {
        if (month < monthes.length && month !== 0) {
            setMonth(month - 1)
            console.log(month)
        } else {
            setMonth(24)
            console.log(month)
        }
    }


    return (
        <div className={cl.header}>
            <div className={cl.inner_header}>
                <div className={cl.month_box}>
                    <h1>Month:</h1>
                </div>
                <ul className={cl.functionality}>
                    <span>
                        <li><button onClick={changeMonthDown}>back</button></li>
                    </span>
                    <span>
                        <li>
                            <h1>{monthes[month]
                                ? monthes[month].name
                                : 'error'
                            }</h1>
                        </li>
                    </span>
                    <span>
                        <li><button onClick={changeMonthUp}>further</button></li>
                    </span>
                </ul>
            </div>
            <div>
                <MyChart transactions={dataForChartSummedArray}/>
            </div>
        </div>
    )
}

export default MyNavbar

MyChart.jsx

import React from 'react';
import { Chart } from 'react-google-charts';

const MyChart = ({ transactions }) => {
  return (
    <div>
      <Chart
        chartType="PieChart"
        data={[['Category', 'Amount'], ...transactions]}
        options={{ title: 'All spendings for this month' }}
        legendToggle
      />
    </div>
  );
};

export default MyChart;

The Problem:

I want to organize my components better. Right now, everything is getting jumbled into one file (MyNavbar.js), and I’m not sure how to break it into logical components without breaking the functionality. My goal is to:

  • Have a component for the navbar (MyNavbar)
  • Have a component for the main content with a chart on the left and some items on the right
  • Have a footer
  • Have a SumOfItems component to show the total spending of the month

I’m trying to structure my app like this:

/src
  /components
    /navbar
      MyNavbar.jsx
    /main
      /leftSide
        MyChart.jsx
      /rightSide
        ItemsList.jsx
      MiddleOfPage.jsx
    /underparts
      SumOfItems.jsx
    /footer
      Footer.jsx
  App.js
  transactions.json
  App.css

What I need help with:

  1. How to structure my components and break down App.js properly.
  2. How to pass data down from parent components (like MyNavbar) to child components (like MyChart).
  3. Any best practices for managing state and props in this type of app.

My Goal:

I want to make sure that the logic in each component is clean and the app is structured well. I also want to be able to pass the required data between components while keeping the code maintainable and scalable.

Intl-tel-input format number

I need to display iti number (from iti.getNumber()) as normal human readable number (such as ‘+351920650120’ => ‘+351 920 650 120’)

i use vanilla js and tried using iti.getFormattedNumber() but it didn’t work. iti.getNumber(intlTelInputUtils.numberFormat.INTERNATIONAL) also doesn’t work.

with this i get the error ‘intlTelInputUtils is not defined’

    <script>
            document.addEventListener("DOMContentLoaded", (event) => {
                 const input = document.querySelector("#tel");
              const iti = window.intlTelInput(input, {
                  initialCountry: "auto",
                    strictMode: true,

                  geoIpLookup: callback => {
                fetch("https://ipapi.co/json")
                  .then(res => res.json())
                  .then(data => callback(data.country_code))
                  .catch(() => callback("pt"));
              },
                loadUtils: () => import("https://cdn.jsdelivr.net/npm/[email protected]/build/js/utils.js"),
              });
              
              
            iti.promise.then(() => {
                
               setTimeout(() => {
                  const formattedNumber = iti.getNumber(intlTelInputUtils.numberFormat.INTERNATIONAL);
                  console.log(formattedNumber);
                }, 100);
                
            });
             
            });
            </script>

Is it worth using generator functions as “scripts”? [closed]

The classic approach

function builderFunction(builder) {
  builder.add(thing1);
  builder.add(thing2);
  builderFunction2(builder);
}

The generator approach

function* builderFunction() {
  yield thing1;
  yield thing2;
  yield* builderFunction2();
}

Or another example

function configureRoutes(builder) {
  builder.route('app', builder => {
    builder.middleware(myMiddleware, builder => {
      builder.method('GET', indexHandler);
    })
    configureAssets(builder)
  })
  builder.method('GET', redirectToIndexHandler);
}
function* configureRoutes() {
  yield route('app', function*() {
    yield middleware(myMiddleware, function*() {
      yield method('GET', indexHandler);
    })
    yield* configureAssets()
  })
  yield method('GET', redirectToIndexHandler);
}

Does it worth it to define things that way? This is not opinion-based, but a concrete comparison of 2 methods. Is this only a preference, or these methods also have some differences?

My while loop on JavaScript isn’t re assigning a value back to its original variable

I am writing this JavaScript code using the while loop that asks a user for there age. I’ve written the code but it accepts me even after filling ages below 18. How shall I go about it.

I tried the code below and was expecting it to be in a loop as long as the age is below 18 but it didn’t work that way.

let age = Number(prompt("Please enter your age: "))

while(age<18){

console.log(prompt("You are too young"))
}

console.log("You can proceed")

Add horizontal line to React Native stacked bar chart (library undecided)

I’m looking to display data in a stacked bar chart of which there are a few options I have seen

However, I am then wanting to add a horizontal line atop the bars to show a user-defined target value.

For example, a user’s earnings from 3 revenue streams (shown in yellow, oragne and brown) over several months, where they have specified a target of $100 within a settings page.

enter image description here.

How would one go about this?

odoo18 how to fix js error in cart at step: fill address

In odoo18, after having purchased a product, at the second part of the cart: /shop/address
I get this error:

UncaughtPromiseError > TypeError

Uncaught Promise > input.parentElement is undefined

Occured on samadeva-oerp-staging-19206039.dev.odoo.com on 2025-03-22 20:42:35 GMT

TypeError: input.parentElement is undefined
    _getInputLabel@https://samadeva-oerp-staging-19206039.dev.odoo.com/web/assets/2/85f3901/web.assets_frontend_lazy.min.js:9093:446
    _markRequired@https://samadeva-oerp-staging-19206039.dev.odoo.com/web/assets/2/85f3901/web.assets_frontend_lazy.min.js:9094:6
    _changeCountry/<@https://samadeva-oerp-staging-19206039.dev.odoo.com/web/assets/2/85f3901/web.assets_frontend_lazy.min.js:9093:291
    _changeCountry@https://samadeva-oerp-staging-19206039.dev.odoo.com/web/assets/2/85f3901/web.assets_frontend_lazy.min.js:9093:264

The related code is located in Odoo18 nativ code : /addons/website_sale:

  • /address.js
  • /templates.xml

Does anyone know how to fix it please ?
enter image description here

Smart search box api in node js

i want to create end point controller function in node js and make auto complite in resulte, i use MongoDB.

this is my function

 exports.searchLectures = asyncHandler( async (req, res) => {
  const search = req.query.search;
  try {
   
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message
    });
  }

});

and this is my model

const mongoose = require('mongoose');

const lectureSchema = new mongoose.Schema({
    teacher: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
    student: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: false },
    maxStudents: { type: Number, required: false, default: 1 },
    price: { type: Number, required: true },
    appointment: { type: Date, required: true },
    period: { type: Number, required: true },  // in minutes
    course: { type: String, required: true },
    category: { type: mongoose.Schema.Types.ObjectId, ref: 'CourseCategory', required: true },
    courseType: { type: String, required: true, enum: ['university', 'school'] },
    title: { type: String, required: true },
    description: { type: String, required: true },
    status: { type: String, required: false, default: 'available', enum: ['available', 'done', 'reserved', 'canceled'] },
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment', required: false }],
    rate: { type: Number, required: false },
    rateCount: { type: Number, required: false },
}, { timestamps: true });

const Lecture = mongoose.model('Lecture', lectureSchema);
module.exports = Lecture;

i want to search by title , course , teacher.name and category.name and alway the function return title

Keep scroll positions on page by url

Can you fix the script, which keeps position on difrent pages with no problem, until there you have some pages with redirected to same php file, but different URL (thanks RewriteRule)?
Would like to keep position even with atributes in URL. For example – page1.php is same as page1.php&abc=1 but diferent of page2.php. This script takes all these pages as same URL so it keeps same position, even if you did not visited second page yet.

.htaccess

RewriteRule page1.php detail.php
RewriteRule page2.php detail.php
RewriteRule page3.php detail.php

script:

<script>
    document.addEventListener("DOMContentLoaded", function (event) {
        var scrollpos = localStorage.getItem("scrollpos");
        if (scrollpos) window.scrollTo(0, scrollpos);
    });

    window.onscroll = function (e) {
        localStorage.setItem("scrollpos", window.scrollY);
    };
</script>

new File() has bigger size than origin blob

I have jQuery ajax request for file and it is returned OK with some size.
Ajax request is with param: xhrFields.responseType = 'blob';
When I process ajax response than response size is the same with response origin filesize.
Response size is 3004260. File size physicaly has 3177066 and its jpg file.

But when I use this:

var file = new File([response], filename, {type: 'application/force-download'});

file.size is 5754539.
than file.size is bigger that origin response. I will save it by:

var url = URL.createObjectURL(file);
console.log(url);
// create a hidden anchor element to download the blob as a file.
var anchorElem = document.createElement("a");
anchorElem.style.display = "none";
anchorElem.href = url;
anchorElem.download = 'test.jpg';
// append the anchor element on to the document body.
$("body").append(anchorElem);
// trigger a click event on this anchor element.
anchorElem.click();
// clean-up
URL.revokeObjectURL(url);

and file is saved but broken because it impossible open it. File have double filesize.
why? What is wrong?

PHP which will send file is:

header('Content-Description: File Transfer');
header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename="test.jpg"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: 3177066');
echo $filecontent;

Origin and good file looks like:
enter image description here

Wrong file looks like this:
enter image description here

How come visiting child component loses functionality?

I have an app that has a 3 JSX files:
1-one for controlling states
2-one for creating items
3-one for viewing created items as a table.

Here is a code sandbox: https://codesandbox.io/p/sandbox/flamboyant-roman-forked-8hw8x2

When viewing the controlling files component(1), the functionality of adding items and viewing the table works. When I go directly to the pages for creating items / viewing the table the functionality does not. Why is this?

Thanks for views

Javascript new File() has bigger size than origin blob

I have jQuery ajax request for file and it is returned OK with some size.
Ajax request is with param: xhrFields.responseType = 'blob';
When I process ajax response than response size is the same with response origin filesize.

But when I use this:

var file = new File([response], filename, {type: 'application/force-download'});

than file.size is 2x bigger that origin response. I will save it by:

var url = URL.createObjectURL(file);
console.log(url);
// create a hidden anchor element to download the blob as a file.
var anchorElem = document.createElement("a");
anchorElem.style.display = "none";
anchorElem.href = url;
anchorElem.download = 'test.jpg';
// append the anchor element on to the document body.
$("body").append(anchorElem);
// trigger a click event on this anchor element.
anchorElem.click();
// clean-up
URL.revokeObjectURL(url);

and file is saved but broken because it impossible open it. File have double filesize.
why? What is wrong?

Navbar link color not remaining at green when clicked

I have a simple navbar that I am trying to get the color to be green when clicked. However it does not seem to be working.

When I hover over the link it turns green and works fine. However I cannot get it so that when I click on the link it remains green and if I click another link the new active turns green and the previous active turn white.

Here’s the HTML and CSS code I have come up:

<nav>
    <ul>
       <li><a class="nav-link" href="index.html"><i class="fa-solid fa-house"></i></a></li>
        <li><a class="nav-link" href="skills.html"><i class="fa-solid fa-tools"></i></a></li>
         <li><a class="nav-link" href="project.html"><i class="fa-solid fa-laptop-code"></i></a></li>
         <li><a class="nav-link" href="contact.html"><i class="fa-solid fa-paper-plane"></i></a></li>
     </ul>
</nav>
nav {
    display: flex;
    justify-content: center;
}

nav ul {
    display: flex;
    list-style: none;
    gap: 30px;
}

.nav-link {
    color: white;
    text-decoration: none;
    font-size: 16px;
    transition: 0.3s;
}

.nav-link:hover {
    color: #32CD32;
}

.nav-link.active {
    color: #32CD32;
}