get 404 for external js file in vue js 3?

i have vue js project and i use adminlte template i set js file like that in my App.vue:

<script>


 export default {
  name: 'App',
  mounted(){
console.log(__filename)
const scriptsToLoad = [
  './template/bower_components/jquery/dist/jquery.min.js',
  './template/bower_components/jquery-ui/jquery-ui.min.js',
  './template/bower_components/bootstrap/dist/js/bootstrap.min.js',
  './template/bower_components/morris.js/morris.min.js',
  './template/bower_components/jquery-sparkline/dist/jquery.sparkline.min.js',
  './template/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js',
  './template/plugins/jvectormap/jquery-jvectormap-world-mill-en.js',
  './template/bower_components/jquery-knob/dist/jquery.knob.min.js',
  './template/bower_components/moment/min/moment.min.js',
  './template/bower_components/bootstrap-daterangepicker/daterangepicker.js',
  './template/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js',
  './template/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js',
  './template/bower_components/jquery-slimscroll/jquery.slimscroll.min.js',
  './template/bower_components/fastclick/lib/fastclick.js',
  './template/dist/js/adminlte.min.js',
  './template/dist/js/pages/dashboard.js',
  './template/dist/js/demo.js'
];

scriptsToLoad.forEach(src => {
  const script = document.createElement('script');
  script.setAttribute("src",src);
  document.head.appendChild(script);
});
}

}


</script>

but i got this error for all files:
main.js:21

   GET http://localhost:8080/template/bower_components/jquery-sparkline/dist/jquery.sparkline.min.js net::ERR_ABORTED 404 (Not Found)

i put adminlte files in src folder

so what is problme?

How to find a DOM object by the text using JS/Chrome extension execution?

Currently trying to access DOM object by the ‘text’, and I can’t find this using standard javascript way – ‘evaluate’ or looping through all th object.

DOM object that I want to access is with textContent <target_text>
I have confirmed that <target_text> is unique across the whole page.

Executing this as part of Chrome extension.

Target element looks like this

<th class="MuiTableCell-root table-header-cell h-8 whitespace-pre-wrap align-middle text-left MuiTableCell-head MuiTableCell-sizeMedium css-1bz4y89" scope="col" style="width: 50%;">Target Text</th>

So there is not unique class or tag to point it by.
It’s parent look like

<tr class="MuiTableRow-root MuiTableRow-head css-16pe4ub"><th class="MuiTableCell-root table-header-cell h-8 whitespace-pre-wrap align-middle text-left MuiTableCell-head MuiTableCell-sizeMedium css-1bz4y89" scope="col" style="width: 50%;">Target Text</th><th class="MuiTableCell-root table-header-cell h-8 whitespace-pre-wrap align-middle text-left MuiTableCell-head MuiTableCell-sizeMedium css-1bz4y89" scope="col" style="width: 50%;">Finding</th><th class="MuiTableCell-root table-header-cell h-8 whitespace-pre-wrap align-middle text-left w-13 MuiTableCell-head MuiTableCell-sizeMedium css-1bz4y89" scope="col"></th></tr>
  const targetElements = document.querySelectorAll('th');
  const targetElement = Array.from(techConcernsElements).find(th => 
    th.textContent.trim() === '<target_text>'
  );

This returns nothing

  const targetElement = document.evaluate(
    "//th[text()='<target_text>']", // This is the Xpath directly.
    document,
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE, // FIRST_ORDERED_NODE_TYPE returns the first matching node
    // Other options include:
    // UNORDERED_NODE_ITERATOR_TYPE - Returns all matching nodes in arbitrary order
    // ORDERED_NODE_ITERATOR_TYPE - Returns all matching nodes in document order
    // UNORDERED_NODE_SNAPSHOT_TYPE - Returns snapshot of matches in arbitrary order
    // ORDERED_NODE_SNAPSHOT_TYPE - Returns snapshot of matches in document order
    // FIRST_ORDERED_NODE_TYPE - Returns first match in document order
    // ANY_UNORDERED_NODE_TYPE - Returns any single matching node
    // NUMBER_TYPE - Returns number value
    // STRING_TYPE - Returns string value
    // BOOLEAN_TYPE - Returns boolean value
    null
  );

Tried out the explicit selector found in the chrome page

#root > div.flex.flex-col.h-screen > main > div > div > div > div:nth-child(2) > div > div.MuiPaper-root.MuiPaper-elevation.MuiPaper-rounded.MuiPaper-elevation1.MuiCard-root.relative.overflow-visible.rounded-sm.w-full.max-w-6xl.xl:max-w-7xl.css-1kxnsga > div.[&_tbody_tr_td]:text-lg.[&_th]:text-base > div:nth-child(2) > table > thead > tr > th:nth-child(1)

via
const targetElement = document.querySelector('#root > div.flex.flex-col.h-screen > main > div > div > div > div:nth-child(2) > div > div.MuiPaper-root.MuiPaper-elevation.MuiPaper-rounded.MuiPaper-elevation1.MuiCard-root.relative.overflow-visible.rounded-sm.w-full.max-w-6xl.xl\:max-w-7xl.css-1kxnsga > div\[\&_tbody_tr_td\]\:text-lg\[\&_th\]\:text-base > div:nth-child(2)');

This also returns nothing

Why can if statement works using an object (like Map) with “.has()” and no working with “.includes”?

That’s my code to explain my idea better (I’m a non english speaker):

The “.includes()” method doesn’t work in this case

const sentence = "hello world hello boy";

let words = sentence.split(" ");

const quantWords = new Map();

