Dynamic use of fragment in Thymeleaf – Spring Boot / reload a part of a page dynamically onChange/onClick whatever

as the title indicates, I am trying to create a page, more precisely a form which part of it must be reloaded when an element of the page is changed (onChange)

I use Thymeleaf for the frontend and Spring Boot for the backend.

Theoretically in Thymeleaf, we are supposed to send directly via the controller the fragment and receive it as a complete fragment.

By putting “model.addAttribute()” inside the Get request for the fragment, + having well made the page of our fragment on the thymeleaf side, it’s supposed to do things automatically, that is to say give me the fragment already built in hand when I’m going to make a call via the fetch or via an ajax in order to receive the response (the fragment).

So I’ll just need to take the part of the page I want to replace via a getElementById and do a “.load(response)”

The problem is that I get a string and not the constructed fragment …

That is, I get “fragments/underHeadingList :: input”, as a String. I guess it doesn’t work.

However, when I put,

div th:replace=”fragments/underHeadingList :: input”>

directly in my code, it works and calls the fragment

The problem of course is that the list that this fragment is supposed to display, changes depending on the element selected during the onChange …

Material UI select component doesn’t showthe selected value

I have a select component and I can see the menu items and also select them but the component doesn’t show the selected value. It’s handle function works well becauese when I selected an item the the value in the database is updated

Here is the code part from it:

handleSelect(event){
        this.props.handleChange(event);
    }

render() {

    const values= {
        "1": translation.getText("SAMEWINDOW"),
        "2": translation.getText("NEWWINDOW"),
        "3": translation.getText("NEWTAB")
    };

    return(

        <Select
            name="code"
            value={values[this.props.data.code]}
            onChange={this.handleSelect}
        >
            {Object.keys(values).map((item) => (
                <MenuItem value={item}>{values[item]}</MenuItem>
            ))}
        </Select>
    )
}

I tried to change the object keys type from string to number, but it didn’t help

how to toggle my navbar to slide over in mobile view?

I want my navbar to slide over by clicking on its icon in mobile view, but I’m having some problem with that. It’s not sliding over by clicking. I’m sure I have followed the right js syntax for it.

html

        <div class="navbar mx-auto ">
            <a asp-action="Index">صفحه اصلی</a>
            <a href="#products">محصولات</a>
            <a href="#about">درباره ما</a>
            <a href="#contact">ارتباط با ما</a>
        </div>
        <div class="icons">
            <i class="fa-solid fa-cart-shopping "></i>
            <i class="fa-solid fa-magnifying-glass "></i>
            <i class="fa-solid fa-right-to-bracket "></i>
            <i class="fa-solid fa-bars" id="menu-btn"></i>
        </div>

CSS

    .header .navbar {
        position: absolute;
        top: 100%;
        left: -100%;
        background: #13131a;
        width: 30rem;
        height: calc(100vh - 9.5rem);
        align-items: flex-start;
        flex-direction: column;
        justify-content: flex-start;
        overflow: hidden;
    }


    .header .navbar .active {
        left: 0;
    }

javascript

let navbar = document.querySelector(".navbar");
document.querySelector("#menu-btn").onclick = () => {
    navbar.classList.toggle("active");
}

I just don’t know where I’m going wrong.
It should’ve worked

‘Absolute’ position gets moved by elements from list React Native

I want to have a fixed button on the right bottom side of the screen, but it moves depending on the items that are mapped/rendered in the list. If there are a lot of jobs then it’ll move to the bottom, but if there is only 1 item in jobs list then the button will show on top:

  return (
    <View>
      <View style={generalStyles.container}>
        {jobs.map((job, i) => (
          <TouchableOpacity style={generalStyles.jobListItem} index={i} key={i} onPress={() => console.log(job + 'got clicked uwu')}>
            <Text style={generalStyles.jobListItemText}>
              {job}
            </Text>
            <IconButton style={generalStyles.jobListItemIcon} icon={props => <MaterialIcon name="add-box" {...props} size={70} />} color={colors[3]} />
          </TouchableOpacity>
        ))
        }
      </View>
      <View> //Button moves depending on how many jobs there are
        <IconButton
          onPress={() => console.log('route to add new job screen')}
          style={generalStyles.homeAddJobButton}
          icon={props => <IonIcon name='add-circle-sharp' {...props} size={100} color={colors[5]} />}
        />
      </View>
    </View>
  );

