I want to format Text in water wave structure, with repeating values and looping from right to left

enter image description here

As you can see in the image – I want to achieve the yellow line structure. I tried to search many article, blogs but eventually I got nothing related to my problem.

If you could help me provide article for this kind of problem I would appreciate it.
If you could provide me with a bit of code structure to begin with and related article I would really appreciate your time.

Thank you for your time. And sorry if i am wrong in any sense as it is my first question on stackOverflow.

How do I fix this, so that the stars in the rating can be evenly distributed on each card

This is the code from Html that displays the rating

<div class="row">
    <input type="hidden" name="id_porto" id="id_porto" value="<?php echo $idpor; ?>">
    <div class="col-sm-5">
        <i class="fas fa-star star-light mr-1 main_star"></i>
        <i class="fas fa-star star-light mr-1 main_star"></i>
        <i class="fas fa-star star-light mr-1 main_star"></i>
        <i class="fas fa-star star-light mr-1 main_star"></i>
        <i class="fas fa-star star-light mr-1 main_star"></i>
    </div>
    <div class="col-sm-5">
        <h6 class="rating-display">
            <b><span id="average_rating" class="avg_<?php echo $idpor; ?>">0.0</span> / 5</b>
        </h6>
    </div>
</div>

This is the code from Ajax that displays the rating

<script>
$(document).ready(function(){
  
    load_rating_data();

    function load_rating_data(){
        var id_porto = $('#id_porto').val();
        var link = "display_rate.php";

       $.ajax({
            url: link,
            method:"POST",
            data:{id_porto:id_porto},
            dataType:"json",
            success:function(data){
                  $('.avg_' + id_porto).text(data.average_rating);
              
                var count_star = 0;
                $('.main_star').each(function(){
                    count_star++;
                    if(Math.ceil(data.average_rating) >= count_star)
                    {
                        $(this).addClass('text-warning');
                        $(this).addClass('star-light');
                    }
                });
            }
          })
        }
});
</script>

and the following are the results that I have created

Result:

Result

I hope this problem can be fixed and the use of ratings can be evenly distributed. Here are the results I want

The result I want:

The result I want

Call to undefined method AppControllersMain::getRequestInput()

i try to validate input from my form, here is my controller