for (let word of words) {  
    if (quantWords.includes(word)) {
        quantWords.set(word, + 1);
    } else {
        quantWords.set(word, 1);
    }
}
console.log(quantWords);

Otherwise, using “.has()”, it works

const sentence = "hello world hello boy";

let words = sentence.split(" ");

const quantWords = new Map();

for (let word of words) {  
    if (quantWords.has(word)) {
        quantWords.set(word, + 1);
    } else {
        quantWords.set(word, 1);
    }
}
console.log(quantWords);

Is there a way to get data from an API (eg. colors theme) and use them to update tailwind.config.js file with the new color theme from the API?

I’m currently building a project that’ll allow the user to choose their color scheme, which will be saved to an API (currently using a local dummy API). I’m looking to grab the data from the API and update the tailwind.config.js file with the new colors, but can’t seem to achieve this. I get the following error message:

[vite] Internal server error: [postcss] /Applications/MAMP/htdocs/CG/src/index.css:213:5: ‘colors.primary400’ was found but does not resolve to a string.

Below is my code so far…

http.js

export async function fetchClientData() {
    const response = await fetch("http://localhost:3000/client");
    const resData = await response.json();

    if (!response.ok) {
        throw new Error();
    }

    return resData.client;
}

clientDataStyling.js


import { fetchClientData } from "./http";

let FCDStylingObj;

async function fetchClientAPIStyling() {
    try {
        const FCDStyling = await fetchClientData();
        FCDStylingObj = {
            fetchPrimary400: FCDStyling[0].colors.primary400,
        }
        var getFCDStylingObj = await FCDStylingObj.fetchPrimary400;
        return getFCDStylingObj;

    } catch (error) {
        console.log('Error message | ' + error);
    }
}

let clientStyling = fetchClientAPIStyling();

clientStyling.then(function (result) {
    return result;
})

export const CLIENT_DATA = {
    colors: {
        primary400: clientStyling
    },
}

tailwind.config.js

/** @type {import('tailwindcss').Config} */

import { CLIENT_DATA } from './src/clientDataStyling';

console.log(CLIENT_DATA.colors.primary400);

export default {
    content: [
        "./index.html",
        "./src/**/*.{js,ts,jsx,tsx}",
    ],
    theme: {
        extend: {
            fontFamily: {
                title: "Poppins, sans-serif",
                body: "Poppins, sans-serif"
            },
            colors: {
                primary100: "#b8ace860",
                primary200: "#6e56a1c4",
                primary300: "#644b99",
                // primary400: "#392976",
                primary400: CLIENT_DATA.colors.primary400,
                secondary: "#e372a9",
                third: "#3eb392",
                success: "#3eb392",
                error: "#f94b4b"
            },

            borderWidth: {
                global: "1px"
            },

            borderRadius: {
                global: "5px"
            },

            transitionDuration: {
                global: "300ms"
            }
        },
    },
    plugins: [],
}

Any help would be grateful as I’ve been going around in circles these past couple of days! Or if there’s any other css framework that’ll work for what I’m trying to achieve. Thanks again!

How do I invoke my lang key using Handlebars JS inside a Javascript template literal

I’m trying to invoke my lang files (i.e. en.json, es.json, etc.) within a Javascript template literal however, when I call upon the lang file using Handlebars, it renders the lang call as a string instead of converting it into the text in my lang files. How do I change my code to make it pull from the lang files instead? Currently it is displaying the button with {{ lang product.quick_view }} as plain text.

Here is the HTML:

        <div class="quiz">
            <div id="quiz-container">
                <div id="question-container" class="question"></div>
                <ul id="options-container" class="productGrid"></ul>
            </div>
            <ul id="result-container" class="result">
            </ul>
        </div>
    <script src="{{cdn 'assets/js/autoselect-assist.js'}}"></script>

And here is my Javascript:

function displayResults() {
    questionContainer.textContent = "Your recommended product(s):";
    optionsContainer.innerHTML = "";
    
    if (filteredProducts.length > 0) {
        filteredProducts.forEach(result => {
            const productElement = document.createElement("li");
            productElement.classList.add("product");
            productElement.innerHTML += `
                <article class="card" data-event-type="list" data-name="${result.name} data-product-category="" data-product-brand="${result.brand} data-product-price="${result.price}>
                    <figure class="card-figure">
                        <a href="${result.url}" class="card-figure__link" target="_blank" aria-label="${result.name}, ${result.price}" data-event-type="product-click">
                            <div class="card-img-container">
                                <img src="${result.img}" class="card-image lazyautosizes ls-is-cached lazyloaded" alt="${result.name}" title="${result.name}" data-sizes="auto" srcset="${result.img} data-srcset="${result.img}" sizes="285px">
                            </div>
                        </a>
                        <figcaption class="card-figcaption">
                            <div class="card-figcaption-body">
                                <button type="button" class="button button--small card-figcaption-button quickview" data-event-type="product-click">{{ lang "products.quick_view" }}</button>
                                <label class="button button--small card-figcaption-button">
                                {{ lang "products.compare" }}
                                <input type="checkbox" name="products[]">
                                </label>
                                <a href="${result.url}" data-event-type="product-click" class="button button--small card-figcaption-button">{{ lang "products.choose_options" }}</a>
                            </div>
                        </figcaption>
                    </figure>
                    <div class="card-body">
                        <p class="card-text" data-test-info-type="brandName">${result.brand}</p>
                        <h3 class="card-title">
                            <a href="${result.url}" target="_blank">${result.name}</a>
                        </h3>
                        <div class="card-text" data-test-info-type="price">
                        <div class="price-section price-section--withoutTax">
                            <span class="price-label"></span>
                            <span class="price-now-label" style="display: none;"></span>
                            <span data-product-price-without-tax class="price price--withoutTax">$${result.price}</span>
                        </div>
                    </div>
                </article>`;
            optionsContainer.appendChild(productElement);
        });
    } else {
      optionsContainer.textContent = "No products match your criteria. Please try again!";
    }

    const restartButton = document.createElement("button");
    restartButton.textContent = "Restart Quiz";
    restartButton.addEventListener("click", restartQuiz);
    restartButton.classList.add("restart", "button", "button--primary");
    optionsContainer.appendChild(restartButton);
}

