How to enable touch-like scrolling by grabbing and dragging with the mouse?

Here is a minimal example of what I’m trying to do:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    #box {
      background-color: red;
      width: 200px;
      height: 250px;
      overflow-x: hidden;
      overflow-y: scroll;
      cursor: grab;
    }
    #box div {
      background-color: blue;
      margin: 30px;
      width: 100px;
      height: 100px;
    }
  </style>
</head>
<body>
  <div id="box">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>
</body>
</html>

If you’re on mobile, you will be able to scroll through #box by touching and dragging up or down. However, if you’re on a desktop browser, then you will have to use the scrollbar or the mouse scroll wheel.

How can I enable scrolling by grabbing (i.e. pressing and holding the left mouse button) and then dragging (i.e. moving the mouse) up or down? Can I solve it with CSS only?

connecting lines between web elements

I’m making a web page with Bootstrap 5 and a specific design, I’ve been trying for several days to generate this part but I haven’t found anything. I can think of placing a div to generate the horizontal line.

Is it possible to create something like this image? enter image description here

<div class="bd-example">
<div class="card" style="width: 18rem;">
  <img class="card-img-top" data-src="holder.js/100px180/?text=Image cap" alt="Image cap [100%x180]" style="height: 180px; width: 100%; display: block;" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22286%22%20height%3D%22180%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20286%20180%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_1879f97305a%20text%20%7B%20fill%3Argba(255%2C255%2C255%2C.75)%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A14pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_1879f97305a%22%3E%3Crect%20width%3D%22286%22%20height%3D%22180%22%20fill%3D%22%23777%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%2299.12312316894531%22%20y%3D%2296.6%22%3EImage%20cap%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true">
  <div class="card-body">
    <h5 class="card-title">Card title</h5>
   
  </div>
  <ul class="list-group list-group-flush">
    <li class="list-group-item">Cras justo odio</li>
    <li class="list-group-item">Dapibus ac facilisis in</li>
    <li class="list-group-item">Vestibulum at eros</li>
  </ul>
  <div class="card-body">
 
  </div>
</div>
</div>

React App does not re-render when clicked into a NavLink. The URL changes, but the page does not

This is the App.js file

import './App.css';
import {BrowserRouter, Route, Switch, NavLink} from 'react-router-dom'
import Home from './pages/Home.js'
import About from './pages/About.js'
import Contact from './pages/Contact.js'

function App() {
  return (
    <div className="App">
    <BrowserRouter>
      <h1>brruh</h1>
      <nav>
        <NavLink exact to="/">Home</NavLink>
        <NavLink to="/about">About</NavLink>
        <NavLink to="/contact">Contact</NavLink>
      </nav>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/about" component={About}/>
        <Route path="/contact" component={Contact}/>
      </Switch>
    </BrowserRouter>
    </div>

  );
}
export default App;

And this is the index.js file

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

I tried reinstalling the react-router-dom package, however the problem still persists.
If I manually access the other pages (about and content), they show up.
Or if I click on the About page link and then refresh the page, the About page shows up.
However, those pages do not show up without page refreshing but the URL does change

In a PDF file, what Javascript code can I use in calculation that could tell if the user edited a field?

In a PDF file, what Javascript code can I use in calculation that could tell if the user edited a field? This field in question calculates what is input into the field based on a drop-down menu. However, I want the users to be able to edit the field if they want. But every time you try to edit the field and click off of it, it goes back to what it was before. So, I figured an easy way to fix it is if there is some variable that tells me if it was either calculated or edited by user, and if edited by user, I would just put an if statement in there to prevent the calculation. If you can think of any other creative solutions to this problem, I would be interested to hear it.

Is there a way to wrap a SharedWorker in a Promise?

I tried to use webworker-promise to wrap a SharedWorker in a promise based way. But that doesn’t seem to be working. Is there a way to make this work or is there some other library available?

import WebworkerPromise from 'webworker-promise'

const worker = new WebworkerPromise(new SharedWorker('worker.ts'));