> class Main extends BaseController
>     {
>         
>          public function registration(){
>     
>             $rules = [
>                  'name' => 'required'
>                  ];
>          
>            $input = $this->getRequestInput($this->request);
>            
>          
>             if (!$this->validate( $rules)) {
>              return $this
>              ->getResponse(
>                  $this->validator->getErrors(),
>                  ResponseInterface::HTTP_BAD_REQUEST
>              );
>          }

But unfortunately, I am getting:

Call to undefined method AppControllersMain::getRequestInput()

How to convert a matplotlib plot data into JSON file to run in my react component?

So, my friend has a ML model which does a prediction based on a company’s stock. The output is displayed using matplotlib plot graph and it does the job. Now, I have a react based website in which I want to integrate the plot graph. So, I tried the img display method but that will cause issues in dynamic running.

So, I tried converting the python plot graph into data using mpdl3 module and then converted it to JSON object using the following code:

import json
import mpld3
fig=plt.gcf()
mpld3_data = mpld3.fig_to_dict(fig)
print(mpld3_data);
mpld3_data_str = json.dumps(mpld3_data)
with open('mpld3_data.json', 'w') as f:
    json.dump(mpld3_data, f)

It does give me a JSON file and I can import it to my react file. Upon importing it into a JS file, I parsed it there using the following code:

import mpld3_data from "...file location..."
var graph_data=JSON.parse(mpld3_data);
export default graph_data

But while running the file, it throws me a “Module not found” error.

PS: Since, it is a python code, the code and the JSON file it produces is outside my src file. So, I have to import it using relative path.

I don’t know what should I do here and what approach would be better. Thank you for your help and I would really appreciate it.

How do custom HTML tags interact with cloning a template?

Here’s the test case that I’m confused with. In html (in the end of body):

<template id="test">
    <test-tag class="test-id"></test-tag>
</template>

In the script:

class TestTag extends HTMLElement {
    constructor() {
        super();
        console.log("TestTag created");
    }
    get Property() : string {
        return "Hello";
    }
}

// in some function:
    customElements.define("test-tag", TestTag);
    customElements.whenDefined("test-tag").then(() => {
        console.log("test-tag defined");
        var tag = document.createElement("test-tag") as TestTag;
        console.log(tag.Property);

        var template = document.getElementById("test") as HTMLTemplateElement;
        var clone = template.content.cloneNode(true) as DocumentFragment;
        var tag2 = clone.querySelector<TestTag>(".test-id");
        if(tag2 == null){
            console.error("tag2 is null");
        } else {
            //customElements.upgrade(tag2);
            if(!(tag2 instanceof TestTag)){
                console.error("WTF?!"); //did not expect to be here
            }
            console.log(tag2.Property); //tag2.Property is undefined
        }
    });

The first tag object works as I expect. The second one doesn’t: it seems that cloning the template creates a generic DOM element rather than an instance of my TestTag class.

To me it seems to be the main function of custom elements – to define necessary behaviour and reuse it while still describing complex divs with HTML markup rather than some ugly construction code of dozens createElement/appendChild calls. So it seems like I’m missing something obvious. Like maybe shadow DOM mechanic but customElements.upgrade() does nothing in this case.

My question is: if there’s some well-known part of using custom elements I’ve missed then what is it; if not, what can be reasonably done to obtain a TestTag instance as tag2 value in the example above and why my example behaves the way it does?

Flask and Fetch POST Request

I am trying to send POST request but I get 500 error, its second day and i keep trying to solve it,
please help

Flask:

from flask import Flask, render_template, redirect, url_for

app = Flask(__name__)


@app.route('/tasks/today')
def homepage():
    return render_template('index.html', action='Мой день')


@app.route('/')
def redirect_to_homepage():
    return redirect('/tasks/today')

@app.route('/post', methods=['GET', 'POST'])
def get_input_text():
    print('Function worked!')

app.run()

Js:

let user = {
    name: 'John',
    surname: 'Smith'
};
  
let response = fetch('/post', {
    method: 'POST',
    headers: {'Content-Type': 'application/json;charset=utf-8'},
    body: JSON.stringify(user)
});

Thank you for any help

How to filter() from a user input?

I want to obtain an array from a user input using a prompt and then use that array to filter() and get a specific array.

I have used the following:

var number = prompt("write your number","");

var matrix = number.split("");

and I get the desired array but when I applied the filter() method to the matrix array it does not seem to work. I would like to get an array with just the numbers 3s.

The code that I present here works because I have defined the array in the code itself. But I want to use a user input instead.

<script>
        
var matrix = [3,2,2,3,2,3];
        
function find_3(value) {
            
  return (value === 3);

}
        
var result = matrix.filter(find_3);
        
document.write(result);
        
</script>

Webpack dynamic import and copyplugin

I have a bunch of json files that are imported in my code through dynamic import (code splitting)

    const hash = simpleHash(`${language}.${customerId}`)
    const clientTranslations = await import(
    /* webpackChunkName: "client_translation-[request]" */
    /* webpackMode: "lazy" */
      `../../../translations/client_translations_hashed/${hash}.json`
    )

However, the files in the /client_translations_hashed folder are placed there by the webpack.CopyPlugin, that reads json files from another location in my repo, and applies a hashing to ${language}.${customerId}, the same that the import uses.

In short, the use case is we deploy for multiple clients, but we want to have only one build. We dont want one client to see translations for the other clients or see the filename of the json for the other clients. That’s why we hash it. It’s not strong security, but it’s Good Enough (TM).

   new CopyPlugin({
      patterns: [{
        from: '../common_packages/assets/translations/client_translations/*.json',
        to: ({ absoluteFilename }) => {
          const filename = path.basename(absoluteFilename, path.extname(absoluteFilename))
          if (!filename) {
            throw new Error(`Error whilst trying to create hashed version of ${absoluteFilename}...`)
          }
          const hashed = simpleHash(filename)
          return `../../../common_packages/assets/translations/client_translations_hashed/${hashed}.json`
        },
      }],
    }),

The problem that we are facing is that it seems that Webpack seems to inspect the directories for dynamic imports before the CopyPlugin is allowed to run. Because when we start from a clean situation, ie an empty client_translations_hashed folder, the client_translation-[request].js files that are to be imported dynamically are not generated.
When I run webpack a second time (so when the client_translation_hashed files have been copied from the last time webpack was run) it works.

Ideally, I would like to run webpack only once.

RXjs in angular is making mutiple api calls while using Interval and api calls keeps on multiplying it

I have 2 API calls say FirstApi and SecondApi. First Api provides output with 3 different status(complete,failed, inprogress).
When the user redirects to the page on Complete state and Failed state both API needs to be called once.
when status is Inprogress the SecondApi needs to be called every 30 seconds. The thing to be noted is that FirstApi status keeps on changing is that first it will be in progress for around 40 mins then status changes . so until the status changes from inprogress to comple we need to keep on calling on interval based as output of second APi is depent on the first api. tried setinterval did not work used rxjs did not work. Please provide the solutions.

I tried using setinterval, rxjs interval. I expect second api need to be called every 30 seconds until the first api status changes to complete from inprogress.

Send Data Received From WebSocket Through to a Discord Server with a Discord bot

I am trying to make a FRC scouting data collection web application. The thing is, i don’t have a way to set up a database to hold the information. A friend of mine mentioned using a Discord bot and sending the information to a Discord channel. I want to use a Web Socket connection hosted by piehost.com to send information from the web application to the discord bot. I am using JavaScript to send the data and using Python to receive it. I have gotten to a point where the python script is reviving the data and i can print it in the terminal however when i try to integrate the “sending to discord” part, python doesn’t recognize the string. I have no errors, its just not working.

Test HTML with JavaScript Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button onclick="send()">Click!</button>

    <script>
        let socket = new WebSocket("wss://piehost.com"); //not real url

        function send() {
            console.log("[open] Connection established");
            console.log("Sending to server");
            socket.send("Hello World!");
            console.log("Sent!");
        };
    </script>

</body>
</html>

Discord Bot Python Code (Runs in Replit)

import discord
from discord.ext import commands
import os
import websockets
import asyncio

# WebSocket Server URL (replace 'YOUR_WEBSOCKET_URL' with the actual WebSocket server URL)
WEBSOCKET_URL = 'wss://piehost.com' #not real URL

# Discord Channel ID (replace 'YOUR_CHANNEL_ID' with the actual channel ID)
CHANNEL_ID = 'channel_id'

# Initialize Discord client
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)
intents = discord.Intents.default()
client = discord.Client(intents=intents)

# Function to send message to Discord channel
async def send_to_discord(message):
    # Change the line where channel is retrieved to correctly get a TextChannel
    channel = client.get_channel(int(CHANNEL_ID))

    # Check if the channel is a TextChannel before sending the message
    if isinstance(channel, discord.TextChannel):
        await channel.send(message)

# Function to handle WebSocket messages
async def handle_message(message):
    try:
        await send_to_discord(message)
    except Exception as e:
        print(f"Failed to send message to Discord: {e}")

# Function to connect to WebSocket server
async def connect_to_websocket():
    try:
        async with websockets.connect(WEBSOCKET_URL) as websocket:
            print("Connected to WebSocket server")
            while True:
                message = await websocket.recv()
                await handle_message(message)
    except Exception as e:
        print(f"WebSocket connection failed: {e}")

# Event: Bot is ready
@client.event
async def on_ready():
    print(f'Logged in as {client.user}')

    # Connect to WebSocket server
    await connect_to_websocket()

# Start the bot
bot.run(os.environ["TOKEN"])

multer error while compiling typescript project

i am creating api /product/create where i can create product with image and other details. i am using multer with typescript to upload the image. but when i run npm run build i get this error.

node_modules/@types/multer/index.d.ts(46,13): error TS2717: Subsequent property declarations must have the same type.  Property 'files' must be of type 'FileArray | null | undefined', but here has type '{ [fieldname: string]: File[]; } | File[] | undefined'.

this is the function createProduct controller

export const createProductController = async (req: Request, res: Response) => {
    upload(req, res, async (err: any) => {
        if (err) {
            return res.status(500).send({ err: err.message });
        }

        if (!req.body.name || !req.body.price || !req.body.description || !req.file) {
            return res
                .status(400)
                .json({ err: "All fields should be selected - name, price, file" });
        }

        if (isNaN(Number(req.body.price))) {
            return res.status(400).json({ err: "Price must be a number" });
        }

        let productDetails = {
            name: req.body.name,
            price: req.body.price,
            description: req.body.description,
            image: req.file.path,
        };

        try {
            const createdProduct = await Product.create(productDetails);
            return res.status(201).json({ message: "Product created" });
        } catch (error) {
            console.error(error);
            return res.status(500).json({ err: "Error creating product" });
        }
    });
};

multer disk storage config


// Multer disk storage configuration
const storage = multer.diskStorage({
    destination: (req: Request, file: Express.Multer.File, cb: Function) => {
        cb(null, "content"); // Set the destination folder for storing files
    },
    filename: (req: Request, file: Express.Multer.File, cb: Function) => {
        console.log('inside storage');
        cb(null, Date.now() + path.extname(file.originalname)); // Generate unique filenames for uploaded files
    }
});

file upload middleware

// Multer file upload middleware configuration
const upload = multer({
    storage: storage,
    limits: { fileSize: 10000 * 100 }, // Set file size limit (in bytes)
    fileFilter: (req: Request, file: Express.Multer.File, cb: FileFilterCallback) => {
        console.log('inside upload');
        const fileTypes = /jpg|png|mp4|gif/;
        console.log('file', file.mimetype, file.originalname);
        if (fileTypes.test(path.extname(file.originalname).toLowerCase())) {
            return cb(null, true); // Accept the file if its extension matches allowed file types
        } else {
            return cb(new Error('Invalid file type'));
        }
    }
}).single('image');

i looked up on google but couldn’t find anything. i tried installing latest version version of multer.

How to set a Document ID in firebase based on the data of the submitted vue3 form [duplicate]

There is a code:

import { collection, addDoc } from 'firebase/firestore';
import { requestGiftCard } from '@/firebase';
const name = ref();
const surname = ref();
const email = ref();
const number = ref();
const showAllItems = ref(false);


const handleSubmit = async () => {
    try {
        
        const formDataCollection = requestGiftCard;

       
        await addDoc(formDataCollection, {
            name: name.value,
            surname: surname.value,
            email: email.value,
            number: number.value,
            
        });

        name.value = '';
        surname.value = '';
        email.value = '';
        number.value = '';
        
        console.log('Form data sent successfully!');
        console.log(formDataCollection);
    } catch (error) {
        
        console.error('Error sending form data:', error);
    }
};

You need to make sure that when submitting the form, the Document ID in the firebase collection is the same as the first and last name that were entered in the form.

In fact, I don’t even know if it is possible to implement such a thing, but if possible, I will be very grateful to someone who will write how to do it.

There was an attempt to implement it, but it was not successful:

const documentId = `${name.value}-${surname.value}`;

        // Отправьте данные в коллекцию с уникальным Document ID
        await addDoc(formDataCollection, {
            name: name.value,
            surname: surname.value,
            email: email.value,
            number: number.value,
            // Добавьте другие данные из формы по мере необходимости
        }, { id: documentId });

Jquery Autocomplete conflict with minLength and selection of ui.item.label

when I click on the empty search bar, it shows all results, but it won’t work when I click on any one of the results on the pop up list. Here is my code with Jquery Autocomplete:

$('#search').autocomplete({
        source: function(request, response) {
            let term = request.term;
            let data = handleAutocomplete(term); //your custom handling
            response(data);
        },
        minLength:0,/**/       /*show all options on focus, but conflict with click droplist option*/
        select: function(event, ui){
            if(ui.item){
                console.log('select', ui.item.label);
                return ui.item.label;
            }
            else{
                console.log('select with null value');
            }
        }, /*"get automatically value on focus if no values selected"*/
        change: function(event, ui){
            let searched = this.value;
            console.log("Searched: " + searched);
            if(ui.item){
                console.log('change', ui.item.id);
            }else{
                console.log('change with null value');
                let result = categories.filter(function( value ) {
                    return value.toLowerCase().indexOf(searched.toLowerCase()) !== -1;
                });
                if(result.length>0){
                    $(this).val(result[0]);
                }
                else{
                    //clear the autocomplete
                    $(this).val("");
                }
                
            }
        }
    }).focus(function(){ 
        $(this).autocomplete('search', $(this).val()); /*show all options on focus*/
});

how to sort products by users distance using mongo Geospatial Queries?

I am developing a web app that finds the nearest users (neighbors) and display their product that they want to buy, they also have the ability to sell.

the app uses node.js, javaScript, mongodb, mongoose.

my problem is with sorting the products. I want to display the products sorted from the nearest users of the loggedIn user to the furthest users but I could not do that. I have spent hours but I just could not figure out what is wrong

const Product = require('../models/products')
const User = require('../models/user')

module.exports.index = async (req, res) => {
    try {
        // get logged in user location
        const currentUserLocation = req.user.location.coordinates;

        // sorting users
        const nearbyUsers = await User.find({
            location: {
                $near: {
                    $geometry: {
                        type: 'Point',
                        coordinates: currentUserLocation
                    },
                }
            }
        });

        // Get products of nearby users
        const products = await Product.find({ author: { $in: nearbyUsers.map(user => user._id) } });
        console.log("this is the users log: ",nearbyUsers)
        console.log('this is the products log: ',products)
    



        // Render the products on the main page
        res.render('products/index', { products });
    } catch (error) {
        console.error('Error fetching nearby products:', error);
        res.status(500).send('Internal Server Error');
    }
};

user model

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');
const Product = require("../models/products")

const UserSchema = new Schema({
    email: {
        type: String,
        required: true,
        unique: true
     },
     phoneNumber: Number,
   
     location: {
         type: {
           type: String,
            enum: ['Point'],
          required:true
    },
     coordinates: {
             type: [Number],
             required:true
         }
    
}})

UserSchema.index({ location: '2dsphere' }); 

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model('User', UserSchema);

product model

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const productSchema = new Schema ({
    title:String,
    images:[
      {
        url:String,
      filename:String
    }
    ],
    price:Number,
    description:String,
   
    
   author:{
    type: Schema.Types.ObjectId,
    ref:'User'
 },
 transactionType: {
    type: String,
    enum: ['sell', 'rent'],
},
status: {
    type: String,
    enum: ['available', 'sold', 'pending'], 
    default: 'available' // Default status is available
},



});



module.exports=mongoose.model('Products',productSchema)

the index ejs file

 <%- layout ('/layouts/boilerplate') %>
   <h1>all products</h1> 
   <div>
   <a href="/products/new">add a product</a>
   <a href="/products/borrowing-requests">View Borrowing Requests</a>
</div>
   <% for(let product of products) {%>
    <div class="card" mb-3>
       <div class="row">
        <div class="col-md-4">
            <img src="<%= product.images[0].url %>" class="img-fluid" alt="Product Image">        </div>
        <div class="col-md-8">
            <div class="card-body">
                <h5 class="card-title"><%= product.title %></h5>
                <p class="card-text"><%= product.price %></p>
                <p class="card-text">
                <small class="text-secondary"><%= product.description %></small>
            </p>
            <a class="btn btn-primary" href="/products/<%= product._id %>">view <%= product.title %> </a>
                        </div>
                
            </div>
        </div>
       </div>
    </div>
<% } %>

I think that there Is something wrong with the logic of the code here but I can’t figure It out, I have provided the code relevant to the problem.

do you think that there Is a better way to do this job?, do I need to use something like using mapbox for the code?

If you have any suggestions, please let me know

Note: The coordinates of users are already in the database

My script doesn´t let me add contributors to my github repository

I have 15 repositorys, all of them with the name “21-051-(numberOfTheGroup)” where numberOfTheGroup is a number that depends of the number of the group. I have an .xlsx document that have gmail and number of the group of the members of each group.

I made this script, i want to take the emails of the .xlsx and the number of group, and add that emails as contributors of each repositorys (obviusly, only add the email to the repository of his group).

I made the script in Javascript with node.js and other version in python, but it doesn´t work in any of two options. In both cases send me the error Not Found. All the configurations in github and in the script are okay for me, i saw the documentation in github and other posts to do the script and all of them do the same thing i did, but it doesn´t work.

I will let the code here if somebody knowns what is the problem.

Python code:

import pandas as pd
from github import Github

# Token de acceso a GitHub
token = "Here i put my github token"

# Autenticación en GitHub con el token de acceso
g = Github(token)

# Leer el archivo Excel (.xlsx)
datos = pd.read_excel("Lista_Mails.xlsx")

# Iterar sobre cada fila del archivo CSV
for index, fila in datos.iterrows():
    grupo = fila["Grupo"]
    correo = fila["Correo"]

    # Obtener el nombre del repositorio correspondiente al grupo
    nombre_repositorio = f"24-051-{grupo}"
    
    try:
        # Obtener el repositorio
        repositorio = g.get_repo(f"SantiBoero1/{nombre_repositorio}")

        # Añadir al correo electrónico como colaborador
        try:
            repositorio.add_to_collaborators(correo, "maintain")
            print(f"Correo {correo} añadido al grupo {grupo} en el repositorio {nombre_repositorio}")
        except Exception as e:
            print(f"Error al añadir colaborador {correo} al repositorio {nombre_repositorio}: {str(e)}")
    except Exception as e:
        print(f"Error al acceder al repositorio {nombre_repositorio}: {str(e)}")

Javascript code:

const { Octokit } = require('@octokit/rest');
const fs = require('fs');
const xlsx = require('xlsx');

// Token de acceso a GitHub
const token = 'Here i put my github token';

// Crear una instancia de Octokit con el token de acceso
const octokit = new Octokit({
  auth: token,
});

// Leer el archivo Excel (.xlsx)
const workbook = xlsx.readFile('Lista_Mails.xlsx');
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
const datos = xlsx.utils.sheet_to_json(worksheet);

// Iterar sobre cada fila del archivo Excel
datos.forEach(async (fila) => {
  const grupo = fila.Grupo;
  const correo = fila.Correo;

  // Obtener el nombre del repositorio correspondiente al grupo
  const nombreRepositorio = `24-051-${grupo}`;

  try {
    // Añadir al correo electrónico como colaborador
    await octokit.repos.addCollaborator({
      owner: 'SantiBoero1',
      repo: nombreRepositorio,
      username: correo,
      permission: 'maintain', // Cambiar a 'pull' si se desea un rol de solo lectura
    });

    console.log(`Correo ${correo} añadido al grupo ${grupo} en el repositorio ${nombreRepositorio}`);
  } catch (error) {
    console.error(`Error al añadir colaborador ${correo} al repositorio ${nombreRepositorio}: ${error.message}`);
  }
});

I tried to see documentation, other posts with the same problem, but i don´t get an answer