For reference, Handlebars calls lang like this: {{ lang "products.quick_view" }}

Trigger Script in Google Doc via Link

I have a current script in Google Docs that adds a header with collapsible list beneath it (on a pageless setup) underneath a specific section of the document.

I am looking for users to be able to trigger the script from within the document. I have been able to achieve this in Google Spreadsheets using links and Drawings (and using a custom menu, but that’s less ideal in this instance), but have not been able to achieve the same thing within Google Docs.

Ideally, a user would click a link, which would trigger the script that adds the following:
Example of the text script should input

Here’s the script I have so far:

function insertText() {
  var header = "Enter_Item_Title_Here"
  var bulletOneHeader = "Agenda Item Owner(s): ___________"
  var bulletTwoHeader = "Discussant: ___________"
  var bulletThreeHeader = "Discussion Date: ___________"
  var bulletFourHeader = "External follow up: ___________"
  var bulletFiveHeader = "Notes: ___________"
  var bulletSixHeader = "Action Items: ___________"
  var cursor = DocumentApp.getActiveDocument().getActiveTab().asDocumentTab().getBody();
  var pr = cursor.findText("New Items:").getElement().getParent();
  var i = cursor.getChildIndex(pr) + 1;
  cursor.insertParagraph(i, header).setHeading(DocumentApp.ParagraphHeading.HEADING3);
  cursor.insertListItem(i + 1, bulletOneHeader).setGlyphType(DocumentApp.GlyphType.BULLET).setAttributes({ [DocumentApp.Attribute.BOLD]: true });
  cursor.insertListItem(i + 2, bulletTwoHeader).setGlyphType(DocumentApp.GlyphType.BULLET).setAttributes({ [DocumentApp.Attribute.BOLD]: true });
  cursor.insertListItem(i + 3, bulletThreeHeader).setGlyphType(DocumentApp.GlyphType.BULLET).setAttributes({ [DocumentApp.Attribute.BOLD]: true });
  cursor.insertListItem(i + 4, bulletFourHeader).setGlyphType(DocumentApp.GlyphType.BULLET).setAttributes({ [DocumentApp.Attribute.BOLD]: true });
  cursor.insertListItem(i + 5, bulletFiveHeader).setGlyphType(DocumentApp.GlyphType.BULLET).setAttributes({ [DocumentApp.Attribute.BOLD]: true });
  cursor.insertListItem(i + 6, bulletSixHeader).setGlyphType(DocumentApp.GlyphType.BULLET).setAttributes({ [DocumentApp.Attribute.BOLD]: true });
}

Here’s an example google doc that includes the script I have so far.

I’ve been looking at and playing around with this existing question and also this one, but haven’t been able to figure it out.

How to replace or target in a string in javascript?

I have such a string which is gotten from a file:

'{"aaa":"sssbbb"}'

I need to delete everything after the backslash (including the backslash) till the first ", respectively till the end of current value.

I can’t really parse this and can’t really string replace the backslash with anything else.

How to Maintain Independent Scrolling and Clickable Links in Preloaded Iframe/WebView Squares on 4 Pages?

