Finding the most optimal path to transform old html to new html

Given 2 arrays which represent list of HTML elements in old HTML and new HTML respectively, I need to find the diff between the 2 arrays.

What I am doing currently:

  1. Create a 2D min cost matrix using dynamic programming using Levenshtein distance
  2. Traverse the matrix from bottom right to top left and find the path

But this does not always results in a optimal path (mostly because I am taking locally optimal decisions that prove to be sub optimal globally). So, I want to know what is the way to approach this?

I tried dijkstra’s algorithm but then the path it produces is the shortest path (sum of all the costs) but then it may or may not be true.

Here is how my code looks like:

creation of matrix

row       = old.length+1;
column    = current.length+1;
diff      = []
function createMatrix() {
  matrix = new Array(row);
  for (var i = 0; i < row; i++) {
    matrix[i] = new Array(column);
  }
  //fill the 0th row and column
  for (var i = 0; i < row; i++) {
    matrix[i][0] = i;
  }
  for (var j = 0; j < column; j += 1) {
    matrix[0][j] = j;
  }
  //calculate min operations
  for (var i = 1; i < row; i++) {
    for (var j = 1; j < column; j++) {
      var a = old[i - offset];
      var b = current[j - offset];
      var subDistance = (a.hashVal == b.hashVal) ? 0 : 10e6;
      var costReplace = matrix[i - 1][j - 1] + subDistance * a.elementCount + subDistance * b.elementCount;
      var costRemoved = matrix[i - 1][j] + a.elementCount;
      var costInserted = matrix[i][j - 1] + b.elementCount;
      matrix[i][j] = Math.min(costReplace, costRemoved, costInserted);
    }
  }
}

function that finds the path to create the diff:

function traceBack(){
  var i,j;
  
  for(i=row-1,j = column-1;i>0&&j>0;){
      var top = matrix[i-1][j];
      var topLeft = matrix[i-1][j-1];
      var left = matrix[i][j-1];
      if(topLeft== matrix[i][j] && topLeft <= top && topLeft <=left  ){
        current[j-offset].status = 'unchanged';
        diff.unshift(current[j-offset]);
        i--;
        j--;
      }
      else if(top < matrix[i][j]  ){
        (old[i-offset]).status = 'removed';
        diff.unshift(old[i-offset]);
        i--;
      }
      else if (left < matrix[i][j] ){
        (current[j-offset]).status ='inserted';
        diff.unshift(current[j-offset]);
        j--;
      }

  }

  while(i>0){
    (old[i-offset]).status ='removed';
    diff.unshift(old[i-offset]);
    i--;
  }
  while(j>0){
    (current[j-offset]).status = 'inserted';
    diff.unshift(current[j-offset]);
    j--;
  }
}

Few points:

  1. Input HTML strings are transformed to DOM object using htmlparser library
  2. Some basic pre-processing is done on the DOM objects
  3. Objects are flattened into a single list (children chain, flattened out)
  4. createMatrix is called ..

eBay 10-second script evaluation [closed]

I’ve had an issue with the eBay website for a few months. Timed it today and every single page is taking over 15 seconds to load.

Ran Lighthouse on one of the pages and found the culprit.
enter image description here

Not sure what to try next. For now I’ve added https://ir.ebaystatic.com/rs/c/globalheaderweb to my uBlock Origin filter list and that has improved the page load speed to near-instant. However there are some artefacts like the navigation not rendering correctly – although I might even prefer it!

Is there something that might be doing this because of my network configuration or is this something I should take up with eBay directly?

They will tell me to clear cache/use different browser/restart the computer/turn off the WiFi/etcetc but I’ve already done all of that.

I am struggling in building chrome extension that takes the highlighted text and use Gemini model to return rectified text

I am using manifest v3 and I seek help from chatgpt for writing my code for AI chrome extension that takes the highlighted text and rectify any grammatical errors and return corrected text. I have decided to use Gemini free api for the response. Need guidance if anyone has made similar project before or can share the insights please aid!

I watched several youtube tutorials but none of them helped also I tried gpt into providing me the code but the provided code always had some error in it. This is my first time building extension.

Example code:

Manifest.json:

{
  "name": "AI grammer",
  "version": "1.0",
  "manifest_version": 3,
  "description": "AI extension for rectifying grammer",
  "permissions": [
    "contextMenus",
    "tabs",
    "activeTab"
  ],
  "background": {
    "service_worker": "background.js",
    "type": "module"
  }
}

