Filter text in a table with merged cells with “rowspan” or “colspan”

I have an HTML code, and I want the filterTable() function to filter the myTable table after typing something in the searchInput.

For example, if I type “Rafael,” the relevant row should be fully displayed with all its merged cells, and the rest that do not contain this word should be hidden.

My code:

function filterTable() {
    var input = document.getElementById("searchInput");
    var filter = input.value;
    var table = document.getElementById("myTable");
    var rows = table.getElementsByTagName("tr");

    for (var i = 1; i < rows.length; i++) {
        rows[i].style.display = "none";
    }

    for (var i = 1; i < rows.length; i++) {
        var row = rows[i];
        var cells = row.getElementsByTagName("td");
        var rowMatchesFilter = false;

        for (var j = 0; j < cells.length; j++) {
            var cell = cells[j];
            var cellContent = cell.textContent;

            if (cellContent.indexOf(filter) > -1) {
                rowMatchesFilter = true;

                if (cell.getAttribute("rowspan")) {
                    var rowspan = parseInt(cell.getAttribute("rowspan"));
                    for (var k = 0; k < rowspan; k++) {
                        rows[i + k].style.display = "";
                    }
                } else {
                    row.style.display = "";
                }
                break;
            }
        }
        if (rowMatchesFilter) {
            row.style.display = "";
        }
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Table Search</title>
    <style>
        table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
            padding: 8px;
            width: 500px;
        }
    </style>
</head>
<body>

<h2>Information Table</h2>

<input type="text" id="searchInput" placeholder="Enter search text" oninput="filterTable()">

<table id="myTable">
    <thead>
        <tr>
            <th>Building</th>
            <th>Floor</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td rowspan="5">Building 1</td>
            <td rowspan="2">Floor 1</td>
            <td>Martin</td>
        </tr>
        <tr>
            <td>Cristiano</td>
        </tr>
        <tr>
            <td rowspan="3">Floor 2</td>
            <td>Karim</td>
        </tr>
        <tr>
            <td>Rafael</td>
        </tr>
        <tr>
            <td>Anna</td>
        </tr>
        <tr>
            <td>Building 2</td>
            <td>Floor 1</td>
            <td>Carlos</td>
        </tr>
    </tbody>
</table>
</body>
</html>

However, when I type “Rafael”, it filters, but shows:

Building Floor Name
Rafael

But I want to show:

Building Floor Name
Building 1 Floor 2 Rafael

trpc Server-Side Rendering after fetching the data /api

Hello there I’m using trpc and fastify and i have created an api end point to fetch data from prismic cms now I’m confused how to use this fetched data on my pages since I want to render my pages server side with pug template engine, when i go to /api/home I can see the data without issues, but I’m not sure how to extend my setup with trpc to allow my pages to use those fetched data

lib/trpc/index.ts

import { initTRPC } from '@trpc/server';
import superjson from 'superjson';

/**
 * Wrapper around TRPC
 *
 * TRPC is a typesafe way of making an API server and a client
 * The TypeScript types are shared between the two, keeping them in sync
 * The strength of TRPC is how quickly you can add new endpoints
 *
 * @see https://trpc.io
 */
export class Trpc {
    private readonly trpc = initTRPC.create({
        /**
         * @see https://trpc.io/docs/v10/data-transformers
         */
        transformer: superjson,
    });

    /**
     * @see https://trpc.io/docs/v10/router
     */
    public readonly router = this.trpc.router;

    /**
     * @see https://trpc.io/docs/v10/merging-routers
     */
    public readonly mergeRouters = this.trpc.mergeRouters;

    /**
     * @see https://trpc.io/docs/v10/procedures
     **/
    public readonly procedure = this.trpc.procedure;

    /**
     * @see https://trpc.io/docs/v10/middlewares
     */
    public readonly middleware = this.trpc.middleware;
}

lib/fastify/index.ts

import type { Router } from '@trpc/server';
import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify';
import type { AnyRouterDef } from '@trpc/server/dist/core/router';
import fastify from 'fastify';
import metricsPlugin from 'fastify-metrics';
import * as trpcPlayground from 'trpc-playground/handlers/fastify';

export interface ServerOptions {
    dev?: boolean;
    port?: number;
    prefix?: string;
}

/**
 * Wrapper around fastify
 *
 * @see https://www.fastify.io/
 */
export class Fastify {
    constructor(
        /**
         * The port
         */
        private readonly port: number,

        /**
         * The host
         */
        private readonly host: string,

        /**
         * Whether to run in development mode
         * Defaults to Env.NODE_ENV === 'development'
         */
        dev: boolean,

        /**
         * The fastify server being wrapped
         *
         * @dependencyinjection
         */
        public readonly server = fastify({ logger: dev })
    ) {}

    /**
     * Starts the fastify server
     */
    public readonly start = async () => {
        try {
            /**
             * @see https://www.fastify.io/docs/latest/Reference/Server/#listen
             */
            await this.server.listen({ port: this.port, host: this.host });
            console.log('listening on port', this.port);
        } catch (err) {
            this.server.log.error(err);
            process.exit(1);
        }
    };

    /**
     * Stop the fastify server
     */
    public readonly stop = async () => {
        await this.server.close();
    };

    /**
     * Registers metrics on fastify server
     */
    public readonly registerMetrics = async (endpoint = '/metrics') => {
        await this.server.register(metricsPlugin, { endpoint });
    };

    /**
     * Register a trpc router on fastify server
     * Include a playground endpoint if you want to use the playground
     */
    public readonly registerTrpc = async (
        prefix: string,
        appRouter: Router<AnyRouterDef>,
        playgroundEndpoint: string | undefined
    ) => {
        await this.server.register(fastifyTRPCPlugin, {
            prefix,
            trpcOptions: { router: appRouter },
        });
        if (playgroundEndpoint) {
            this.server.register(
                await trpcPlayground.getFastifyPlugin({
                    trpcApiEndpoint: prefix,
                    playgroundEndpoint,
                    router: appRouter,
                    request: {
                        superjson: true,
                    },
                }),
                { prefix: playgroundEndpoint }
            );
        }
    };
}

routes/home/index.ts

import { AbstractRoute } from '../abstract';
import { client } from '../../lib/prismic/client';

export class HomeRoute extends AbstractRoute {
    name = 'home';

    handler = this.trpc.procedure.query(async () => {
        try {
            const page = await client.getByUID('page', 'home');
            if (!page) throw new Error('Home page not found');
            return page;
        } catch (error: any) {
            throw new Error('Failed to fetch homepage: ' + error.message);
        }
    });
}

server.ts

import { Api } from '../api';
import { Env } from '../config/env';
import { Fastify } from '../lib/fastify';
import { Trpc } from '../lib/trpc';

/**
 * The top level server that instantiates the API and starts the server
 *
 * @example
 * const server = new Server()
 * await server.start()
 * await server.stop()
 */
export class Server {
    constructor(
        /**
         * The Env options for the server
         */
        private readonly env = Env.getEnv(),

        /**
         * The Trpc instance the API and routers will use
         *
         * @dependencyinjection
         */
        trpc = new Trpc(),

        /**
         * The API instance the server will use
         *
         * @dependencyinjection
         */
        private readonly api = new Api(trpc),

        /**
         * The Fastify instance the server will use to mount the API
         *
         * @dependencyinjection
         */
        private readonly fastifyServer: Fastify | undefined = undefined
    ) {}

    /**
     * Starts the server
     */
    public readonly start = async () => {
        const server = await this.init();
        return server.start();
    };

    /**
     * stops the server
     */
    public readonly stop = () => {
        return this.fastifyServer?.stop();
    };

    /**
     * Initializes the server if not yet initialized
     *
     * @returns the fastify server
     */
    private readonly init = async () => {
        if (this.fastifyServer) {
            return this.fastifyServer;
        }

        const fastifyServer = new Fastify(
            this.env.PORT,
            this.env.HOST,
            this.env.NODE_ENV === 'development'
        );

        await fastifyServer.registerMetrics();
        await fastifyServer.registerTrpc(
            this.env.TRPC_ENDPOINT,
            this.api.handler,
            this.env.TRPC_PLAYGROUND_ENDPOINT
        );

        return fastifyServer;
    };
}

index.ts

import type { Api } from './api';

export { Server } from './server';

export type AppRouter = Api['handler'];

How to simulate multiple users in a single machine?

I’m trying to make a multiuser web app (multiplayer games/chat room/etc). And I want to test it with multiple users without using many devices and/or using my friend’s help. Let’s say I can open multiple browsers (4-6) on my computer where I can open the inspector in each browser. Also, it’s read as a different user (different IP?) in each browser.

How do you use the value defined in functions, outside of those functions? [duplicate]

I am attempting to create a simple addition calculator using javascript. My plan was to run a function when the button for one with the id “i” was clicked. This function would determine if there was a pre-existing value for “FirstNumberPicked”, and if not it would assign the number one to it. It would also asign the number one to “SecondNumberPicked”, if the reverse happened. Next I created a function that would add the two varrables together, when the answer button in HTML was pressed. Unfortunatly I learnt after reciving “undefined” as my result in the console that variable scope is a thing I then tried to fix it. (The HTML is not shared.)
Current Code in my IDE:

const i = document.querySelector("#i"); // The element with this ID is a button

const answer = document.querySelector("#answer")

let SecondNumberPicked;
let FirstNumberPicked;
i.onclick = onePick
answer.onclick = answerFunction
function answerFunction(params) {
console.log(FirstNumberPicked+SecondNumberPicked);
}
function onePick() {
if (FirstNumberPicked>0) {
let SecondNumberPicked = 1;
}else { let FirstNumberPicked = 1;}
}

I tried to to replace FirstNumberPicked with a variable within the function OnePick, that would then update the real FirstNumberPicked variable outside of the function and then use console.log() to find out if it would update it. I ended up getting the value of undefined for the FirstNumberPicked variable.

How to create a responsive 3D carousel with keen-slider in React?

I’m trying to build a responsive 3D carousel in React using the keen-slider library. My goal is to have a carousel that rotates along the Y-axis, displaying each slide in a circular layout. As the screen size changes, I want the carousel to adjust its layout to stay centered and maintain the 3D effect (be responsive).

I’ve implemented some code, but the carousel does not maintain the central rotation axis as I resize the screen.

import React from "react"
import { useKeenSlider } from "keen-slider/react"
import "keen-slider/keen-slider.min.css"
import "./styles.css"

const carousel = (slider) => {
  const z = 300
  function rotate() {
    const deg = 360 * slider.track.details.progress
    slider.container.style.transform = `translateZ(-${z}px) rotateY(${-deg}deg)`
  }
  slider.on("created", () => {
    const deg = 360 / slider.slides.length
    slider.slides.forEach((element, idx) => {
      element.style.transform = `rotateY(${deg * idx}deg) translateZ(${z}px)`
    })
    rotate()
  })
  slider.on("detailsChanged", rotate)
}

export default function App() {
  const [sliderRef] = useKeenSlider(
    {
      loop: true,
      selector: ".carousel__cell",
      renderMode: "custom",
      mode: "free-snap",
    },
    [carousel]
  )

  return (
    <div className="wrapper">
      <div className="scene">
        <div className="carousel keen-slider" ref={sliderRef}>
          <div className="carousel__cell number-slide1 ">1</div>
          <div className="carousel__cell number-slide2">2</div>
          <div className="carousel__cell number-slide3">3</div>
          <div className="carousel__cell number-slide4">4</div>
          <div className="carousel__cell number-slide5">5</div>
          <div className="carousel__cell number-slide6">6</div>
        </div>
      </div>
    </div>
  )
}

and i have this CSS code:

  .wrapper {
    display: flex;
    justify-content: center;
    flex: 1;
  }
  .scene {
    width: 100%;
    height: 200px;
    perspective: 1000px;
    position: relative;

    background-color: red;
  }
  .scene .carousel.keen-slider {
    width: 100%;
    height: 100%;
    position: absolute;
    overflow: visible;
    transform: translateZ(-288px);
    transform-style: preserve-3d;
  }
  .carousel__cell {
    position: absolute;
    width: 240px;
    left: 10px;
    height: 200px;
    border: 1px solid rgba(0, 0, 0, 0.3);
  }
  

I’d like each slide to maintain a fixed aspect ratio and remain responsive, adjusting their size based on screen width without breaking the 3D effect, so i know that i need to change the carousel__cell class, but witch fluid measure i should use?

Thanks.

Removing dynamically added event listener does not work

My app has a feature that allows the user to select a unit. In the background, the app will append an event listener for example, to sum a dynamically added <td> element inside the table or when then selected unit is a date then make the <td> a datepicker.

Now, the above feature works perfectly fine yet there is one problem that I am stuck with.

selectUnit.addEventListener("change", function (e) {
                            e.stopPropagation();
                            const tds = trElement.querySelectorAll('td[data-bs-type="unitType"]');   
                            const consolidatedTD = trElement.querySelector("td[data-bs-cns='cns']");
                            const targets = trElement.querySelectorAll("td[data-bs-tgt='tgt']"); 
                            
                            if (tds) { 
                                const unitType = selectUnit.value;   
                                tds.forEach(td => {
                                    td.textContent = '';
                                    const fpInstance = td._flatpickr;

                                    if (td.contentEditable === 'true') {
                                        // Remove all relevant input listeners
                                        td.removeEventListener("input", validateInputTD);
                                        td.removeEventListener("input", validateInputValueTD);

                                        if (targets) {
                                            // Use the function with bound targets and consolidatedTD
                                            targets.forEach(t => {
                                                console.log(t);
                                                t.removeEventListener("input", () => updateConsolidatedValue(targets, consolidatedTD));
                                            });
                                        }

                                        if (unitType == 1) {
                                            td.addEventListener("input", validateInputValueTD); 

                                            // Add the event listeners to the targets
                                            targets.forEach(t => {
                                                t.addEventListener("input", () => updateConsolidatedValue(targets, consolidatedTD));
                                            });

                                        } else if (unitType == 2) {
                                            td.addEventListener("input", validateInputTD);
                                        } else {
                                            td.textContent = "Select date";
                                            flatpickr(td, {
                                                onChange: function (selectedDates, dateStr) {
                                                    td.textContent = dateStr;  // Update the td with selected date
                                                }
                                            });
                                        }

                                        if (fpInstance) {
                                            fpInstance.destroy();
                                        }
                                    }
                                });  
                            } 
                        });

As you can see here on the above code.

I am appending to sum the value of each target <td> when the selected unit is value but when I changed it to another unit, this the event listener is removed yet the functionality of adding the content of the td is still summed up.

function updateConsolidatedValue(targets, consolidatedTD) {
            consolidatedTD.textContent = "";

            // Reset consolidatedValue for each input event
            let consolidatedValue = 0;

            // Recalculate the consolidated value based on current target values
            targets.forEach(t => {
                consolidatedValue += parseInt(t.textContent) || 0;
            });

            // Update the consolidatedTD with the new total
            consolidatedTD.textContent = consolidatedValue;
    }

How can I removed this listener when the value of the select element is changed only to value?

date-fns function returns incorrect response for isSameDay; So does javascript comparison

I have been using the date-fns function “isSameDay” to test if two actions take place on the same day. The function is given two standard javascript date objects. We recently found a bug where the isSameDay function returns false if the two dates are the same, but one of the two date objects has a time after 7pm.

const sameDay = isSameDay(date1, date2);

To make it confusing, the function returns true when run locally, but false on the server. I believe that this has something to do with the time zone difference between me locally and the server.

My expectation was that the date-fns functions would not be affected by being run in a different time zone as the date-time objects it is being given are all UTC.

When I first started looking at this, I took the two date-time objects and ran getFullYear, getMonth, and getDate and then compared those two items and got a false again when one date-time object was after 7pm – same as with the date-fns function.

There are options in the isSameDay function that may be able to handle the issue at hand, but the documentation doesn’t explain it well enough.

What I have had to do as a work around is to create two strings for the two dates in question after forcing those dates to be central time zone and then compare the strings.

Can anyone explain if/how options can be used so that the isSameDay function works correctly?

ESlint doesn’t allow to build nextjs 15 app because of unused error variable in a try catch

I’m learning nextJS 15 and I’m making an app using the pokeAPI but when I run npm run build eslint gives me the following message:

Error: ‘error’ is defined but never used. @typescript-eslint/no-unused-vars

The following code is the one producing the error:

const getPokemon = async (id: string) => {
    try {
        const pokemon = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`, {
            cache: "force-cache"
        }).then(res => res.json());
        return pokemon;
    } catch (error) {
        notFound();
    }
};

Is there a way to ignore that unused variable specifically?

Here’s the .eslintrc.json:

{
    "extends": ["next/core-web-vitals", "next/typescript"]
}

I tried the no-unused-vars rule but it didn’t work

I have being trying to submit this form for a product but since almost 1 week I can’t but when I make the form as an axternal file it works [closed]

Trying to submit a form for a product addition

I try to submit a form it turns, but no addition to the databases, tried it several times but nothing
But when I change and instead put the form as a external php file on its own it works….and I don’t really see what the problem is with this page

The php code here is the select from the tables so on this same page I want to print and submit products but when I submit it no product added don’t really know if did something wrong on this page specifically

      </style>

            <!-- <a href="add.php" style="padding-left: 88%;"><button class="view" style="background-color: lightseagreen;">+ AddNew</button></a> -->

            <button class="view"
               onclick="togglePopup()"  style="width: 160px; background-color: lightseagreen;">+ AddNew</button>

               <a href="add11.php">+ AddNew</a>

        <div class="report-container">
            <div class="report-header">
                <h1 class="recent-Articles">Products Info</h1>
                <button class="view"><?=count($productss)?> Products</button>
                <button class="view">Products List</button>
                <!-- <div class="view" width="10px">Products List</div> -->
            </div>

            <div class="report-body">
                <div class="report-topic-heading">
                    <h3 class="t-op" style="margin-right: 60px;">Product Image</h3>
                    <h3 class="t-op" style="margin-right: 60px; margin-left: 30px;">Category</h3>
                    <h3 class="t-op" style="margin-right: 70px; margin-left: 40px;">Name</h3>
                    <h3 class="t-op" style="margin-right: 60px; margin-left: 30px;">Price</h3>
                    <h3 class="t-op" style="margin-right: 60px; margin-left: 30px;" >Quantity</h3>
                    <h3 class="t-op" style="margin-right: 60px; margin-left: 30px;">Actions</h3>
                    <hr>
                </div>

                <div class="items">
                       <?php foreach($productss as $item){
                                        
                                         $sql = "SELECT * FROM product_category WHERE category_id = :id";
                                            $statment = $db->prepare($sql);
                                            $statment->bindvalue(':id', $item["category_id"], PDO::PARAM_INT);
                                            $statment->execute();
                                            $product_categorys = $statment->fetchAll(PDO::FETCH_ASSOC);
                                            $product_category=$product_categorys[0];
                                            $item["category_names"]=$product_categorys[0]["category_name"];
                 ?>
                
                    <div class="item1"> 
                        <h3 class="t-op-nextlvl" style="margin-right: 60px;"><img src="../upload/<?=$item["product_image"]?>" width="80px"></h3>
                        <h3 class="t-op-nextlvl" style="margin-right: 60px; margin-left: 30px;"><?=$item["category_names"]?></h3>
                        <h3 class="t-op-nextlvl" style="margin-right: 60px; margin-left: 30px;"><?=$item["name"]?></h3>
                        <h3 class="t-op-nextlvl" style="margin-right: 60px; margin-left: 30px;"><?=$item["price"]?></h3>
                        <h3 class="t-op-nextlvl" style="margin-right: 60px; margin-left: 30px;"><?=$item["qty"]?></h3>
                    <hr>
                          
                    <form method="POST" action="" style="display: flex; flex-direction: row;">    
                    <h3 class="t-op-nextlvl" style="margin-right:46px;"><a href="Delete.php?id=<?=$item['product_id']?>"><img src="../Icons/delete.png" width="30px" alt=""></a></h3>
                         <input type="hidden" value="<?=$item['product_id']?>" name="id" id="">
                             <button name="submitbtn" type="submit" style="border: none;"><img src="../Icons/edit.png" alt="edit" width="35px"></button>
                    </div>
                    <?php
                }
                  ?>
                </div>
            </div>
        </div>




        <div id="popupOverlay"  class="overlay-container" style="padding-bottom: 30px">
<div class="popup-box" style="width: 570px;">
    <h2 style="color: green;">Add A Product</h2>


        <form method="post" action="" enctype="multipart/form-data" style="padding-top: 20px; padding-left: 40px;">
    <div id="feedback-form">
        <h2 class="header">New Product</h2>
        <div>
            
        <section>
          <div class="select-containers">
     <select class="select-box" name="category_id" id="">
        <option value="" selected disabled>
          Choose The Product Category
        </option>
        <?php 
        foreach($product_categoryss as $item1){
           ?>
           <option value="<?=$item1["category_id"]?>"><?=$item1["category_name"]?></option> 
           </div>
           <?php
        }

        ?>
        
        <input type="text" name="name" placeholder="Product Name" required></input>
          
        <input type="number" name="price" placeholder="price" required></input>

        <input type="number" name="qty" placeholder="Quantity" required></input>

        <input type="text" name="description" placeholder="description" required></input>

        <input type="file" name="product_image" placeholder="Main Image" required></input>
    
        <input type="file" name="product_image1" placeholder="Image1" required></input>

        <input type="file" name="product_image2" placeholder="Image2" required></input>

        <input type="file" name="product_image3" placeholder="Image3" required></input>

        <input type="file" name="product_image4" placeholder="Image4" required></input>


            <button type="submit">Submit</button>
            </section>
    <!-- <center>
        <input type="reset" class="btn btn-dark" value="Cancel">
        <input type="submit" class="btn btn-primary" name="envoyer" value="Add">
    </center>     -->
  </form>

  
  <button class="btn-close-popup" onclick="togglePopup()">Close</button>
</div>

XSRF-TOKEN won’t change a second time

I’m creating a single page form that won’t reload the page after submitting the form. I’m currently at the stage where I first get messages like I filled something in incorrectly (that’s ok), but then when I click the button again, I get err 419. I noticed, in Applications DevTool, that the first time both XSRF-TOKEN and laravel_session change, but the next time I submit the form, only laravel_session changes.How to prevent it and how to fix it? Thank you

Step by Step:

  1. I come to the page, of course I have a new laravel_sesion + XSRF token

  2. I click on the form – a new laravel_session + XSRF token is then generated

  3. I click on the form again – only laravel_session is generated

    @section('content')
    @include('notifications')
    @if(config('register.register'))
        <div style="text-align: center">
            {!! Html::form('POST', route('auth.register.register'))->id('registerForm')->class('form-horizontal')->open() !!}

            @if($hash)
                <div class="form-group">
                    {!! Html::label('reflink_hash', trans('translate.promo_code_label_user'))->class('control-label col-sm-3')->attribute('data-translate-key', 'promo_code_label') !!}
                    <div class="col-sm-8">{!! Html::text('reflink_hash', $hash)->class('form-control')->readonly()->attribute('data-translate-key', 'promo_code_placeholder_user') !!}</div>
                </div>
            @endif

            <div class="form-group">
                {!! Html::label('username', trans('translate.login'))->class('control-label col-sm-3')->attribute('data-translate-key', 'login') !!}
                <div class="col-sm-8">{!! Html::text('username')->class('form-control')->attribute('data-translate-key', 'login_placeholder') !!}</div>
            </div>

            <div class="form-group">
                {!! Html::label('password', trans('translate.password'))->class('control-label col-sm-3')->attribute('data-translate-key', 'password') !!}
                <div class="col-sm-8">{!! Html::password('password')->class('form-control')->attribute('data-translate-key', 'password_placeholder') !!}</div>
            </div>

            <div class="form-group">
                {!! Html::label('password_confirmation', trans('translate.confirm_password'))->class('control-label col-sm-3')->attribute('data-translate-key', 'confirm_password') !!}
                <div class="col-sm-8">{!! Html::password('password_confirmation')->class('form-control')->attribute('data-translate-key', 'password_placeholder') !!}</div>
            </div>

            <div class="form-group">
                {!! Html::label('email', trans('translate.email'))->class('control-label col-sm-3')->attribute('data-translate-key', 'email') !!}
                <div class="col-sm-8">{!! Html::email('email')->class('form-control')->attribute('data-translate-key', 'email_placeholder') !!}</div>
            </div>

            <div class="form-group">
                {!! Html::label('code', trans('translate.code_delete_char'))->class('control-label col-sm-3')->attribute('data-translate-key', 'code_delete_char') !!}
                <div class="col-sm-8">{!! Html::text('code')->class('form-control')->attribute('maxlength', '7') !!}</div>
            </div>

            <div class="form-group">
                {!! Html::label('pin', trans('translate.pin'))->class('control-label col-sm-3')->attribute('data-translate-key', 'pin') !!}
                <div class="col-sm-8">{!! Html::text('pin')->class('form-control')->attribute('maxlength', '4')->attribute('data-translate-key', 'pin_placeholder') !!}</div>
            </div>

            <div class="form-group">
                <div class="col-sm-offset-3 col-sm-8" style="width: 304px; margin:0 auto 10px auto">
                    {!! Html::label('captcha', trans('translate.captcha'))->class('control-label col-sm-3')->attribute('data-translate-key', 'captcha') !!}
                    {!! app('captcha')->display() !!}
                </div>
            </div>

            <div class="form-group">
                <div class="checkbox">
                    <label>
                        <input type="checkbox" name="checkbox">
                        <span data-translate-key="terms">{{ trans('translate.accept_terms') }}</span>
                        <a href="{{ route('main.rules.index') }}"><b data-translate-key="tos">{{ trans('translate.tos') }}</b></a>
                        <span data-translate-key="terms">{{ trans('translate.terms_end') }}</span>
                    </label>
                </div>
            </div>

            <div class="form-group">
                <button type="submit" name="create-account" value=" "><span data-translate-key="register">{{ trans('translate.register_me') }}</span></button>
            </div>

            {!! Html::form()->close() !!}
        </div>
    @else
        <div class="alert" data-translate-key="registration_unavailable">{{ trans('translate.registration_unavailable') }}</div>
    @endif

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#registerForm').on('submit', function(event) {
                event.preventDefault(); // Zabrání obnovení stránky

                $.ajax({
                    url: $(this).attr('action'),
                    method: 'POST',
                    data: $(this).serialize(),
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    success: function(response) {
                        if (response.status === 'success') {
                            alert(response.message); // Úspěšná registrace
                            // Přesměrování nebo aktualizace UI
                        } else {
                            alert(response.message); // Zobrazení chyby
                        }
                    },
                    error: function(xhr) {
                        alert('Err');
                    }
                });
            });
        });
    </script>
@endsection

TauriV2 – access to files, directories and subdirectories

I’m trying to access all files, directories and subdirectories within a directory in the $HOME directory in a Tauri App (Svelte as frontend, but I don’t think that matter).
The file system looks something like

$HOME
  - project-dir
    - file.txt
    - .hidden
      - config.json

I need to have access to everything inside the project-dir directory.
My capabilities.json looks like

 "permissions": [
        "fs:default",
        {
            "identifier": "fs:scope",
            "allow": [
                {
                    "path": "$HOME/project-dir/**"
                },
                {
                    "path": "$HOME/project-dir/**/*"
                }
            ]
        }
    ]

I manage to read files in the project-dir directory, but not nested files (Unhandled Promise Rejection: forbidden path), and also apparentyle I haven’t allowed the use of the fs.watch function

Unhandled Promise Rejection: fs.watch not allowed

When accessing the files I use the path API to create the path to files, but still can’t access that nested config.json file.
Anyone can help me configuring the capabilities file?

Wait Until For Loop Completes In Javascript

Say I have a for loop inside a function like this:

function test() {
    for(let i = 0; i < 10; i++) {
        console.log(i) ;  
    };
    return;
};

This works, but the function returns before the for loop is done. How do I make it wait until the for loop is done to return?

I have tried using deffrent combonations of awaits andpromisesand searched a lot on Google, but have not found anything.

Coloring Sankeyplot links based on source nodes – issue with (sankeyNetwork::colourScale)

I’m trying to assign colors to links within a Sankey diagram command in Rstudio. Specifically, I would like the links to be colored by their source node group (SOF_Data$Species_Binomial).

The links and nodes already display properly, but when the command to color links is included (sankeyNetwork::colourScale), the diagram displays blank. Additionally, the command to color nodes (sankeyNetwork::NodeGroup) displays as the default blue, regardless of the color input from nodes_SOF_Data$color.

Starting data frame, node list creation:

library(dplyr)
library(networkD3)
library(htmlwidgets)
library(data.table)

SOF_Data <- data.frame(
  Species_Binomial = c("C. artedi", "C. artedi", "C. artedi", "C. artedi", "C. artedi", "C. artedi", "C. fera", "C. fera"),
  Life_Stage = c("Larva/fry", "Embryotic/egg", "Embryotic/egg", "Embryotic/egg", "Embryotic/egg", "Larva/fry", "Embryotic/egg", "Larva/fry"),
  Effect_Category = c("Growth", "Growth", "Survival", "Growth", "Growth", "Growth", "Growth", "Growth"),
  Categorical_Effect = c("Growth rate", "Other - Specific", "Survival - Specific", "Development rate", "50% hatching time", "Growth rate", "Development rate", "Otolith growth"))
 
nodes_SOF_Data <- data.frame(name = unique(c(
  SOF_Data$Species_Binomial,
  SOF_Data$Life_Stage,
  SOF_Data$Effect_Category,
  SOF_Data$Categorical_Effect))) 
nodes_SOF_Data$color <- "#000"

Links creation:

links1_SOF_Data <- SOF_Data %>%
  group_by(Species_Binomial, Life_Stage) %>%
  summarize(value = n()) %>%
  ungroup() %>%
  mutate(source = match(Species_Binomial, nodes_SOF_Data$name) - 1,
         target = match(Life_Stage, nodes_SOF_Data$name) - 1,
         LinkGroup = Species_Binomial)

links2_SOF_Data <- SOF_Data %>% 
  group_by(Species_Binomial, Life_Stage, Effect_Category) %>% 
  summarize(value = n()) %>% 
  ungroup() %>% 
  mutate(source = match(Life_Stage, nodes_SOF_Data$name) - 1,
         target = match(Effect_Category, nodes_SOF_Data$name) - 1,
         LinkGroup = Species_Binomial) 

links3_SOF_Data <- SOF_Data %>% 
  group_by(Species_Binomial, Effect_Category, Categorical_Effect) %>% 
  summarize(value = n()) %>% 
  ungroup() %>% 
  mutate(source = match(Effect_Category, nodes_SOF_Data$name) - 1,
         target = match(Categorical_Effect, nodes_SOF_Data$name) - 1,
         LinkGroup = Species_Binomial)

links_SOF_Data <- bind_rows(links1_SOF_Data, links2_SOF_Data, links3_SOF_Data)

links_SOF_Data <- links_SOF_Data %>%
  mutate(color = case_when(Species_Binomial == "C. artedi" ~ "#66c2a5", 
Species_Binomial == "C. fera" ~ "#e78ac3"))

Sankey graph code:

colour_scale_species <- JS("function(d) { return d.color; }")

sankey_SOF_Data <- sankeyNetwork(Links = links_SOF_Data, 
                                 Nodes = nodes_SOF_Data, 
                                 Source = "source", 
                                 Target = "target", 
                                 Value = "value", 
                                 NodeID = "name", 
                                 units = "Count", 
                                 fontSize = 12, 
                                 nodeWidth = 30, 
                                 NodeGroup = "color", 
                                 LinkGroup = "LinkGroup", 
                                 colourScale = colour_scale_species)
sankey_SOF_Data

I’ve tried imbedding a color hex code column in the links_PaperData column and calling directly from that, although it doesn’t seem to fix the issue.