I’m building a web application with an interactive UI where users can drag, resize, rotate, and zoom content inside four draggable squares (#square1, #square2, etc.). Each square contains an iframe with scrollable content, and I’m using Interact.js to handle drag/resize operations and jQuery for event handling.

I’m facing a strange issue when multiple users interact with different squares at the same time:

  1. Simultaneous Scrolling Problem:

If User1 starts scrolling the content in square1 and User2 starts scrolling square2, I want both to be able to scroll simultaneously without interrupting each other.
However, as soon as User2 begins interacting with square2, User1’s scroll in square1 stops. I want both scrolls to continue independently.
Touch Gesture Interference:

  1. The bigger issue is that links inside the squares stop working when users are interacting with touch gestures (e.g., dragging, pinching, rotating). Links work fine when no touch gestures are active, but once the user starts interacting with a square, the hyperlinks become unresponsive.
    Ideally, I want users to continue scrolling content while still being able to click on the hyperlinks inside each square.

I’ve set up separate scroll event listeners for each square, with each scroll position stored in localStorage to persist across sessions. I’m also using CSS touch-action settings (e.g., touch-action: none) for gesture-based interactions, and I’ve ensured each square is draggable using Interact.js.

Despite these efforts, the scroll behavior and hyperlink functionality are still problematic when touch gestures are active. Specifically, the link inside the square becomes unclickable as long as gestures (dragging, zooming, or rotation) are taking place.
Independent Scrolling: Users should be able to scroll content in any square without interrupting other squares, even if they’re interacting with different squares at the same time.
Clickable Links: Links inside each square should remain clickable during touch interactions (drag, pinch, rotate, etc.), and scrolling should not interfere with hyperlink functionality.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Multi-touch Squares</title>
    <script src="js/jquery.min.js"></script>
    <script src="js/interact.min.js"></script>
    <link rel="stylesheet" href="css/style.css" />
  </head>
  <body>
    
    <!-- Buttons to show hidden squares -->
    <div class="show-buttons">
      <div class="show-btn type1" id="circle1"></div>
      <div class="show-btn type2" id="circle2"></div>
      <div class="show-btn type3" id="circle3"></div>
      <div class="show-btn type4" id="circle4"></div>
    </div>

    <!-- Boundary container for draggable squares -->
    <div id="boundary">
      <!-- Square 1 -->
      <div id="square1" class="square hidden">
        <div class="square-header">
          Name of Item 1
          <div class="close-btn">&times;</div>
        </div>
        <div class="square-content">
          <iframe src="a.html" frameborder="0" style="pointer-events: auto;"></iframe>
        </div>
      </div>
      <!-- Square 2 -->
      <div id="square2" class="square hidden">
        <div class="square-header">
          Name of Item 2
          <div class="close-btn">&times;</div>
        </div>
        <div class="square-content">
          <iframe src="b.html" frameborder="0" style="pointer-events: auto;"></iframe>
        </div>
      </div>
      <!-- Square 3 -->
      <div id="square3" class="square hidden">
        <div class="square-header">
          Name of Item 3
          <div class="close-btn">&times;</div>
        </div>
        <div class="square-content">
          <iframe src="c.html" frameborder="0" style="pointer-events: auto;"></iframe>
        </div>
      </div>
      <!-- Square 4 -->
      <div id="square4" class="square hidden">
        <div class="square-header">
          Name of Item 4
          <div class="close-btn">&times;</div>
        </div>
        <div class="square-content">
          <iframe src="d.html" frameborder="0" style="pointer-events: auto;"></iframe>
        </div>
      </div>
    </div>


    
    <script src="js/script.js"></script>
  </body>
</html>
/* Style for draggable squares */
.square {
    width: 480px;
    height: 1080px;
    position: absolute;
    user-select: none;
    transform-origin: center;
    background-color: white;
    overflow: hidden;
    z-index: 500;
}

/* Content inside each square (scrollable if necessary) */
.square-content {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: auto;
    -webkit-overflow-scrolling: touch;
}

/* Make iframes fit square dimensions and remove borders */
.square iframe {
    width: 100%;
    height: 100%;
    border: none;
}

/* Individual styling for each square with unique colors and positions */
#square1 {
    border: 2px solid red;
    left: 50px;
    top: 50px;
    border-top: 30px solid #FF7F7F;
}
#square2 {
    border: 2px solid red;
    left: 300px;
    top: 50px;
    border-top: 30px solid #ADD8E6;
}
#square3 {
    border: 2px solid red;
    left: 50px;
    top: 300px;
    border-top: 30px solid #90EE90;
}
#square4 {
    border: 2px solid blue;
    left: 50px;
    top: 50px;
    border-top: 30px solid #ADD8E6;
}

/* Close button styling */
.close-btn {
    position: absolute;
    top: 5px;
    right: 5px;
    background: white;
    border: 1px solid #333;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    line-height: 18px;
    text-align: center;
    cursor: pointer;
    font-family: Arial, sans-serif;
    font-size: 12px;
    z-index: 500;
    touch-action: none;
}

/* Styling for the show buttons container */
.show-buttons {
    position: absolute;
    top: 0%;             /* Position from the top */
    left: 50%;             /* Center horizontally */
    transform: translateX(-50%); /* Adjust to truly center */
    z-index: 1;
    display: flex;         /* Use flexbox for alignment */
}

/* Styling for each show button */
.show-btn {
    width: 50px;           /* Set a fixed width */
    height: 50px;          /* Set a fixed height */
    margin: 5px;           /* Space between circles */
    border-radius: 50%;    /* Make it circular */
    cursor: pointer;        /* Pointer cursor on hover */
    touch-action: none;     /* Disable touch actions */
}

/* Specific styles for each show button */
#circle1 { 
    width: 480px;          /* Specific width */
    height: 1080px;        /* Specific height */
    border-radius: 0;      /* Ensure square shape */
    background-color: red; 
}
#circle2 { 
    width: 480px;          /* Specific width */
    height: 1080px;        /* Specific height */
    border-radius: 0;      /* Ensure square shape */
    background-color: blue; 
}
#circle3 {
    width: 480px;          /* Specific width */
    height: 1080px;        /* Specific height */
    border-radius: 0;      /* Ensure square shape */
    background-color: green; 
}
#circle4 { 
    width: 480px;          /* Specific width */
    height: 1080px;        /* Specific height */
    border-radius: 0;      /* Ensure square shape */
    background-color: yellow; 
}

/* Hide buttons by default */
.hidden {
    display: none;
}

/* Styles for squares in scroll mode */
.square.scroll-mode {
    touch-action: pan-y pinch-zoom;
}

/* Styles for squares not in scroll mode */
.square:not(.scroll-mode) {
    touch-action: none;
}

/* Ensure iframe is interactive */
.square iframe {
    pointer-events: auto;
}

/* Disable interactions when not scrolling */
.square:not(.scroll-mode) iframe {
    pointer-events: none;
}