Background.js:

async function newTab(info, tab) {
  const { menuItemId, selectionText } = info;

  if (menuItemId === "correctGrammar") {
    const selectedText = selectionText.trim();

    const apiKey = ""; // Replace with your actual API key
    const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${apiKey}`;

    const prompt = {
      contents: [
        {
          parts: [
            {
              text: selectedText,
            },
          ],
        },
      ],
    };

    try {
      // Send the POST request to the API
      const response = await fetch(apiUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(prompt),
      });

      if (!response.ok) {
        throw new Error(`API request failed with status ${response.status}`);
      }

      const data = await response.json();

      // Assuming corrected grammar is returned in a specific field
      const correctedText =
        data?.contents?.[0]?.parts?.[0]?.text || "No corrected text received.";

      // Display the corrected text in a new tab
    
    } catch (error) {
      console.error("Error while calling the API:", error);

      // Display the error in a new tab
      
    }
  }
}

// Create context menu options
chrome.contextMenus.create({
  title: "Correct Grammar",
  id: "correctGrammar",
  contexts: ["selection"],
});

// Add the event listener for the context menu click
chrome.contextMenus.onClicked.addListener(newTab);

Popup.html:

<!DOCTYPE html> 
<html>
  <head>
    <script src="jquery-1.8.3.min.js"></script>
    <script src="popup.js"></script>
    <style>
      body { width: 300px; }
      textarea { width: 250px; height: 100px;}
    </style>
  </head>
  <body>
    <textarea id="text"> </textarea>
    <button id="paste">Paste Selection</button>
  </body>
</html>

Collision the slider on JS

I tried to make a simple slider using JavaScript but when I ran the code the slide looked stacked at the back which should have been moved to the left so the slider remained in its previous position only changing to appear in the middle.

The slides stack on top of each other, and if I add more than 3 <li> the slides will stack to the left.

Here is my code using Tailwind:

let currentIndex = 0;
const totalSlides = document.querySelectorAll('.slides li').length;

function showSlide(index) {
  const slides = document.querySelector('.slides li');
  const slideList = document.querySelectorAll('.slides li');
  // ensure the index is within a valid range
  if (index < 0) {
    currentIndex = totalSlides - 1; // If earlier, go back to the last slide
  } else if (index >= totalSlides) {
    currentIndex = 0; // If next, go back to the first slide
  } else {
    currentIndex = index;
  }
  // Set the active class

  slideList.forEach((slide, index) => {
    slide.style.zIndex = ''
    if (index === currentIndex) {
      slide.style.transform = `translateX(${-100+1*100}px)`
      slide.style.zIndex = '1'
    } else if (index < currentIndex) {
      var sl = `translateX(${100}px) scale(0.75)`
      slide.style.transform = sl
    } else {
                  var sla = `translateX(${-100}px) scale(0.75)`

      slide.classList.add('active');
      slide.style.transform = sla
    }
  });
}

function nextSlide() {
  currentIndex = (currentIndex + 1) % totalSlides; // Return to first slide
  showSlide(currentIndex);
}

function prevSlide() {
  showSlide(currentIndex - 1);
}
// Interval untuk slide otomatis
setInterval(nextSlide, 4000);
.slides li{
  display: flex;
  transition: transform 3s linear;
}
.slide li img {
  width: 100%;
  display: block;
  transition: all 500ms ease;
  animation-timing-function: linear;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="https://unpkg.com/@tailwindcss/browser@4"></script>
</head>
<body>
<section class="container">
  <div class="relative w-50 p-15 pl-10 m-10">
   <div class="w-5 bottom-190 slides md:bottom-210">
    <ul id="slideList">
     <li class="absolute thdg active0" style="transform: translateX(100px) scale(0.75);" id="first-clone"><img src="https://fakeimg.pl/800x600/?text=Image+1"></li>
     <li class="absolute thdg active" style="transform: translateX(0px); z-index: 1;"><img src="https://fakeimg.pl/800x600/?text=Image+2"></li>
     <li id="last-clone" class="absolute thdg active" style="transform: translateX(-100px) scale(0.75);"><img src="https://fakeimg.pl/800x600/?text=Image+3"></li>
    </ul>
  </div>
</div>
</section>
</body>
</html>

How to the slides are not collision and can also be moved using the cursor?

Showdown.js removes font-awesome icons after using method makemarkdown()

I’ve wrote a simple markdown editor and by file inserting generate markdown as following:

[@fa-file-pdf filename.pdf(application/pdf)](blob:http://localhost.loc/8d3bde70-0ba0-4ee0-a9f3-232b624c1114)

For conversion to HTML I use the following code:

    const converter = new showdown.Converter({
        extensions: ['icon']
    });
    converter.setOption('literalMidWordUnderscores', true);
    return converter.makeHtml(md_content);

It works properly and in HTML appears a font-awesome icon.

<a href="blob:http://localhost.loc/8d3bde70-0ba0-4ee0-a9f3-232b624c1114"><i class="fa fa-file-pdf"></i> filename.pdf(application/pdf)</a>

But when I try to convert back from HTML to markdown using following code:

        const converter = new showdown.Converter({
            extensions: ['icon']
        });
        return converter.makeMarkdown(html_content);

font-awesome icon(@fa-file-pdf) disappears and I get the following:

[filename.pdf(application/pdf)](blob:http://localhost.loc/8d3bde70-0ba0-4ee0-a9f3-232b624c1114)

Is it possible to save icon by converting from html to markdown with help of makemarkdown method?

The user is not the owner of the lock.The template is locked by another user or in another application

How can i edit the docusign template after i generated createViewEdit url and now i want to edit the file it has. i am working with nodejs.

    templatesApi.createTemplate(docusignSet.docusignAccountId, { envelopeTemplate: templateDefinition }, function (error, templateResponse) {
                // console.log("error=====", error, "templateResponse======", templateResponse);
                if (error) {
                    callback(true, error);
                } else {
                    let templateId = templateResponse.templateId;
    
                    let viewRequest = {
                        returnUrl: templateData.returnUrl,
                        // showOnlyStandardFields: true,
                    };
    
                    let output = {};
                    output.templateId = templateId;
    
                    // Generate the template edit view URL
                    templatesApi.createEditView(docusignSet.docusignAccountId, templateId, { returnUrlRequest: viewRequest }, function (error, response) {
                        console.log("error====", error, "response======", response);
                        if (error) {
                            callback(true, error);
                        } else {
                            if (response.url) {
                                output.url = response.url;
                                callback(false, output);
                            } else {
                                callback(true, "No URL returned for template edit view.");
                            }
                        }
                    });
                }
            });

Here is generated the edit view url. Now i want to edit the template files

 const response = await axios.put(
                `${docusignSet.baseUri}/v2.1/accounts/${docusignSet.docusignAccountId}/templates/${templateData.templateId}/documents`,
                templateUpdate,
                {
                    headers: {
                        'Authorization': `Bearer ${accessToken}`,
                        'Content-Type': 'application/json'
                    }
                }
            );

It gives me error “The user is not the owner of the lock.The template is locked by another user or in another application”.

npm install – problem with installing dependencies

Dear colleagues, my name is Sofia and I have been working as Manual QA for 2 years. Now, I am trying to study API manual testing.

I’m having difficulty installing dependencies for this project: https://github.com/IT-switcher/verifier

Here’s the issue: I cloned this project to my computer using the link https://github.com/IT-switcher/verifier.git. I’m working in VS Code. Then, as mentioned in the instructions, I replaced the line “java:docker”: “./gradlew bootJar -Pprod jibDockerBuild” with “java:docker”: “gradlew.bat bootJar -Pprod jibDockerBuild”. I also tried changing it to “java:docker”: “gradlew bootJar -Pprod jibDockerBuild”, also mentioned in the instructions as a possible alternative. I’m working on Windows 10.

In the end, the dependencies install but with critical errors. After running the command npm fix –force three times, I’m still left with three major issues I can’t resolve no matter what I try.

I’ve tried many approaches. I made sure that the JDK path is correctly configured in my computer settings. Java, Docker, and Node.js are all installed, as you can see in the screenshot. I’ve also tried inputting the error into ChatGPT, but it hasn’t helped me solve the problem yet. Additionally, I tried creating a new Windows account, reinstalling VS Code, cloning the project, and running the npm install again from scratch.

I even tried running the npm install via the Bash terminal instead of PowerShell.

Nothing has worked so far; I keep encountering the same errors with some dependencies. Below are the screenshots.

Has anyone experienced anything similar? I’d be incredibly grateful if someone could help me get this project running on my computer. Feel free to ask if you need additional information or screenshots, and I’ll provide everything needed.

Screenshots are below.

Versions of node, java and docker

Project content

Project content

Errors

Errors

Electron App Icon Not Changing After Installation on Windows

I’m facing an issue with setting the app icon in my Electron.js project. During development, the custom icon appears correctly, but after building and installing the app on Windows 10, the default Electron icon is still displayed.

What I’ve tried:
Icon File:

I created a .ico file and verified it works when applied to folders manually.
Placed the .ico file inside the public and resources folders.
Electron Configuration:

In main.js:

import { app, BrowserWindow, ipcMain } from "electron";
import { fileURLToPath } from "node:url";
import path from "node:path";
import { createNote, deleteNote, getNotes, readNote, writeNote } from "./libs";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

process.env.APP_ROOT = path.join(__dirname, "..");

export const VITE_DEV_SERVER_URL = process.env["VITE_DEV_SERVER_URL"];
export const MAIN_DIST = path.join(process.env.APP_ROOT, "dist-electron");
export const RENDERER_DIST = path.join(process.env.APP_ROOT, "dist");

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL
  ? path.join(process.env.APP_ROOT) 
  : path.join(process.env.APP_ROOT, "resources");

  const iconPath = process.env.NODE_ENV === "development" 
  ? path.join(process.env.VITE_PUBLIC, "/src/assets/logo.ico") 
  : path.join(RENDERER_DIST, "logo.ico");


  console.log(iconPath)

let win: BrowserWindow | null;

function createWindow() {
  win = new BrowserWindow({
    width: 900,
    height: 600,
    minWidth: 900,
    minHeight: 600,
    frame: false,
    transparent: true,
    visualEffectState: "active",
    center: true,
    title: "Note taking app",
    titleBarStyle: "hidden",
    trafficLightPosition: { x: 15, y: 10 },
    icon: iconPath,
    webPreferences: {
      preload: path.join(__dirname, "preload.mjs"),
      contextIsolation: true,
      sandbox: true,
      nodeIntegration: false,
    },
  });

Electron Builder Configuration (package.json)

"build": {
  "appId": "com.example.electronproject",
  "productName": "Notepad Premium",
  "files": [
    "dist/**/*",
    "dist-electron/**/*",
    "node_modules/**/*",
    "resources/**/*",
    "public/logo.ico",
    "package.json"
  ],
  "directories": {
    "output": "release"
  },
  "extraResources": [
    {
      "from": "/src/assets/logo.ico",
      "to": "logo.ico"
    }
  ],
  "win": {
    "target": [
      "nsis"
    ],
    "icon": "/src/assets/logo.ico",
    "signAndEditExecutable": false
  },
  "nsis": {
    "oneClick": false,
    "allowToChangeInstallationDirectory": true
  },
  "asar": true
}

ven after following all these steps, the installed app still shows the default Electron icon in:

The taskbar when running the app.
The Start menu and desktop shortcut.
However, the correct icon appears in development mode.

Check if browser supports installing PWA

How can I check if a user’s browser supports installing PWA?

I’m now trying to add this to a React application, but I want to know for other frameworks as well.

I’ve visited the documentation, but I’m trying to know how I (as the Front-end dev) can check if the user can install the app as PWA.

The best thing I could come up with is this:

const hasSupportForPWA = () => {
   if ('onbeforeinstallprompt' in window) {
      return true;
   }
   return false;
}

Is there a more elegant solution ?

The npx-create-app is not working on my pc [duplicate]

I have a problem with creating a react application. I used the command npx-create-react-app from the official React docs, but it doesn’t work.

I use the nodeJS terminal and the command works for a moment where it says:

Installing packages. This might take a couple of minutes
Installing react, react-dom, and react-scripts with cra-template... 

After these messages appear, the npx command stops and nothing else appears on the terminal.

I know that a React app requires some time, but it’s still the same in my PC. When I ran the command on another pc, it worked just fine.

I tried every other command but to no avail. Is it my PC’s fault? what should I do?

Imports from barrel file don’t work with JEST

I have long-term problem in my tests, when I test something have import from barrel file. Error is same everywhere:

import { funcName } from “../../”;

TypeError: (0 , common_1.funcName) is not a function

This is because import is coming from index.ts, when I import it directly(from source file) it works clear, but I cannot change every file just for have functional tests, I think there is better issue solving, but I can’t find any. (Let’s ignore fact that Barrel files are not good)

Every issue on stackOverflow I saw people suggest to use Mock for single functions, but it seems like not good solution, I cannot test components with empty functions.

I tried to use many configurations in jest, actually I have this one:

  testEnvironment: "jsdom",
  preset: "ts-jest/presets/default-esm",
  injectGlobals: true,
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
    "(.*)/index$": ["$1/index.ts", "$1/index.js"],
    "\.(css|less|scss|sass)$": "identity-obj-proxy",
    "^lodash-es$": "lodash",
    "^lodash-es/(.*)$": "lodash/$1"
  },
  roots: ["<rootDir>/src"],
  modulePaths: ["<rootDir>/src"],
  moduleDirectories: ["node_modules", "src"],
  "transform": {
    "\.[jt]s?$": ["ts-jest", { useESM: true, isolatedModules: true, diagnostics: false }]
  },
  transformIgnorePatterns: [
    "/node_modules/(?!@testing-library).+\.js$"
  ],
  extensionsToTreatAsEsm: [".ts", ".tsx"],
  setupFilesAfterEnv: ["./jest.setup.ts"],
  globals: {
    extensionsToTreatAsEsm: [".ts", ".js"],
  },
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
};

So, the question is if someone had same problem or there’s some familiar solution? I have no idea what to do next because I lost days for fix it, but I wasn’t success in this.

Fetching data from PodBean in JS/Vue/Nuxt

I’m trying to use the PodBean API to just fetch data from my Podcast (a list of episodes), but the documentation isn’t too clear (and I’m not knowledgable enough) to figure out how I do this using Vue/Nuxt/JS.

Does anyone know how to do this?

I tried looking at the PodBean API documentation and someone else’s post on here, but I’m either getting 401 Authorization errors or srtuff just isn’t being fetched.

Alternative to DOMParser for Chrome Extension Service Worker to Parse Stringified DOM and Use XPath

I am working on a Chrome extension and facing an issue with parsing a stringified DOM in the context of the service worker. Specifically, I have a stringifiedDOM, which is the return value of document.documentElement.outerHTML, and I also have a list of XPaths generated by attributes and text to identify elements in this DOM. For all cases, I am considering the count value as 1.

Unfortunately, the DOMParser API does not work in the context of a Chrome extension’s service worker, which means I cannot directly parse the stringified DOM into a document and locate elements using XPath.

What I Need:
An alternative to DOMParser that works in the service worker’s context.
The ability to parse the stringified DOM into a structure that allows me to use XPath expressions to find specific elements.
Ideally, a lightweight third-party library or browser API that works seamlessly in a service worker.
Additional Details:
Here’s a summary of my current process:

I extract the DOM from a web page using document.documentElement.outerHTML and send it to the service worker as a string.
I need to parse this string in the service worker and use XPaths to identify elements inside the parsed DOM.
Attempts:
I tried using DOMParser, but it’s unavailable in the service worker context. I am exploring third-party libraries like xmldom or others that may suit this requirement, but I want to confirm the best approach before proceeding.

Any suggestions or guidance on libraries or techniques that could help me achieve this would be highly appreciated

Strapi – I’m getting error when i am navigating pages like Content Type Builder, Roles Edit, Users edit page

When i am navigating pages like Content Type Builder, Roles Edit, Users edit page.

TypeError: history.at is not a function at http://localhost:1337/admin/node_modules/.strapi/vite/deps/chunk-WZM3OO77.js?v=4ee7e11a:9643:43

enter image description here
and if i am reloading its working.

And Another error when i navigating Content Type Manager page

TypeError: [“id”,(…allowedFields),(…DEFAULT_ALLOWED_FILTERS),(…(intermediate value)(intermediate value)(intermediate value))].map(…).filter(…).toSorted is not a function

enter image description here

This is what i am facing when i run in
System – Edition Windows Server 2022 Standard
Version 21H2
OS build 20348.3091

But if i am running Local Windows machine or Mac or Ubuntu VM instance its working

enter image description here

The error Need to be resolve, Page need to load successfully