Automatically disable a button once there’s no associated element left

I have a list with several elements, and some controlling buttons that can hide/show these elements. Some buttons have control over just one element, while others have multiple elements. Do you maybe know how can I gray out a button automatically when all of its associated elements are already hidden by other buttons? For example:

Button01 hides/shows ElementX and ElementY,
Button02 hides/shows only ElementY.
What I want to do is, graying out Button02 automatically once ElementY is hidden by the other button.

HTML:

<div class="filterbutton" data-filter=".filter01">Filter01</div>
<div class="filterbutton" data-filter=".filter02">Filter02</div>

<div class="filter01">ElementX</div>
<div class="filter01 filter02">ElementY</div>

JS:

for (let button of document.querySelectorAll(".filterbutton")) {
    button.addEventListener("click", filter);
}

let filters = new Set;

function toggleDisplay(selector, display) {
    let elems = document.querySelectorAll(selector);
    for (let elem of elems) {
        elem.style.display = display;
    }
}

function filter() {
    let filterSelector = this.dataset.filter;
    let show = filters.delete(filterSelector);
    this.style.color = show ? "" : "rgb(200,200,200)";
    if (!show) {
        filters.add(filterSelector); // toggle this filter
    } else {
        toggleDisplay(filterSelector, "");
    }
    if (filters.size) {
        toggleDisplay([...filters].join(","), "none");
    }
}

Try/catch async fuunction outside of async context

I have a few classes which use ‘dns’ from node.js. But when an error occurs, my app is thrown. I made a siimple example with classes and throwable functions and I faced with the same problem. It’s works if an exception is thrown from function but it doesn’t work if an exception is thorwn from class.
Example:

class Test {
  constructor() {
    this.t();
  }
  async t() {
    throw new Error("From class");
  }
}

async function test(){
  new Test();
}

try {
  test().catch(e => {
    console.log("From async catch");
  });
} catch (e) {
  console.log("From try catch");
}

Output:

Uncaught (in promise) Error: From class
    at Test.t (<anonymous>:6:11)
    at new Test (<anonymous>:3:10)
    at test (<anonymous>:11:3)
    at <anonymous>:15:3

How to catch errors from try/catch block in this example?

Array.at method not working in React-Native Release and debug(not on browser debuger) builds

I am using react-native (0.68.1) with typescript and unable to use the new Array.at() method in my app as it throws the following error.

Although it does seem to work when using chrome debugger. I understand that the issue is the method being fairly new and not present in the javascript version packaged in the build.But my question is, why it is not poly filled by typescipt? my understanding is that typescript during transpilation replaces non supported features with polyfills.

simulator screenshot iphone 13 iOS 15.0

The following is my typescript config.

    {
     "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react-native",
    "lib": ["es2017"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext",
    "resolveJsonModule": true /* Allows importing modules with a ‘.json’ extension, which is a common practice in node projects. */
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ]
}

How to render html template from a callback function flask

From javascript , I am calling a fetch api which routes to the flask and in flask, I have a function that will get invoked at a interval of 15 seconds. From this callback function how to renderthe template. Earlier I was getting error that you are trying to render template outside the context. I resolved all those issues, Now I am not getting any error, render template line is also getting executed without any exception but in ui the page is not loading.

My object isn’t displaying when i use the javascript constructor method to create an object

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>CREATE JAVASCRIPT OBJECTS USING OBJECT-LITERAL</h1>
    <P id="text"></P>
    <script language="javascript" type="text/javascript">
        document.write("OBJECT CREATION");

        function char(name, anime, specie){
            this.name = name;
            this.anime = anime;
            this.specie = specie;
        }
        var character = char("Goku", "dragonballz", "saiyan");
        document.getElementById("text").innerHTML = character.name + " is from " + character.anime + " and he is a super " + character.specie + " Alien ";
    </script>
</body>
</html>

So… As you can see, I tried using the javascript constructor method to create an object, And its not dispaying, In the console it said character which is the variable name is undefined.
I’m just currently learning javascript, so i would love to get some help.

Can somebody convert Javascript Websocket code to Python Websocket code

I somehow managed to make this WebSocket code work on JavaScript. But then I realized I will require this in my Python API.