/* Allow interaction when in scroll mode */
.square.scroll-mode iframe {
    pointer-events: auto;
}
$(document).ready(function () {
    // Object to store transformation states (position, scale, rotation) for each square
    const transformStates = {};

    // Boundary element where squares are confined
    const boundary = document.getElementById('boundary');

    // Variables for touch-based scrolling in square content
    let touchStartY = 0;
    let scrolling = false;

    // Variables for tracking click vs drag
    let isDragging = false;
    let dragStartTime = 0;
    const DRAG_THRESHOLD = 10; // Pixel movement threshold
    const DRAG_TIME_THRESHOLD = 200; // Milliseconds

    // Track the highest z-index dynamically
    let highestZIndex = 1000;

    // Prevent default behavior for touch events on buttons to avoid accidental gestures
    $('.show-btn, .close-btn').on('touchstart touchmove touchend', function (e) {
        e.preventDefault(); // Prevent default touch behavior
    });

    // Disable dragging for the show-buttons (circles)
    interact('.show-btn').unset();

    // Explicitly ensure show-buttons cannot be moved
    $('.show-btn').on('mousedown touchstart', function (e) {
        e.stopPropagation(); // Stop event propagation to prevent dragging
    });

    // Function to set up interactions for draggable and gesturable elements
    function setupInteractions(element) {
        interact(element)
            .draggable({
                inertia: true, // Enable inertia for smooth dragging
                modifiers: [
                    interact.modifiers.restrict({
                        restriction: boundary, // Restrict dragging within boundary
                        elementRect: { top: 0, left: 0, bottom: 1, right: 1 },
                    }),
                ],
                listeners: {
                    start(event) {
                        bringToFrontIfNeeded(event.target); // Bring square to the front if needed
                    },
                    move: dragMoveListener, // Handle drag movements
                    end(event) {
                        // Retain z-index on release
                        const state = transformStates[event.target.id];
                        state.scale = state.currentScale;
                    },
                },
            })
            .gesturable({
                listeners: {
                    start(event) {
                        // Initialize the starting angle and scale for gestures
                        const state = transformStates[event.target.id];
                        state.startAngle = state.angle - event.angle;
                        state.startScale = state.currentScale;
                    },
                    move(event) {
                        // Update the scale and angle based on gesture movements
                        const state = transformStates[event.target.id];
                        const newScale = state.startScale * event.scale;
                        state.currentScale = Math.max(0.5, Math.min(1.5, newScale));

                        const interpolationFactor = 0.1;
                        state.scale = state.scale + (state.currentScale - state.scale) * interpolationFactor;
                        state.angle = state.startAngle + event.angle;

                        updateElementTransform(event.target); // Apply transformations
                    },
                    end(event) {
                        // Finalize the scale after gesture ends
                        const state = transformStates[event.target.id];
                        state.scale = state.currentScale;
                    },
                },
            });

        // Add touch/click listener to bring tapped squares to the front
        $(element).on('mousedown touchstart', function (e) {
            if (!isDragging) {
                bringToFrontIfNeeded(element); // Bring to front if not dragging
            }
        });

        const $content = $(element).find('.square-content');

        // Handle touch-based scrolling within square content
        $content.on('touchmove', function (e) {
            const touchY = e.originalEvent.touches[0].clientY;
            const deltaY = touchStartY - touchY;
            if (!scrolling && Math.abs(deltaY) > 10) {
                scrolling = true;
                $(element).addClass('scroll-mode'); // Enable scroll mode
                interact(element).unset(); // Disable interactions during scroll
            }

            if (scrolling) {
                e.stopPropagation(); // Stop event propagation
                this.scrollTop += deltaY; // Scroll content
                touchStartY = touchY; // Update touch start position
            }
        });

        // Reset scrolling state on touch end
        $content.on('touchend', function () {
            scrolling = false;
            $(element).removeClass('scroll-mode'); // Disable scroll mode
            setTimeout(() => setupInteractions(element), 100); // Re-enable interactions
        });
    }

    // Function to set up handlers for each circle button
    function setupCircleHandlers(circleId, squareIds) {
        $(`#${circleId}`).on("mousedown touchstart", function (e) {
            isDragging = false;
            dragStartTime = Date.now(); // Record start time

            const startX = e.type === "mousedown" ? e.pageX : e.originalEvent.touches[0].pageX;
            const startY = e.type === "mousedown" ? e.pageY : e.originalEvent.touches[0].pageY;

            $(document).on("mousemove touchmove", function (moveEvent) {
                const currentX = moveEvent.type === "mousemove" ? moveEvent.pageX : moveEvent.originalEvent.touches[0].pageX;
                const currentY = moveEvent.type === "mousemove" ? moveEvent.pageY : moveEvent.originalEvent.touches[0].pageY;

                if (Math.abs(currentX - startX) > DRAG_THRESHOLD || Math.abs(currentY - startY) > DRAG_THRESHOLD) {
                    isDragging = true; // Mark as dragging if movement exceeds threshold
                }
            });

            $(document).on("mouseup touchend", function () {
                $(document).off("mousemove touchmove");
                $(document).off("mouseup touchend");

                if (!isDragging && Date.now() - dragStartTime < DRAG_TIME_THRESHOLD) {
                    positionSquare(circleId, squareIds[0]); // Position square if not dragging
                }
            });
        });
    }

    // Function to position a square based on the corresponding circle button
    function positionSquare(circleId, squareId) {
        const circlePosition = $(`#${circleId}`).offset();
        const top = circlePosition.top;
        const left = circlePosition.left;

        const $square = $(`#${squareId}`);
        $square.css({
            top: top + 'px',
            left: left + 'px',
            transform: 'translate(0px, 0px) scale(1) rotate(0deg)'
        }).removeClass('hidden').show(); // Show and position square

        // Reset transform state when repositioned
        transformStates[squareId] = {
            x: 0,
            y: 0,
            scale: 1,
            angle: 0,
            currentScale: 1,
        };

        // Reinitialize interactions to ensure proper dragging
        setupInteractions($square[0]);

        // Reset iframe content to default
        const iframe = $square.find('iframe');
        if (iframe.length > 0) {
            const defaultSrc = iframe.attr('data-default-src');
            if (defaultSrc) {
                iframe.attr('src', defaultSrc);
            }
        }

        // Bring the square to the front
        bringToFrontIfNeeded($square[0]);
    }

    // Function to bring an element to the front by updating its z-index
    function bringToFrontIfNeeded(element) {
        const currentZIndex = parseInt($(element).css('z-index'), 10);
        if (currentZIndex < highestZIndex) {
            highestZIndex += 1; // Increment the highest z-index
            $(element).css('z-index', highestZIndex); // Assign the new z-index
        }
    }

    // Listener for drag movements
    function dragMoveListener(event) {
        const target = event.target;
        const state = transformStates[target.id];

        state.x += event.dx; // Update x position
        state.y += event.dy; // Update y position

        updateElementTransform(target); // Apply transformations
    }

    // Function to update the transform property of an element
    function updateElementTransform(element) {
        const state = transformStates[element.id];
        element.style.transform = `translate(${state.x}px, ${state.y}px) scale(${state.scale}) rotate(${state.angle}deg)`; // Apply CSS transform
    }

    // Set up handlers for each circle button
    setupCircleHandlers("circle1", ["square1"]);
    setupCircleHandlers("circle2", ["square2"]);
    setupCircleHandlers("circle3", ["square3"]);
    setupCircleHandlers("circle4", ["square4"]);

    // Initialize interactions for each square
    $(".square").each(function () {
        const element = this;
        const $square = $(element);

        // Initialize transformation state for this square
        transformStates[element.id] = {
            x: 0,
            y: 0,
            scale: 1,
            angle: 0,
            currentScale: 1,
        };

        // Store default iframe source
        const iframe = $square.find('iframe');
        if (iframe.length > 0) {
            iframe.attr('data-default-src', iframe.attr('src'));
        }

        setupInteractions(element); // Set up interactions for the square
    });

    // Close button handler to hide the square
    $(".close-btn").on("click touchend", function (e) {
        e.stopPropagation();
        e.preventDefault();
        const square = $(this).closest(".square");
        const squareId = square[0].id;
        
        // Force reset any ongoing interaction
        interact(square[0]).unset();
        
        // Reset transform state
        transformStates[squareId] = {
            x: 0,
            y: 0,
            scale: 1,
            angle: 0,
            currentScale: 1,
        };
        
        // Reset the square's transform
        square.css('transform', 'translate(0px, 0px) scale(1) rotate(0deg)');
        
        // Hide the square
        square.addClass("hidden").hide();
        
        // Simulate touchend/mouseup to reset any ongoing drag
        $(document).trigger('touchend');
        $(document).trigger('mouseup');
        
        // Re-initialize interactions after a brief delay
        setTimeout(() => {
            setupInteractions(square[0]);
        }, 100);
    });
});