The stylings are as followed:

 jobListItem: {
    backgroundColor: colors[1],
    padding: 30,
    marginVertical: 2,
    borderRadius: 7,
    alignItems: 'center',
    flexDirection: 'row'
  },

  homeAddJobButton: {
    height: 100,
    width: 100,
    borderRadius: 999,
    position:'absolute',
    alignSelf:'flex-end',
    bottom: 50
  },

If I comment everything out except the <IconButton/> then it’s in the correct position, but when I add the other components it starts positioning incorrectly. Anybody know why it doesn’t keep its position fixed?

Why does Bootstrap 5’s getOrCreateInstance() method for collapsibles immediately toggle the element?

I’ve not had to work with the Collapse feature in Bootstrap 5 until today and I strongly dislike it!

If I have a simple setup with a collapsible element – hidden initially – and a button to toggle its visibility, like this:

<button class="btn btn-primary" id="toggleDetails">Show Details</button>
<div class="collapse border mt-2 p-2" id="details">
    Here is some information.
</div>

and some Javascript like this:

const details = document.getElementById("details");
const detailsCollapse = bootstrap.Collapse.getOrCreateInstance(details);

const btn = document.getElementById("toggleDetails");
btn.addEventListener("click", (e) => {
    detailsCollapse.toggle();
});

why does the getOrCreateInstance toggle the collapsible element’s visibility? Surely its only job is to get the collapse instance. It’s absolutely infuriating. Am I doing something wrong? If not, how I get the collapse instance without toggling it? Obviously in my actual code the setup is more complex than this but this issue is currently holding me up.

There’s a fiddle showing the problem here.

Exist any workaround for limit size of variable in javascript?

I am trying scrape some data from an website using Tumpermonkey Browser Addon & Javascript. The goal it’s to ‘export’ parts of info into a .CSV/.txt file and than download it and Import into google SpreadSheet to do my calcs on future.

My script is working when i run in a page with +/- 270 results/lines/rows.

Problem is when i go to the page with + than 2000 results/lines/row. For this page I add more 1 variable to pick a “rarity link” class. BUT when scraping, the script/console stucks/loops on value/cicle +/-1065 results/lines/rows. and keeps in loop on that value (1065) with no data and dont finish.

I think is some problem about Variable size limit?!?.

I am some days thinking & work about an workaround for this, like Replace the a full http link in a text Word if that link include specific word, but without success, i am newer in javascript maybe the “logic” is wrong on my script.
I have tried at different browsers (Firefox and Brave) with last stable version of Tampermonkey, I have increased to disk.cache size and enable disk.smart options to in ‘about:config’ browser menus.

Script Work:

1- Detect if contains X quantity of Pieces after page loaded

2- When reach all Pieces/End of page/Last Piece in the ‘for’ cicle. Will prepare the Variable (allDump) as a file and download it as .csv.

The Scrapping code and Download zone:

(function() {
'use strict';
 // Move BOTH: 0-2500 || 1-270
let piecetabsel = 0; // 0 = zone of +2000 rows Status: PROBLEM!   ||   1 = Zone of >280 Rows Status:OK
let totalpieces = 2500;  // 2500rows/line   ||   270rows/lines

let piecenamea = '';
let piecebonusa = '';
let piecepowera = '';
let themnrimage = '';
let pieceDumpFile = '';
let piecerarity = '';

var piecedumper = function(totalpieces){
    var countpieces = totalpieces - 1;
    var intra3 = setInterval(function(){
        for (koko; countpieces >= koko; koko++) {
            console.log("ID:" + koko);
            // >280 Pieces zone
            if (piecetabsel == 1){
                piecenamea = document.getElementsByClassName('piece-name')[koko].innerHTML;
                piecebonusa = document.getElementsByClassName('extra-value')[koko].innerHTML;
                piecepowera = document.getElementsByClassName('the-power')[koko].innerHTML;
                themnrimage = document.getElementsByClassName('photo-link')[koko].currentSrc;
                if(pieceDumpFile === ""){ pieceDumpFile = 'Common;' + piecenamea + ';' + piecebonusa + ';' + piecepowera + ';' + themnrimage + 'n'; }
                if(pieceDumpFile !== ""){ pieceDumpFile = pieceDumpFile + 'Common;' + piecenamea + ';' + piecebonusa + ';' + piecepowera + ';' + themnrimage + 'n'; }
            }
            // +2000 pieces zone - STUCK ZONE one 1065
            if (piecetabsel == 0){
                piecenamea = document.getElementsByClassName('collection-product-name')[koko].innerHTML;
                piecebonusa = document.getElementsByClassName('collection-bonus-amount')[koko].innerHTML.replace(/[+ ]/g, '').replace(".", ",");
                piecepowera = document.getElementsByClassName('power-value')[koko].innerHTML.replace(".", "");
                piecerarity = document.getElementsByClassName('collection-product-level-img-size-2')[koko].currentSrc;
                //
                // same has 270pieces zone ... BUT. with my workaround to decrease var size. NO SUCCESS
                if (piecerarity.includes('lv_2')) { pieceraritya = 'Uncommon'; }
                else if (piecerarity.includes('lv_3')) { pieceraritya = 'Rare'; }
                else if (piecerarity.includes('lv_4')) { pieceraritya = 'Epic'; }
                else if (piecerarity.includes('lv_5')) { pieceraritya = 'Legendary'; }
                else if (piecerarity.includes('lv_6')) { pieceraritya = 'mythic'; }
                else if (piecerarity.includes('lv_7')) { pieceraritya = 'SpecialOnes'; }
                else { pieceraritya = 'Common'; }
                if(pieceDumpFile === ""){ pieceDumpFile = pieceraritya + ';' + piecenamea + ';' + piecebonusa + ';' + piecepowera + 'n'; }
                if(pieceDumpFile !== ""){ pieceDumpFile = pieceDumpFile + pieceraritya + ';' + piecenamea + ';' + piecebonusa + ';' + piecepowera + 'n'; }
            }
        }
        clearInterval(intra3);
        var allDump='Rarity;Name;Power;Extra;Photon'+pieceDumpFile;
        downloadZone(allDump);
    }, 9000);
}
var downloadZone = function(allDump){
    var data=allDump;
    var a = document.createElement("a");
    a.href = 'data:application/csv;charset=utf-8,' + encodeURIComponent(data);
    a.download = 'MyInfoScrapper.csv';
    console.log("Generate CSV File and Downloading");
    a.click();
}
piecedumper(totalpieces);
})();

I am Expecting some Ideas/workarounds/solution for my situation, i am out of ideas.
Maybe, something to do some ‘File-Part1.csv.’ ‘File-Part2.csv’ ?!

Why does a Promise.prototype.someMenthod is not working?

I was writing a polyfill for the Promise.all() using the concept of Prototypal Inheritance where I am chaining the myAll method to the prototype of the Promise.

Promise.prototype.myAll = function(iterable) {
const temp = [];
for (let i = 0; i < iterable.length; i++) {
    iterable.then((res)=>temp.push(res)); // resolving every promise
}

return Promise.resolve(temp);
};

const pp = Promise.myAll([a,b,c]); // Throws an error Promise.myAll is not a function

Can someone please expain why it is not working?