dex.js:67 Uncaught (in promise) TypeError: this._worker.postMessage is not a function
    at index.js:67:20
    at new Promise (<anonymous>)
    at Worker.postMessage (index.js:64:12)
 

Cannot find module ‘express’ even though ‘express’ is already installed

I ran the command npm start and got the following error.

node:internal/modules/cjs/loader:928
  throw err;
  ^

Error: Cannot find module 'express'
Require stack:
- C:CodecodeFilecode-file-appdistserverserver.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:925:15)
    at Function.Module._load (node:internal/modules/cjs/loader:769:27)
    at Module.require (node:internal/modules/cjs/loader:997:19)
    at require (node:internal/modules/cjs/helpers:92:18)
    at Object.<anonymous> (C:CodecodeFilecode-file-appdistserverserver.js:6:35)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:973:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12) {
  code: 'MODULE_NOT_FOUND',
}
npm ERR! code 1
npm ERR! path C:CodecodeFilecode-file-appserver
npm ERR! command failed
npm ERR! command C:WINDOWSsystem32cmd.exe /d /s /c node ../dist/server/server.js

npm ERR! A complete log of this run can be found in:
npm ERR!     C:Userspatriv5AppDataLocalnpm-cache_logs2023-04-20T15_45_54_540Z-debug.log

I already ran the command npm install express and see express listed in my package.json dependencies and in my node_modules folder yet I am still receiving the error. Has anybody else encountered this issue?

How to access individual properties in an array of objects returned from axios post?

I am trying to search a database for records on specific workout data to use Chart.js to display a line graph showing progress. I have the data returned from axios, but when trying to use chart.js, it give me an error saying I can’t use an array of objects as input for chart, so I need to access the individual properties of each object to create an array for the x and y axis.

What would be the syntax for accessing each date and weightOne from all objects?

one of the 14 objects returned from axios post

I have tried accessing the properties from the axios response in a loop and adding each date and WeightOne to an array, but the arrays are still empty.

Vaadin and Quill Editor: Issues with saving the current content

I am having an issue with integrating the Quill Editor into my Vaadin application. When I change the content of the editor and save it, I do not get the current content of the editor but the previous content instead. I have tried to get the content using CompletableFuture and executeJs, but it still doesn’t work as expected. When I try to save the new content, setValue is called, but futureContent.get() returns null.

Here is the relevant code:

@JsModule("./js/quill.js")
public class QuillEditor extends AbstractSinglePropertyField<QuillEditor, String> {

  public QuillEditor() {
        super("value", "", false);
        getElement().executeJs("createQuillEditor($0)", getElement());

        getElement().addEventListener("text-change", event ->
                fireEvent(new ComponentValueChangeEvent<>(this, this, getEmptyValue(), false)));
    }