How to make a div the same width as the element above it WITHOUT using relative positioning?

I have a form where I am trying to set up a dropdown menu below an input field.

My issue is that I can’t get the dropdown menu to be the same width as the input field above it.

If I set the dropdown menu to use relative positioning and I set it to 75% (the same width as the input field) then it works. But the issue then becomes that the dropdown menu pushes down the elements below it when it expands and that is not what I want. I want it to overlay the elements below it when it expands.

So when I set the dropdown div to use relative positioning the width is ok but then it pushes down the elements which is what I dont want. But then when I set it to use fixed positioning it overlays the elements below it ( which is what I want ) but then I cannot get it to have the same width as the input above it.

How do I make this dropdown div BOTH overlay the elements below it when it extends and ALSO be the same exact width as the input field above it?

Ty for your time and God Bless.

here is a reference to the dropdown div and the input field above it

const input = document.getElementById("bizcategory");
const listContainer = document.getElementById("myList");


const words = ['option5', 'option6', 'option7', 'option8',
  'option9', 'option10', 'option11'
];

for (let i = 0; i < words.length; i++) {
  const newItem = document.createElement("li");
  newItem.textContent = words[i];
  newItem.style.listStyle = "none";
  listContainer.appendChild(newItem);

}



const listItems = listContainer.querySelectorAll("li");

input.addEventListener("focus", () => {
  listContainer.style.display = "block";
})

input.addEventListener("blur", () => {
  setTimeout(() => {
    listContainer.style.display = "none";
  }, 200);
});

listItems.forEach(i => i.addEventListener("click", function() {
  input.value = i.textContent;
  listContainer.style.display = "none";
}));
.signininput {
  height: 40px;
  width: 75%;
  box-sizing: border-box;
}


.list-container {
  display: none;
  border: 1px solid #ccc;
  background-color: white;
  width: 75%;
}

.list-container ul {
  list-style: none;
  padding: 0;
  margin: 0;
  width: 75%;
}

.list-container li {
  padding: 5px;
}

.list-container li:hover {
  background-color: #f0f0f0;
  cursor: pointer;
}
<input class="signininput"  type="text" id="bizcategory" name="bizcategory" placeholder="" maxlength="255" onblur="this.value=removeSpaces(this.value);"></input>
<div class="list-container" id="myList">
  <ul style="list-style: none;">
    <li>Option 1</li>
    <li>Option 2</li>
    <li>Option 3</li>
    <li>Option 4</li>
  </ul>
</div>

In Hyperledger fabric when i query qscc ‘GetBlockByTxID’ i get an error saying” error no such transaction ID in index”