Can anyone convert this Javascript to Python so it can do the same job?

    var previous = null;
    var current = null;
    var dataFile = null;
    var process = null

    io.on('connection', (socket) => {
        operation = () => {
            try {
                dataFile = JSON.parse(fs.readFileSync('./progress/progress.json'));
                current = JSON.stringify(dataFile);
            } catch (err) {}

            if (previous && current && previous !== current) {
                process = dataFile["process"]
                if (process == 'Done') {
                    clearInterval(operation_instance)
                    io.emit('progress', { process: process, percentage: "100" });
                }
                if (process && process !== 'Done') {
                    io.emit('progress', { process: process, percentage: dataFile[process] });
                }
            }
            previous = current;
        }
        operation_instance = setInterval(operation, 100);
    });

what is different of set vs append

In Javascript, URLSearchParams Is it different “set” between “append”?

const test = new URLSearchParams();
test.append("name", "Harry Potter");
const test = new URLSearchParams();
test.set("name", "Harry Potter");

^ different?

Highlight and read section by using Javascript

1- I need help creating a code.

2- The app has 18 readers (each reader has csv file), and 114 texts ( each text has csv file)

3- Each reader has csv file :1soundlinks.csv, 2soundlinks.csv,…,18soundlinks.csv to indicates start-stop times for each reader. So, for each reader has to read 114 texts files.
1soundlinks.csv has three columns:

column 1, column2, column3, column4

Text#, Audio file, Link of Audio, the points of times

text1، 110401.mp3 , Link of Audio(In Google Drive) , the points of times (highlight)
text2، 110402.mp3 , Link of Audio(In Google Drive) , the points of times (highlight)
text3 ، 110403.mp3 , Link of Audio(In Google Drive) , the points of times (highlight)

https://drive.google.com/drive/folders/1aWtwj5OxYfYzxa6mgmEH75WpwaHADHW_?usp=sharing

Here are only 2 texts of 114 texts

1.csv means text number wich is the first text 1

This link for 1.csv

https://docs.google.com/spreadsheets/d/1igSCZEPs0yC6wRfq-_y5hFh2T6OlYBtek-saRtfDhZQ/edit?usp=sharing

114.csv means text number 114 wich is the last text 114

 This the link for 114.csv

https://docs.google.com/spreadsheets/d/1NMp30H8vTCSsFwPQvd6iImP_ZF3eMWkV7aVb9KmQJkg/edit?usp=sharing

These text csv files have two columns

column1, column2.

No of line, sentence

1,sentence1

4- The app will take a csv file of lines of text (in arabic), with a corresponding audio file (there are 114.csv files for texts and 17 csv sound files), and display the lines of the csv file. The user can then play the audio file, and the respective lines will be highlighted, or the user can select a line and that line will be played back, and then continue playback from there. The user should be able to select any csv file (and corresponding audio file) and the user may also select a different audio file for the same csv.

5- I have quite a few display and formatting requirements for the arabic text and the layout

6- I want to highlight a line / section of text in html. By set tags e.g. id, to each section of text I wish to highlight, then run a javascript function to apply the highlight to that identified section of text. Then I would need to pass the selected text position back to the app in order to play the relevant sound

7- I have all the assets – csv, timings, audio files, arabic fonts, that I believe are required. These are currently located on google drive, along with files that help to synchronise the text and audio.

8- There is significant history on the community for many parts of this work already

This is the .apk

https://drive.google.com/file/d/1RvSM5F4-azcDTo6UqvID1tfDHCwLv0aK/view?usp=sharing

remove clicked word from textarea with vanila js

i try to remove x item each time i click on “item name x”
i came with folowing code but this just remove every item added by click no matter if matches.
as basic code with ‘item name x’ instead of ‘r.innerHTML’ works fine but only for elements that are already there and not for items added by click.

<html>

<textarea id="cartlist">
item name 4
item name 4
</textarea >
<br />
<div class="itm"><a href="#" data-item="1" id="it">item name 4</a><p>add item name 
4</p></div>
<div class="itm"><a href="#" data-item="1" id="it">item name 3</a><p>add item name 
3</p></div>
<br><br>
remove:<a href="#" class='toBeRemoved' onclick="removeOnlyThis()"> item name 4</a>
remove:<a href="#" class='toBeRemoved' onclick="removeOnlyThis()"> item name 3</a>
<br><br>
<a href="#"  class="remove" onclick="eraseText();">remove all</a>
</html>
 <style>
#cartlist {
width: 100%;
height: 100px;
}
p{
position:absolute;
top:-15px;
z-index:-1;
text-decoration:underline;
}
.itm{
position:relative;
height:20px;
color:green;}
#it{opacity:0;
width:110px;
background:pink;
position:absolute;
 }
body{
background:#111;
}
</style>
<script>
var cartlist = document.querySelector('#cartlist');
var items = document.querySelectorAll('[data-item]');

