Variables in classes don’t work with tailwind css + react to change a color

does anyone know why, when using Tailwind CSS in a class and attempting to use a state variable (in this case, I am using React), the color changes in the DOM, but nothing changes in the user interface?

interface CustomButtonProps {
    color: string;
    borderRadius: string;
    buttonText: string;
    colorText: string;
}

const CustomButton: React.FC<CustomButtonProps> = ({ color, borderRadius, buttonText, colorText }) => {


    return (
        <button className={`bg-[${color}] rounded-${borderRadius} px-4 py-2 text-[${colorText}]`}>
            {buttonText}
        </button>
    );
};

export default CustomButton;

Inspecting the page, the color of the text and the background of the class do change, but on the interface side, nothing happens.

Is it a Tailwind issue? Is there something I should do in the Tailwind setup file? Because if I manually set it in the code as bg-[#000], it works, but if I set it dynamically, in this case, I’m using a color picker, the state variable changes, the class changes too, but on the interface side, nothing happens. Thanks in advance to anyone who can help me.

I want to change the colors of my button in real-time as my state variables change.

how to compare key/value from array and update different value exists

I have two array arr1 and arr2 from where I need to check if arr1 having same key with different value then arr1 updates the arr2’s value.

const arr1 = [{
        text: 'status',
        value: 'status',
        hide: false,
        validate: true,
        sort: true
    },
    {
        text: 'address',
        value: 'add',
        hide: false,
        validate: true,
        sort: true
    },
    {
        text: 'Last Name',
        value: 'lname',
        hide: false,
        validate: true,
        sort: true
    },
    {
        text: 'First Name',
        value: 'fname',
        hide: false,
        validate: true,
        sort: true
    },
    {
        text: 'age',
        value: 'age',
        hide: false,
        validate: true,
        sort: true
    },
];

const arr2 = [{
        text: 'status',
        value: 'status',
        show: false
    },
    {
        text: 'address',
        value: 'add',
        show: false
    },
    {
        text: 'Last Name',
        value: 'lname',
        show: false
    },
    {
        text: 'First Name',
        value: 'fname',
        show: true
    },
];

update the arr1 if value matched in both array update the rest value. for example status matched then arr1 should be {text: ‘status’, value: ‘status’, hide: true, show: false, validate: true, sort: true}.

Hide value gets true because show value false if show value is true and hide will be false.

Is there a way to detect if a file doesn’t exist in Javascript?

I’m a noob so sorry in advance lol.

HELPFUL BUT LIKELY UNECESSARY CONTEXT:

I’m trying to make a “previous” and “next” button in html. When pressed, the image on screen will change to either the previous image, or the next image depending on the button (like flipping a page in a book). This wouldn’t be too big of an issue, except that I have very little idea on how to get a list of the images I have without doing it manually (I want to have the potential of 50+ images, and don’t want to change the list every time I add one)

THE ACTUAL PROBLEM:

I’m trying to make a For Loop in javascript that for every number added, will correspond to a file in a folder which will then be added to a list. Is this possible? (code below, I’m sure that there are silly mistakes but that’s not my concern at the moment)


for(var i = 1; until file is not detected; i++){
     list = list + "fileNumber"+i+".png";
     return list
     }   

//alternatively, would something like this be better? 
//(mild pseudocode warning, try to hold in your barf)

for (var i = 1; 1<2;i++){
     if "filenumber"+i+".png" does not exist:
          return list 
          break
     else:
          list = list +"filenumber"+i+".png"
}


When its done, the list should look like this:

”’
list = [fileNumber1.png, fileNumber2.png, fileNumber3.png]
”’

Is something like this possible? Am I SOL? if it isn’t, are there any alternative ways I can do it without having to learn an entire new language???

Why don’t kubectl commands work when I run them from JavaScript code on Node.js?

I’m trying to execute this code


    const {exec} = require('child_process');

    exec('/snap/bin/kubectl version', (error, stdout, stderr) => {
        if (error) {
            console.error(`Error executing kubectl: ${error}`);
            console.error(`Exit Code: ${error.code}`);
            console.error(`Error Signal: ${error.signal}`);
            return;
        }
        if (stderr) {
            console.error(`stderr: ${stderr}`);
            return;
        }
        console.log(`stdout: ${stdout}`);
    });

and got these console outputs:

  • Command failed: /snap/bin/kubectl version
  • Code: 1
  • Signal: null

Details:

  • OS: Linux (Elementary OS 6)
  • Node.js version is v18.18.0 and node: /snap/bin/node.yarn /snap/bin/node.yarnpkg /snap/bin/node /snap/bin/node.npx /snap/bin/node.npm – paths
  • kubectl is installed and work correctly
  • the full kubectl path is /snap/bin/kubectl
  • In the terminal, all ‘kubectl ‘ commands work correctly
  • The command ‘kubect version’ had been chosen, for example

I tried to make my node.js script executable (chmode +x <myscript.js>).

How can I implement access restrictions to a Spring controller API based on a user’s roles, and send a message back to the user?

I have implemented a DataTable configuration featuring a delete button within each row. Nevertheless, the functionality of the delete button is restricted to users with specific roles, such as “ADMIN.” Users lacking the “ADMIN” or “EDITOR” role will encounter a prompt notifying them of their unauthorized access when attempting to use the delete button.

This is the button, it’s being rendered in one of my DataTable columns:

<form style="display:inline !important;" action="/admin/delete/" method="post" onsubmit="return confirm('Do you really want to delete employee ${row.id} ?');">
<input type="hidden" name="id" value="${row.id}" />
<button class="form-command btn btn-danger btn-sm" type="submit"><i class="fa fa-trash-o"></i></button>
</form>`;

This is the delete API in the controller class:

@PreAuthorize("hasRole({'ROLE_ADMIN', 'ROLE_EDITOR'})")
    @DeleteMapping("delete")
    @ResponseStatus(HttpStatus.OK)
    void delete(@RequestBody Integer id) {
        deleteEntity(id);
    }

The @PreAuthorize annotation is supposed to check the roles of the authenticated user and if they aren’t authorized deny them. The thing is I want to send a message to the front-end user to tell them that they don’t have permission to delete a row.

$(document).ready(function () {
    $('#tableID').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "api-endpoint",
            "type": "POST",
            'beforeSend': function (xhr) {
                xhr.setRequestHeader(csrfHeader, csrfToken);
            },
            'data': function (d) {
                d.search.value = d.search.value || '';
                d.columns[2]['search']['value'] = d.columns[2]['search']['value'] || '';
                d.columns[3]['search']['value'] = d.columns[3]['search']['value'] || '';
                d.columns[4]['search']['value'] = d.columns[4]['search']['value'] || '';
            },
        },
        "columns": [
            // ... (other columns remain unchanged)
        {
                    "data": null,
                    "render": function (data, type, row) {
                        let dropdownMenu = ``;
                        let deleteForm = `
                        <form style="display:inline !important;" action="/admin/delete/" method="post" onsubmit="return confirm('Do you really want to delete employee ${row.id} ?');">
                            <input type="hidden" name="id" value="${row.id}" />
                            <button class="form-command btn btn-danger btn-sm" type="submit"><i class="fa fa-trash-o"></i></button>
                        </form>`;

                        return dropdownMenu + "<br/>" + deleteForm;
                    },
                    "orderable": false
                }
            
        ],
        initComplete: function () {
            // ... (unchanged)
        }
    });
});

How can I achieve this?

Set data from an array of objects onto a card

I have an array of objects with

  1. image
  2. title
  3. price
  4. vendor

I am trying to set each data on a card. I think I’m not accessing the array correctly.

I have an undefined error, how can I solve it? I appreciate your help

const products = '[ { "user_id": "666", "products": [ { "id": "7109593301197", "name": "Product1", "img": "https://www.kasandbox.org/programming-images/avatars/spunky-sam.png", "handle": "handle1", "price": "111.0", "vendor": "Vendor1" }, { "id": "7076369957069", "name": "Product2", "img": "https://www.kasandbox.org/programming-images/avatars/purple-pi-pink.png", "handle": "handle2", "price": "85.0", "vendor": "Vendor2" }, { "id": "7182779154637", "name": "Product3", "img": "https://www.kasandbox.org/programming-images/avatars/mr-pants.png", "handle": "handle3", "price": "435.0", "vendor": "Vendor3" }] } ]';
const data = JSON.parse(products);
const cardElements = document.getElementsByClassName("related-prod-wrapper");

for (var i = 0; i < data.length; i++) {
  const currentCardElement = cardElements.item(i);
  const cardImage = currentCardElement.getElementsByClassName("image").item(0);
  cardImage.setAttribute("src", data[i].img);
}

const cardElements2 = document.getElementsByClassName("related-prod-detail");

for (var i = 0; i < data.length; i++) {
  const currentCardElement2 = cardElements2.item(i);

  const cardVendor = currentCardElement2.getElementsByClassName("vendor").item(0);
  cardVendor.innerHTML = data[i].vendor;

  const cardTitle = currentCardElement2.getElementsByClassName("title").item(0);
  cardTitle.innerHTML = data[i].name;

  const cardPrice = currentCardElement2.getElementsByClassName("precio").item(0);
  cardPrice.innerHTML = data[i].price;

}
<div class="med-product-card">
  <div class="related-prod-wrapper">
    <img class="image">
  </div>
  <div class="related-prod-detail">
    <h3 class="vendor">Vendor</h3>
    <h3 class="title">Card 1</h3>
    <h3 class="precio">Precio</h3>
  </div>
</div>

<div class="med-product-card">
  <div class="related-prod-wrapper">
    <img class="image">
  </div>
  <div class="related-prod-detail">
    <h3 class="vendor">Vendor</h3>
    <h3 class="title">Card 1</h3>
    <h3 class="precio">Precio</h3>
  </div>
</div>

<div class="med-product-card">
  <div class="related-prod-wrapper">
    <img class="image">
  </div>
  <div class="related-prod-detail">
    <h3 class="vendor">Vendor</h3>
    <h3 class="title">Card 1</h3>
    <h3 class="precio">Precio</h3>
  </div>
</div>

Imports, Types and Typescript Compilation in Vanilla JS Project

I have a very unorthodox setup for my current project. The project consists of a django application with multiple “apps” or folders that try to containerize the logic of different sections of the website. I wanted to introduce Typescript into the project, since I love the benefits of typesafety.

However, since this is running purely on Django (no framework running in parallel to the backend, just scripts included in an HTML script tag), what I opted in to do was to just create Typescript files, transpile them and then use the resulting JS files in the HTML script tags required. Each app or folder has a “static” folder, with two subfolders inside: “ts” and “js”. Beside those two folders, there is a tsconfig.json with the following config

{
    "extends": "../../../tsconfig.json", // Path to global tsconfig.json
    "compilerOptions": {
        "outDir": "js", // Where the transpiled Javascript files go
        "rootDir": "ts", // Where the Typescript files are
    },
}

This helps the compiler know that I want the files in the ts folder to be put in the js folder. Django then simply picks up the resulting JS files and uses them.

As you can see, the config uses a parent configuration with the same name, that contains the following:

{
    "compilerOptions": {
        "target": "es5",
        "module": "ES2015",                     // Include imports/exports in the transpiled Javascript
        "moduleResolution": "node",             // Use the locally installed Node modules 
        "lib": [
            "es2019",
            "dom",
            "DOM.Iterable",
            "es2017"
        ],
        "sourceMap": true,                      // Generates a map file that allows us to see the "non-minified" code when debugging
        "noUnusedParameters": true,             // Warns when a function parameter is not used
        "noImplicitReturns": true,              // Enforce always adding types to function inputs
        "removeComments": true,                 // Remove comments from the transpiled JS file
        "strict": true,                         // Enable all strict type checking options


        // Include the globally installed modules
        // (Check where your global modules are installed with: npm root -g)
        // NOTE: The first type root is used by the node_opus container. The
        // rest you can use them to point to your locally installed global
        // modules.  
        "typeRoots": [
            "/home/node/opus/nodejs/node_modules/@types",
            "./nodejs/node_modules/@types"
        ],

        // Specify "types": [] to disable automatic inclusion of @types packages.
        // https://stackoverflow.com/questions/47303252
        "types": ["jquery"]
    },

    // Exclude the "node_modules" folder from the transpilation process
    "exclude": [ "node_modules" ]
}

Everything good up to here. Scripts compile into JS files and files that are next to each other can be imported really easily with proper linting support:

import { APIError } from "./types/common.js";

However, one of the errors that I have found is that when I try to reference a Typescript file found in a different app, like in the following example

import { OpusProgressBar } from "../../../../static/app_core/js/components/progressBar.js";

I get the following error: Could not find a declaration file for module "X". "X" implicitly has an "any" type. This is a pretty big deal breaker for me, since this removes type annotations from my imports, which was the reason I introduced Typescript in the first place.

I tried looking around at how to fix this, and while trying to do this, discovered a few things:

  • When I go to the transpiled Javascript file, that file actually has proper type annotations.
  • Some posts mentioned the fact that I need to use a .d.ts file to solve the problem. I created a sample progressBar.d.ts and included it in the parent tsconfig.json file like you can see below. This caused all imports in my files to be automatically fixed. With them getting correct linting support. No idea why this would work
{
    "compilerOptions": {
        ...
    },

    // Exclude the "node_modules" folder from the transpilation process
    "exclude": [ "node_modules" ],
    "include": [ "progressBar.d.ts" ]
}
  • When the previously mentioned thing worked, I tried compiling, and it failed. It told me that the include setting in my tsconfig.json did not include the files that I was trying to compile. So I added an entry for my scripts in the include setting like this [ "progressBar.d.ts", "./app_name/**/ts/*"]. This made the compilation work again, but my imports broke again
  • I have jQuery installed in my npm global modules, and I use the $ symbol associated with jQuery in multiple scripts for my Django project. Interestingly, for that specific package I do have linting. However, when I fixed my imports, the linting for it just went away

Im sure all of these “symptoms” might sound familiar to someone out there who might be able to help me out. Maybe someone can help me out so that I can have a setup with both correct linting and proper compilation behavior. I just want to code and not have to worry about this tbh. Thank you!

how to use right to left in regex unicode characters

i would like to detect right-to-left language using a javascript unicode character class escape regular expression, but the line below throws an error

> new RegExp(/[p{Bidi_Class=Right_to_Left}]/u)
Uncaught SyntaxError: Invalid regular expression: /[p{Bidi_Class=Right_to_Left}]/u: Invalid property name in character class

the same error is thrown when using

new RegExp(/[p{Bidi_Class=Right_to_Left}]/, "u")

can you please tell me what am i doing wrong and how can i fix it?

Clicking on an image for information to appear on wix

I am coding in JavaScrit in wix to make something that when I click on an element, it will unhide the other elements. Also, clicking another element will unhide another set of elements on the same position than the elements before. Clicking on another element will also hide the current unhidden ones to make space for the new unhidden ones. Clicking the same element will unhide the current ones as well.

$w.onReady(function () { const element1 = $w('#imag32'); const element2 = $w('#image31');

const contentSet1 = [$w('#box18'), $w('#box19'), $w('#text94'), $w('#image39')];
const contentSet2 = [$w('#box20'), $w('#box21'), $w('#text95'), $w('#image40')];

// Initially hide all content sets
contentSet1.forEach(content => content.hide());
contentSet2.forEach(content => content.hide());

// Function to hide all content sets except the one passed as an argument
function hideAllExcept(exceptContentSet) {
    const allContentSets = [contentSet1, contentSet2];
    allContentSets.forEach(contentSet => {
        if (contentSet !== exceptContentSet) {
            contentSet.forEach(content => content.hide());
        }
    });
}

// Toggle visibility of content when the associated element is clicked
element1.onClick(() => {
    console.log("Content 1 visibility: ", contentSet1[0].visible); // Check visibility
    if (contentSet1[0].visible) {
        contentSet1.forEach(content => content.hide('fade'));
    } else {
        hideAllExcept(contentSet1);
        contentSet1.forEach(content => content.show('fade'));
    }
});

element2.onClick(() => {
    console.log("Content 2 visibility: ", contentSet2[0].visible); // Check visibility
    if (contentSet2[0].visible) {
        contentSet2.forEach(content => content.hide('fade'));
    } else {
        hideAllExcept(contentSet2);
        contentSet2.forEach(content => content.show('fade'));
    }
});

});`

I tried this but the clickable elements are not working and the suppose to be unhidden elements are still there.

Facing interruptions with personal ChatGPT responses: Stops mid-sentence without errors. Any insight

I am presently engaged in developing a Text-to-Speech (TTS) and Speech-to-Text (STT) chatbot project that can be accessed through this link: https://talkgpt.seait.repl.co/

However, I’ve come across a significant issue wherein the chatbot abruptly stops in the middle of a conversation without displaying any errors or warnings. It appears that the main problem is related to how the chat response is being streamed, causing only the initial part of the response to be received. Removing ‘stream:true’ from #src/App.tsx:137 should theoretically resolve this by allowing the fetch function to return the entire response. However, doing so results in the chatbot’s response stopping altogether.

I would highly appreciate any assistance or insights you might offer to help address this unexpected pause in the chatbot’s response during its generation process.

The code for this project is available on Replit at: https://replit.com/@SeaIT/talkgpt

Add Azure MSAL/Active Directory SAML to existing web app NodeJS backend

I have a NodeJS app that uses conventional username/password with a hashed password in the database. I have been asked to implement single sign-on using Microsoft Azure Active Directory/Entra ID (called AD below).

To get started, I implemented an OpenID flow by adding a login page (based on MS sample code using ‘npm i @azure/msal-node’) that pops up a window, does the auth against AD and redirects to my app with a token in a cookie. The user clicks Enter to send the token to the backend which uses it to get the identity from AD.

The actual use case I need is SAML. I cannot make it work. Having burned several days, I am deeply traumatized.

After failing to create a local login page with popup as I did with OpenID, I turned to the facility on the Azure SAML configuration page to “Test single sign-on with [MY] SAML APP”, This presents a button that pops up a sign in page and redirects to my app. There, I capture the “samlResponse” and present it to a function that is supposed to use it to find out who logged in.

I have searched for sample code with very little result. Eventually, I thought to see if Azure had API documentation. There is none but that lead me to a trove of examples, none of which mention SAML. One did, however, mention certificates, ie, “auth-code-with-certs”. No joy. It came with sample certificate and key. The certificate was expired when I upload it to Azure. No matter what I did, I got the same error as always, “secretOrPrivateKey must be an asymmetric key when using RS256”.

I did other things but eventually, I got the idea of using a clientSecret instead of a certificate. This told me that I need a redirectUri. WTAF? (For the OpenID version, I use ‘msal-browser.js’ in the login page. It makes sense for that to ask for a redirect.)

Though I have read a million things on this journey, I now wonder if I understand anything about it.

Here is the code I adapted from the example that I am using. It gets the bad key error. If I replace the clientCertificate with clientSecret, I get the redirect error:

const getUserInfo = (samlResponse, callback) => {
    const auth = {
        clientId: '1c3b4392-c123-4f88-b1ba-b32255b18141',
        authority:
            'https://login.microsoftonline.com/bba67e09-06e0-4d07-9123-acdb7a262a91',
        clientCertificate: {
            thumbprint: '2F4848A44EEEC7294E9B75743CE62A40826D1193', // can be obtained when uploading certificate to Azure AD
            privateKey: `-----BEGIN OPENSSH PRIVATE KEY----- [REMOVED FOR READABILITY] -----END OPENSSH PRIVATE KEY-----`
        }
    };
    const cca = new msal.ConfidentialClientApplication({
        auth
    });
    const tokenRequest = {
        code: ssoToken,
        scopes: ['https://graph.microsoft.com/User.Read']
    };

    cca
        .acquireTokenByCode(samlResponse)
        .then(response => {
            const { username: userName, name } = response;
            callback('', { username: userName, name });
        })
        .catch(error => {
            callback(error);
        });
};

(It came from HERE.)

So, here is what I am asking:

  1. My flow is get samlResponse, use backend code to send it to AD to get user info. Is this essentially correct?

  2. If not, what should the flow be?

  3. Does anyone know where I can see Javascript to accomplish this? The lack of code examples is amazing.

I really need some help so, thank you, please.

Issue displaying travel time in input form result – need assistance

Can someone please help me understand why my code to display the travel time is not appearing in the input form result, even though the distance value is displayed? The issue is that the waktu_tempuh part does not show up. Is there a solution to this problem? I’ve been stuck for 2 weeks because of this issue 🙁

here my code :

Waktu Tempuh

function updatePath() {
var startLatitude = parseFloat(document.getElementById(‘startLatitude’).value);
var startLongitude = parseFloat(document.getElementById(‘startLongitude’).value);
var endLatitude = parseFloat(document.getElementById(‘endLatitude’).value);
var endLongitude = parseFloat(document.getElementById(‘endLongitude’).value);
var shipSpeed = parseFloat(document.getElementById(‘shipSpeed’).value);

        // Validasi kecepatan kapal
        if (isNaN(shipSpeed) || shipSpeed <= 0 || shipSpeed > 50) {
            alert("Mohon masukkan kecepatan kapal yang valid antara 1 dan 50 knot.");
            return;
        }

        var startPoint = [startLatitude, startLongitude];
        var endPoint = [endLatitude, endLongitude];

        if (curve1) {
            map.removeLayer(curve1);
        }

        curve1 = L.pathCurve(startPoint, endPoint).addTo(map);

        var halfwayPoint = L.latLng(
            (startPoint[0] + endPoint[0]) / 2,
            (startPoint[1] + endPoint[1]) / 2
        );

        addWaypointOnCurve(curve1, halfwayPoint);

        var route = getRoute(startPoint, endPoint);
        routeData = route; // Menyimpan data rute ke variabel global
        var distance = 0;
        for (var i = 1; i < route.length; i++) {
            var latlng1 = [route[i - 1].x - 90, route[i - 1].y - 360];
            var latlng2 = [route[i].x - 90, route[i].y - 360];
            distance += calculateDistance(latlng1, latlng2);
        }
        var distanceInKm = distance / 1000;
        document.getElementById('travelDistance').value = distanceInKm.toFixed(2);
        var travelTime = calculateTravelTime(distanceInKm, shipSpeed);
        document.getElementById('travelTime').value = travelTime.toFixed(2);
        updateShipPosition(route, shipMarker, shipSpeed);
    }


I attempted to create a code to display the travel time in an input form result. I expected both the distance and waktu_tempuh values to appear, but only the distance is showing up. Despite trying various approaches, I haven't been able to resolve this issue in the past two weeks. Any suggestions or solutions would be greatly appreciated.

Vuelidate RangeError: Maximum call stack size exceeded

I’m trying to validate my fields using vuelidate, but i’m having some issues. When i load my forms, my app dies. The error says: “RangeError: Maximum call stack size exceeded”

import { useVuelidate } from '@vuelidate/core';
import { required, helpers, minLength } from '@vuelidate/validators';
<b-form-group label="Org Name" description="">
                <b-form-input v-model="$v.orgName.$model"  :class="{ 'input-error': $v.orgName.$dirty && $v.orgName.$error }"/>
            </b-form-group>
            <p v-for="error of $v.orgName.$errors" :key="error.$uid" style="color: darkred">{{ error.$message }}</p>
            <span v-if="$v.orgName.$dirty && !$v.orgName.required"></span>

            <b-form-group label="Org" description="">
                <b-form-input v-model="orgTradeName"/>
            </b-form-group>
            <p v-for="error of $v.orgTradeName.$errors" :key="error.$uid" style="color: darkred">{{ error.$message }}</p>
            <span v-if="$v.orgTradeName.$dirty && !$v.orgTradeName.required"></span>
 setup() {
        return { $v: useVuelidate() }
    },
   validations() {
      return {
          orgName: {
              required: helpers.withMessage("required!", required),
              minLength: helpers.withMessage('2 characters.', minLength(2))
          },
          orgTradeName: { 
              required: helpers.withMessage("required!", required),
              minLength: helpers.withMessage(' 2 characters.', minLength(2))
          },
      }
    },
submitForm() {
            this.$v.$touch();
            if (this.$v.$invalid) {
                this.$toast.add({
                    severity: 'error',
                    summary: 'error-',
                    life: 5000
                });
            } else {
                this.updateOrganization();
            }
        },

Error

I want to be able to use the validations