I am trying to get the block number and the block hash on Hyperledger fabric network from my channel, but i was able to get the details using cli with the same transaction ID, when i try with the latest fabric-gateway i get the following error

cause: Error: 2 UNKNOWN: evaluate call to endorser returned error: chaincode response 500, Failed to get block for txID "95841fc8ba7c49bf333430e0fd9ed052a97eb9910610bfd22faa05802c2d2cc5"
  , error no such transaction ID ["95841fc8ba7c49bf333430e0fd9ed052a97eb9910610bfd22faa05802c2d2cc5"
  ] in index

The exact version of gateway are

"@hyperledger/fabric-gateway": "^1.7.1",
"@hyperledger/fabric-protos": "^0.2.2",

The below code works for cli

peer chaincode query -C mychannel -n qscc -c '{"Args":["GetBlockByTxID","mychannel","95841fc8ba7c49bf333430e0fd9ed052a97eb9910610bfd22faa05802c2d2cc5"]}'

Iam using the fabric sample network and modifying the asset transfer basic gateway code.

app.get("/getBlockByTxId/:txId", async (req, res) => {
  try {
    const { txId } = req.params;
    
    const network = gateway.getNetwork(channelName);
    const contract = network.getContract("qscc");
    // Use `GetBlockByTxID` to fetch the block containing the transaction
    console.log("NETWORKKK", network.getName());
    console.log(
      "Methods:",
      Object.getOwnPropertyNames(Object.getPrototypeOf(network))
    );

    const result = await contract.evaluateTransaction(
      "GetBlockByTxID",
      network.getName(),
      txId
    );

    // Parse the result as a block
    const block = Block.decode(result); // Decoding block using Hyperledger protobuf
    res.send(block);
  } catch (error) {
    console.error("Error in getBlockByTxId:", error);
    res.status(500).send("Failed to fetch block by transaction ID");
  }
});

how to require a function from another file inside of the code gen for ajv standalone code?

ajv.addKeyword("isValidString", {
  type: "string",
  code(cxt) {
    const { data, schema, gen } = cxt;

    gen.func(
      "isValid",
      ["data"],
      `
      const external_func = require("./customValidation.js");
      return external_func(data);
    `
    );

    cxt.fail(`!isValid(data)`);
  },
});

So the above sums up the intent.

The key is this line:

const external_func = require("./customValidation.js");

But the code above doesn’t work.

This is the code it generated:

function validate10(
  data,
  { instancePath = "", parentData, parentDataProperty, rootData = data } = {}
) {
  let vErrors = null;
  let errors = 0;
  if (errors === 0) {
    if (data && typeof data == "object" && !Array.isArray(data)) {
      let missing0;
      if (data.username === undefined && (missing0 = "username")) {
        validate10.errors = [
          {
            instancePath,
            schemaPath: "#/required",
            keyword: "required",
            params: { missingProperty: missing0 },
            message: "must have required property '" + missing0 + "'",
          },
        ];
        return false;
      } else {
        if (data.username !== undefined) {
          const _errs1 = errors;
          if (errors === _errs1) {
            if (typeof data.username === "string") {
              async function isValid(data) {
                if (!isValid(data)) {
                  validate10.errors = [
                    {
                      instancePath: instancePath + "/username",
                      schemaPath: "#/properties/username/isValidString",
                      keyword: "isValidString",
                      params: {},
                      message: 'must pass "isValidString" keyword validation',
                    },
                  ];
                  return false;
                }
              }
            } else {
              validate10.errors = [
                {
                  instancePath: instancePath + "/username",
                  schemaPath: "#/properties/username/type",
                  keyword: "type",
                  params: { type: "string" },
                  message: "must be string",
                },
              ];
              return false;
            }
          }
        }
      }
    } else {
      validate10.errors = [
        {
          instancePath,
          schemaPath: "#/type",
          keyword: "type",
          params: { type: "object" },
          message: "must be object",
        },
      ];
      return false;
    }
  }
  validate10.errors = vErrors;
  return errors === 0;
}

In particular, this makes no sense:

              async function isValid(data) {
                if (!isValid(data)) {
                  validate10.errors = [
                    {
                      instancePath: instancePath + "/username",
                      schemaPath: "#/properties/username/isValidString",
                      keyword: "isValidString",
                      params: {},
                      message: 'must pass "isValidString" keyword validation',
                    },
                  ];
                  return false;
                }
              }

change value of element attributes to that of another attribute

I want the value of attribute ‘data-bs-content’ in all elements to be set to the value found in the ‘data-my-data’ attribute when the document is loaded.

I’ve tried about a dozen different strategies that I could think of, but none seem to be working.

The reason I don’t just put the value in ‘data-bs-content’ is because there will be processing that happens on the data in ‘data-my-data’ before setting the value.

<!doctype html>
<html>

<head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script>

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

          var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
          var popoverList = popoverTriggerList.map(function(popoverTriggerEl) {
            var popover = new bootstrap.Popover(popoverTriggerEl, {
              container: 'body',
              trigger: 'click'
            });
            return popover;
          });

          var $element = $('[data-bs-content]');
          $element.attr( "data-bs-content" , function(index, currentValue) {
            return $(this).getAttribute('data-my-data');
          });

        });
    </script>

</head>

<body>
<br/>
<a href="#"
   data-bs-toggle="popover"
   data-bs-content="default data"
   data-my-data="my data 1"
>
    CLICK ME 1
</a>
<br/>
<br/>
<a href="#"
   data-bs-toggle="popover"
   data-bs-content="default data"
   data-my-data="my data 2"
>
    CLICK ME 2
</a>