[].forEach.call(items, function(item) {
item.addEventListener('click', function(){
    ta.value += "n" + item.innerHTML;
});
});

function eraseText() {
document.getElementById("cartlist").value = "";
}


var ta = document.querySelector("#cartlist");
var r = document.querySelectorAll('.toBeRemoved')
for (var i = 0; i < r.length; i ++) {
var id = (r[i].innerHTML);
}
var lines = ta.value.split(/n/g);

function removeOnlyThis(){
for (var i = 0; i < lines.length; i ++) {
if (lines[i].indexOf(id) > -1) {
lines.splice(i, 1);    
}
}

ta.value = lines.join('n');

}
</script>

Close active Bootstrap 5 Tab on click

This question has been asked for Bootstrap 4 and lower but not for Bootstrap 5 I think. For Bootstrap 4 I used some Jquery like this https://www.codeply.com/go/bp/61835

When an active tab gets clicked, the ‘active’ class should be removed from the tab button and the tab pane should be hidden.

Does someone has a simple solution for that? I cannot get it to work without calling preventDefault() for the Bootstrap events (‘show’, etc) and doing everything manually.

Thanks!

React website needs reading CSV in the same folder

I am a newbie studying webengineering. So, this may be a stupid question.

I am now practicing building a simple website by React and try to satisfy the followings.

  1. reading CSV file in the same directory in App.js. This CSV file is not uploaded by tag
  2. parsing the CSV file to JSON.
  3. displaying a table of the data.

When I google the “read csv React”, the results are almost about reading CSV file by uploading.
I know React is a framework for the front architecture.

Let me know the standard to solve this.

React Infinite scroll component not working properly

I am using react-infinite scroll component like this:

const [hasMore, setHasMore] = useState(true)
const [pageNumber, setPageNumber] = useState(1)

  const fetchDataOnScroll = async () => {
    try {
      const res = await axios.get(
        `${process.env.REACT_APP_API}/api/v1/posts?page=${pageNumber}`
        
      )
  
      (res.data.doc.length === 0) setHasMore(false)

      setPosts((prev) => [...prev, ...res?.data?.doc])
      setPageNumber((prev) => prev + 1)
    } catch (error) {
      alert('Error fetching Posts')
      console.log('ERROR', error.data.response)
    }
  }

  return (
<InfiniteScroll
   hasMore={hasMore}
   next={fetchDataOnScroll}
   endMessage='No More Post'
   dataLength={posts.length}
   loader={<h1>LOADING...</h1>}
>
{posts.map((post) => (
 <FeedCard key={post._id} post={post} />
))}
 </InfiniteScroll>
)

I only get LOADING… on my browser. But when I write my next as next={fetchDataOnScroll()}, It renders continuously until the page freezes. I have to close my browser.

How can i fix this?

Massive memory/RAM usage with Chokidar Node.js package from pre-existing files in directory being watched unnecessarily

I’m using the Node.js package “chokidar” for this use case:

  • I’m just watching a single directory on Linux, not recursively
  • I only need it to watch for add events, for when files are atomically moved into the watched directory (they’re moved from another directory on the same filesystem once all changes are done)
  • I don’t need it to look at pre-existing files in the dir at all, just watch for new ones since the app started

Problem:

  • When there is a large number of pre-existing files (like 80k) in the directory when I start my node.js app, Chokidar seems to put a watch on all of them, even though I don’t care about watching existing files at all
  • Initially this was hitting the kernel watch limit, but I’ve already solved that with:

…

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
  • The remaining issue is that all these pre-existing files are being watched, which uses a massive amount of RAM for no reason, as I don’t need it watching those files at all.
  • Is there any way to have Chokidar just entirely ignore all these pre-existing files, and do nothing but watch this single directory for add events for new files only?
  • I know about increasing Node’s RAM limits (which didn’t work in this case anyway), but I feel like it shouldn’t be using all this RAM in the first place, and I want it to be efficient on a small VPS. I’d like to solve the RAM usage issue rather than just give it more RAM than it should need in the first place.

I’m using this code:

chokidar.watch("/my-watched-dir", {
    ignoreInitial: true,
})
.on('add', (filepath) => {...}

I’ve also tried setting the depth option to 0 and 1 too.

The memory usage climbs very high as soon as the app starts (even before the 1st new file appears triggering the add event for the first time).

And there’s no problem when the number of pre-existing files is smaller, so it’s not an issue related to through-put of new files after the app starts.