Is it bad practice to process payload in FE for an endpoint that can do it in BE?

Given the following payload to a POST endpoint

{
  "name": "this is a test",
  "key": "this_is_a_test",
}

The property key is made entirely based on the name key, which is taken from a UI form.

The question is:

Should the frontend process the snake case for the key property before sending to the endpoint or should it send only name property and let backend process it?

The GET request for this endpoint will use both fields in the application afterwards.

How to cache three.js Object3D in cache?

I am new to three.js and want to understand how can I cache the 3D models/Object3D to reduce the loading time of 3D models (collada)

I am using collada loader to load dae file in three.js based viewer. It works fine but I also want to understand how can I cache the model so that model picks it from disk cache and not load the entity again to reduce the loading time.
collada model not loading from disk cache

Hiding all image and video on twitter embedded timelines

I am trying to hide all image and video on twitter embedded timelines but it’s doesn’t work.

I trying this code

<div id='tweet-timeline'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
 <script src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
    <script type="text/javascript">
        twttr.widgets.createTimeline({
            sourceType: 'profile',
            screenName: 'windowsdev'
        }, document.getElementById('tweet-timeline'), {
            width: "469",
            height: "520",
            chrome: 'noheader, nofooter, noborders, transparent, noscrollbar',
            related: 'windowsdev,twitterapi'
        }).then(function(el) {
            $("#twitter-widget-0").contents().find('.Image').css("display", "none");
        });
    </script>

but it’s doesn’t work.

How to perform backend to backend authentication/authorization with Strapi?

I want to use Strapi as a database, so I need only one superuser that will be used by my backend to access protected Strapi endpoints.

So far in my research, all authentication scenarios involve getting a JWT first, and using it in the request authorization header:

const res = await fetch('http://localhost:1337/api/restaurants', {
    headers: {
      Authorization: `Bearer ${jwt}`
    }
});

So my questions are:

Is there another approach for backend-to-backend authentication with Strapi?

If I have to fetch the JWT first (like below for example), where should I save it, and how to keep it in sync with refresh operations?

const res = await fetch(`http://localhost:1337/api/auth/local`, {
    method: 'POST',
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({ identifier, password }),
});
const jwt = (await res.json()).jwt; 

Inexplicable javascript performance test

I was testing different algorithms to find the number of characters of a number and I found this

const nbLoop = 100000000;
const num = 187378654;

console.time("nbChar");
for (let i = 0; i < nbLoop; i++) {
  `${num}`.length;
}
console.timeEnd("nbChar"); // ~160ms
const nbLoop = 100000000;
const num = 187378654;

console.time("nbChar");
for (let i = 0; i < nbLoop; i++) {
  `${num*1}`.length; // num*1 or num+1
}
console.timeEnd("nbChar"); // ~40ms

The same algorithm by switching num to num+1 or num*1 is 4 or 5 times faster

Does someone has an explication ?

P5js imported in vscode doesn’t load image

So I am using this library, which basically is threejs imported in p5js and I wanted to import an image however it is saying the file path is wrong

Code for importing the image:

function preload() {
    img = loadImage("Sea_tilemap.png");
  }

error:
enter image description here

file management:

enter image description here

If anybody knows how to fix it thank you. I also tried storing the image on Imgur and getting the link form there and putting it in the same path link, but it gives the same problem and also a CORS one

Thank you once again

Is it possible to import js file dynamically in Vue 3?

I need to import a js file dynamically via env. So far I was not be able to do it.
I tried these 2 methods but they are failing.

import app from "@/constants/app." + process.env.NODE_ENV + ".js";

const app = () => import("@/constants/app." + process.env.NODE_ENV + ".js");

Last one is not failing but output is something different.
In the picture app is my actual js file.
app1 is when I use const app = () => import("@/constants/app." + process.env.NODE_ENV + ".js");

Do you know any way to import file dynamically?
Thank you.

enter image description here