    @Override
    public String getValue() {
        CompletableFuture<String> futureContent = new CompletableFuture<>();

        ui.access(() -> {
            PendingJavaScriptResult pendingResult = getElement().executeJs("return getHtmlContent($0)", getElement());
            pendingResult.then(jsonValue -> futureContent.complete(jsonValue.asString()));
        });

        try {
            return futureContent.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public void setValue(String htmlContent) {
        getElement().executeJs("setQuillEditorHtmlContent($0, $1)", getElement(), htmlContent);
    }
}

quill.js

window.createQuillEditor = function (element) {
    const quill = new Quill(element, {
        theme: 'snow',
        modules: {
...... etc.

window.getHtmlContent = function (element) {
    const quill = Quill.find(element);
    console.log('Current content:', quill.root.innerHTML);
    return quill.root.innerHTML;
};

window.setQuillEditorHtmlContent = function (element, htmlContent) {
    const quill = Quill.find(element);
    quill.setContents(quill.clipboard.convert(htmlContent));
    console.log('HTML Content:', quill.root.innerHTML);
};
}

I have added various console.log() statements to check the content of the editor, and it seems that the JavaScript code is correctly retrieving the current content. However, the new content is not being properly passed to the Java code.

Does anyone have experience with integrating the Quill Editor and Vaadin or have an idea how I can fix this issue? Any help is greatly appreciated!

Thank you in advance!

In my other class, I have implemented the following binding:

binder.forField(quillEditor).bind(CustomTextblock::getContent, CustomTextblock::setContent);

Grabbing content from tag and passing to OpenAI API for processing

I am building a script using the OpenAI API that grabs text content from a clicked on

tag in index.html and passes to a separate script in explanation.html where the content from the clicked on

tag in index.html is passed to the script in explanation.html where OpenAI processes the content as “What does this sentence mean?” +

content and returns an output that is an explanation of the

content provided to the OpenAI API.

Here is the code I am working with:

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Example</title>
    <script type="text/javascript">
      function showExplanation(element) {
        const sentence = element.textContent.trim();

        fetch('/explanation.html?sentence=' + encodeURIComponent(sentence))
          .then(response => response.text())
          .then(explanation => {
            const win = window.open('', '_blank');
            win.document.write('<html><head><title>Explanation</title></head><body><p>' + explanation + '</p></body></html>');
          })
          .catch(error => console.log(error));
      }
    </script>
  </head>
  <body>
    <a href="#" onclick="showExplanation(this)">Sentence 1</a>
    <a href="#" onclick="showExplanation(this)">Sentence 2</a>
    <a href="#" onclick="showExplanation(this)">Sentence 3</a>
  </body>
</html>

explanation.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Explanation</title>
  </head>
  <body>
    <p>Loading...</p>
    <script type="text/javascript">
      const sentence = new URLSearchParams(window.location.search).get('sentence');
      const api_key = 'YOUR_OPENAI_API_KEY_HERE';

      fetch('https://api.openai.com/v1/engines/davinci-codex/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + api_key
        },
        body: JSON.stringify({
          'prompt': "What does this sentence mean? " + sentence,
          'max_tokens': 512,
          'n': 1,
          'stop': '.'
        })
      })
        .then(response => response.json())
        .then(output => {
          const explanation = output.choices[0].text;
          const pElement = document.createElement('p');
          pElement.textContent = explanation;
          document.body.innerHTML = '';
          document.body.appendChild(pElement);
        })
        .catch(error => console.log(error));
    </script>
  </body>
</html>

I tried running the code on My live site and it seems to be getting stuck with a “Loading…” response. The static “Loading…” in the code is not being replaced by the dynamic explanation being fetched from the OpenAI using the provided prompt + sentence extracted from the

tag. Any ideas on how to get this script to return the dynamic explanation?

convert xml to json and force element into array

from this xml:

<pazienti type="array">
<paziente type="Paziente">
<pz-ds-cognome>COGNOME</pz-ds-cognome>
<pz-ds-nome>NOME</pz-ds-nome>
</paziente>
</pazienti>

using this javascript:

// Function to convert XML -> JSON
function convertXmlToJson(xml) {
  const parser = new xml2js.Parser({ explicitArray: false, ignoreAttrs: true });
  return new Promise((resolve, reject) => {
   parser.parseString(xml, (err, result) => {
    if (err) {
      reject(err);
    } else {
      const pazienti = result.pazienti;

      if (pazienti && pazienti.paziente && !Array.isArray(pazienti.paziente)) {
        pazienti.paziente = [pazienti.paziente];
      }
      resolve(result);
    }
});

});
}

when there are more “pazienti” it works fine, when there is only one “paziente” i get:

"pazienti": {"paziente": {"pz-ds-cognome": "COGNOME.","pz-ds-nome": "NOME"}}

I would like to get:

"pazienti": { "paziente":[{"pz-ds-cognome": "COGNOME.","pz-ds-nome": "NOME"}]}

Otherwise when there are more “pazienti”:

"pazienti": { "paziente":[{"pz-ds-cognome": "COGNOME1.","pz-ds-nome": "NOME1"},
                          {"pz-ds-cognome": "COGNOME2.","pz-ds-nome": "NOME2"}]}

How to store multilevel conditions in an array

I want to code a function to handle definable conditions.

The reference data is contained in an object and a simple condition is stored in a 3 elements array like this :

["name", "==", "John Doe"]

here is the code that works well to test a simple condition:

function getResultOfSimpleCondition(data, condition) {
    let c1 = data[condition[0]],
        operateur = condition[1],     
        c2 = condition[2], cond=true;
        switch(operateur){
                case "==" :
                case "="  :         cond = (c1 == c2 ); break;
                case "!=" :         cond = (c1 != c2 ); break;
                case ">"  :         cond = (c1 >  c2 ); break;
                case "<"  :         cond = (c1 <  c2 ); break;
                case ">=" :         cond = (c1 >= c2 ); break;
                case "<=" :         cond = (c1 <= c2 ); break;
                case "like":        cond = (c1.indexOf(c2) >  -1); break;
                case "not like":    cond = (c1.indexOf(c2) == -1); break;
                default   :         cond = (c1 == c2 ); break;
        }
    return cond
}

let myData = { name:'John Doe', age:'28', town:'PARIS', qty:5, uptodate: true},

    condition_0 = ["name", "==", "Jack Sparrow"],    // result false
    condition_1 = ["age", ">=", "24"],               // result true
    condition_2 = ["uptodate", "==", false],         // result false
    condition_3 = ["town", "==", "PARIS"];           // result true

console.log( getResultOfSimpleCondition(myData, condition_0) )

what I’m looking for is how to implement more complex conditions on the same principle.

For example:

on 2 levels:

[ condition_0, "OR", condition_1 ] // result true

or

[ condition_1, "AND", condition_2 ] // result false

on more levels:

[[ condition_0, "OR", condition_1 ], "AND", condition_3] // result true

or

[[ condition_0, "OR", condition_1 ], "AND", condition_3, "AND NOT", [condition_5, "OR", condition_23 ] ]

thank you in advance

How to make cards scroll vertically

What is the best way to create a vertical scroll when one card is stacked on top of another, similar to the example shown in the link below?

Link here

I’ve searched some information and examples but haven’t found anything.

If anyone knows or has examples, please share.

Is it faster to work with array or with dict?

I have ~1Kb dict looking like:

db = {"word": 0, "something": 1, "another": 2, ..., "last": 36000}

and I use the following operations:

  1. find an index of some word (like db["something"]);
  2. find word by its index (like Object.keys($db)[1234])

It works slowly. Would it help if I switch to array?

Chrome Extension – Jquery not loading

I am trying to run JQuery on the chrome extension I built. I am getting the following errors when I load the extension. Uncaught ReferenceError: $ is not defined and Refused to load the script ‘https://code.jquery.com/jquery-3.5.1.min.js’ because it violates the following Content Security Policy directive: “script-src ‘self’ blob: filesystem:”. Note that ‘script-src-elem’ was not explicitly set, so ‘script-src’ is used as a fallback.

So currently I have a thirdParty folder with jQuery-3.5.1.js file

This is how manifest.json looks:

    "manifest_version" : 2,
    "name" : "Calculator",
    "version" : "1.0",
    "description" : "Calculate Anywhere",
    "icons" : {
        "128" : "img/icons128.png",
        "48" : "img/icons48.png",
        "16" : "img/icons16.png"
    },
    "background":
    {
        "scripts": ["thirdParty/jquery-3.5.1.min.js", "background.js"]
    },
    "browser_action" : {
        "default_icon" : "img/icons16.png",
        "default_popup" : "popup.html"
    }
}

this is my backround.js

chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.tabs.executeScript({
        file: 'thirdParty/jquery-3.5.1.min.js'
    });
    chrome.tabs.executeScript({
        file: 'popup.js'
    });
});

popup.js has the main JS and Jquery code for my extension.
Furhtermore I have a script tag to call jquery script in my popup.html which looks like this

    
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

Can someone please tell me what I am missing in the code!!