</body>
</html>

The dataset component does not configure the legend

I’m configuring two charts and the legend only appears when I use series.data, but it doesn’t appear when I use the dataset component (series.datasetIndex and series.encode). Nothing I tried worked. Here’s the code:

   document.addEventListener("DOMContentLoaded", () => {

        // sytem
        const chartSystem = () => {
            return {
                "source": {
                    "first": [
                        ["name", "value"],
                        ["Pressure", 40],
                        ["Temperature", 64],
                        ["Atmosphere", 89]
                    ],
                    "second": [
                        ["name", "value"],
                        ["Label 1", 15],
                        ["Label 2", 68]
                    ]
                }
            }
        }

        // send
        const pullDataset = [];
        const pullData = [];

        const chartSend = () => {
            const { first, second } = chartSystem().source;

            pullDataset.push({
                source: first
                // sourceHeader: true
            });

            pullData.push(
                {
                    data: second.slice(1).map(([name, value]) => ({
                        name,
                        value
                    }))
                }
            );
        };

        chartSend();

        // frames
        const chartUse = echarts.init(document.getElementsByClassName("chart")[0]);

        function chartFrameSwitch0 () {

            const tooltip0 = {
                show: true
            };
            
            const useDataLegend = pullDataset[0].source.slice(1).map(item => item[0]);
            console.log(useDataLegend);

            // legend
            const legend0 = [
                {
                    show: true,
                    data: useDataLegend,
                    borderWidth: 2,
                    borderColor: 'red'
                },
                {
                    show: true,
                    data: pullData[0].data.map(item => item.name),
                    borderWidth: 2,
                    borderColor: 'blue',
                    left: 'center',
                    top: '5%'
                }
            ];

            const grid0 = [
                {
                    top: '30%',
                    left: '5%',
                    width: '38%',
                    height:'30%'
                }
            ];

            const xAxis0 = [
                {
                    gridIndex: 0,
                    type: 'category'
                }
            ];

            const yAxis0 = [
                {
                    gridIndex: 0,
                    type: 'value'
                }
            ];

            const series0 = [
                {
                    type: 'bar',
                    color: ['#49a6de', '#ff7500', '#ff00ff'],
                    colorBy: 'data',
                    datasetIndex: 0,
                    encode: {
                        x: 0,
                        y: 1
                    },
                    xAxisIndex: 0,
                    yAxisIndex: 0
                },
                {
                    type: 'pie',
                    legendIndex: 0,
                    center: ['70%', '50%'],
                    data: pullData[0].data
                }
            ];

            const option = {
                dataset: [pullDataset[0]],
                legend: legend0, // Keep both legends in the array
                tooltip: tooltip0,
                grid: grid0,
                xAxis: xAxis0,
                yAxis: yAxis0,
                series: series0
            };

            chartUse.setOption(option);
        }

        chartFrameSwitch0();

    })
<head>
    <script src='https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js'></script>
</head>
    
<div class='chart' style='width: 100%; height: 100vh;'></div>

See the console.log of useDataLegend:

[
  "Pressure",
  "Temperature",
  "Atmosphere"
]

This is a manual way I tried to set legend.data: [...]. I tried using series.encode, but it doesn’t seem to support setting the legend.

D3. How to scale the text so that it all fits into the drawing area

I use D3 to draw everything on the screen, the problem is that i want all the elements to fit in the block, while leaving as little free space as possible, how to do this, size can take a value from 1 to infinity. At the same time, it is necessary to preserve their ratio between themselves, how to do this is clear, but the question is how to calculate the multiplier that will allow them all to fit into the given block sizes.

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.16.0/d3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-cloud/build/d3.layout.cloud.min.js"></script>
const width = 800;
const height = 600;

const svg = d3
    .select("#tagCloud")
    .append("svg")
    .attr("width", width)
    .attr("height", height);

const layout = d3.layout.cloud()
    .size([width, height])
    .words(tags.map(tag => ({ text: tag.text, size: tag.size, url: tag.url })))
    .padding(5)
    .rotate(() => ~~(Math.random() * 2) * 90)
    .font("Impact")
    .fontSize(x => x.size)
    .on("end", draw);

layout.start();

function draw(words) {
    svg.append("g")
        .attr("transform", `translate(${width / 2}, ${height / 2})`)
        .selectAll("text")
        .data(words)
        .enter()
        .append("text")
        .style("font-size", x => `${x.size}px`)
        .style("font-family", "Impact")
        .style("fill", () => d3.schemeCategory10[Math.floor(Math.random() * 10)])
        .attr("text-anchor", "middle")
        .attr("transform", x => `translate(${x.x}, ${x.y}) rotate(${x.rotate})`)
        .text(x => x.text)
        .on("click", function (item, index) {
            if (item.url) {
                window.location.href = item.url;
            }
        });
}

AuthMiddleware Deprecated: How to Fix Issues with clerkMiddleware?

With the deprecation of authMiddleware, I’m looking for guidance on how to update my code. My previous implementation was structured like this:The code
What would be the recommended approach to achieve the same functionality with the updated tools or methods provided by Clerk? Any examples or best practices would be greatly appreciated!

I tried going through the documentation. But being a beginner I couldn’t get much out of it. Then I tried some alternatives using the help of chatGPT. Those too were unsuccessful.

The code is here:

`import { authMiddleware } from '@clerk/nextjs'

export default authMiddleware({
publicRoutes: "/site","/apit/"
})
export const config = {
matcher: ['/((?!. +\. [\w] +$ |_next).*)', '/',
'/(api|trpc) (.*)'],
}`