node – How to rename files according to a certain pattern

I’m working on a node script to rename files and remove from inside each file a pattern.
At the moment I have this code and it will create a backup copy of the files and folder where the files to rename and edit are placed

#!/usr/bin/node

const fs = require('fs-extra'); 
const path = require('path');

const backupPath = path.join( __dirname , 'wp-backup');
const excludedResources = ['.DS_Store', 'deprefixer.js', 'node_modules'];
const filenamePattern = 'wp-';
const wpFolders = [];
const wpFiles = [];

//
fs.readdir( __dirname, { withFileTypes: true }, (err, files) => {
    if( err ) {
        console.log(err);
    }
    console.log(files.length);
    if( !fs.existsSync( backupPath ) ) {
        fs.mkdir( backupPath, () => {
            for( let file of files ) {
                if( excludedResources.indexOf(file.name) >= 0 ) {
                    continue;
                }
                const srcPath = path.join( __dirname, file.name);
                const destPath = path.join( backupPath, file.name );
                if( file.isDirectory() ) {
                    fs.copy( srcPath, destPath, (err) => {
                        if( err ) {
                            console.log(err);
                        }
                    });
                    wpFolders.push(srcPath);
                    console.log(wpFolders);
                } else {
                    fs.copy( srcPath, destPath, (err) => {
                        if( err ) {
                            console.log(err);
                        }
                    });
                    // not sure here how to proceed.
                    // will be the match() function and a regex better?
                    if( file.name.startsWith('wp-') ) {
                        //fs.renameSync()
                    }
                    wpFiles.push(srcPath);
                    console.log(wpFiles);
                }
            }
        });
    }        
});
    


Accrding to this other question, since I will need to edit the content of the file if a pattern is found, I will implement readline to access each single file and search inside of it. How I can rename the files if the file name will have the pattern I’m looking for?

Three.js relative forces while having a negative force

I’m making a small and simple car simulator. I have a class called GameController where the physics handler is described. In there the absolute forces are converted to relative forces and applied to the position of the object. But now when I am accelerating the object by adding a positive force (pressing W) and then slow down by a backwards force it stops and doesn’t proceed to go backwards even though it gets a negative force.

I know this is caused by the orientation of the player. I set it to follow the velocity but when the velocity becomes negative it flips the object around it’s up axis and now forwards = backwards and the negative force is now headed the other way. It looks like it stands still now.

This is the Physics Handler in the GameController Class:

physicsHandler_(o)
    {
        var vn = new THREE.Vector3().copy(o.velocity_).normalize();

        var up = new THREE.Vector3(0, 1, 0);
        var right = new THREE.Vector3();
        
        right.crossVectors(up, vn).normalize();
        up.crossVectors(vn, right).normalize();
        
        var matrix = new THREE.Matrix4();
        matrix.set
        (
            right.x, up.x, vn.x, 0,
            right.y, up.y, vn.y, 0,
            right.z, up.z, vn.z, 0,
            0, 0, 0, 1
        );

        o.force_.applyQuaternion(o.quaternion_);
        o.acceleration_ = new THREE.Vector3(o.force_.x / o.mass_, o.force_.y / o.mass_, o.force_.z / o.mass_);
        o.velocity_.addScaledVector(o.acceleration_, delta);
        o.position_.addScaledVector(o.velocity_, delta);

        o.quaternion_.setFromRotationMatrix(matrix);
        o.mesh_.position.copy(o.position_);
        o.mesh_.quaternion.copy(o.quaternion_);

        o.force_.set(0, 0, 0);
    }

This is the input part:


gc.addToLoop_(function()
{
    if(gc.input_.keys_['w'])
    {
        car.force_ = new THREE.Vector3(car.force_.x, car.force_.y, car.force_.z + car.forceMotor_);
    }
    if(gc.input_.keys_['s'])
    {
        car.force_ = new THREE.Vector3(car.force_.x, car.force_.y, car.force_.z - car.forceMotorBackwards_);
    }
    if(gc.input_.keys_['a'])
    {
        car.force_.applyQuaternion(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), -5));
        
    }
    if(gc.input_.keys_['d'])
    {
        car.force_.applyQuaternion(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), 5));
    }
});

I tried to use Chat-GPT. Didn’t give any clear answers.

Also tried to check if the angle between the previous quaternion was the other way around but didn’t get any results.

Overlay a video with rounded corners – FFMPEG React Native (Like Facetime or other Video Chats)

I’m trying to overlay one video on top of another using FFMPEG, in the exact same format as FaceTime, but the video would have rounded corners. I’ve tried the commands on other posts but they all generate unexpected results or errors.

Here is the command that overlays the videos decently:

-i main_video.mp4 -i small_overlaid_video_in_lower_left_corner.mp4 -filter_complex 
        "[0:v]scale=iw:ih[main_scaled]; 
        [1:v]scale=iw/2:ih/2:force_original_aspect_ratio=decrease,format=yuva420p[reaction_resized]; 
        [main_scaled][reaction_resized]overlay=x=40:y=H-h-40:format=auto[final]" 
        -map "[final]" -map 1:a? -c:a copy -c:v libx264 -crf 18 -preset ultrafast -t -y output.mp4

The problems this has is that the main videos resolution varies from video to video, so sometimes the overlaid video is super small and sometimes its too big. Three questions:

  1. How do I make the overlaid video the same size in comparison to the main video every time?
  2. How can I apply rounded corners on the rectangle?
  3. How can I modify it to include both video’s audio?

Flatten a Multilevel Doubly Linked List leetcode error

I don’t understand why do you get error even when you try to just return head linked list that was given as an argument here is a question

  1. Flatten a Multilevel Doubly Linked List
    Medium

Topics
Companies
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below.

Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list.Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null.

link to that question https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/description/

Even when you try to just return the argument you get this error:

Line 129 in solution.jsnode = node.next;^TypeError: Cannot read properties of undefined (reading ‘next’)

for the life of me I don’t understand why? the argument you are given is a node is it because child node was not set to null but you should not get error for that I don’t know. if somebody can explain what is going on I will be very grateful.

Show content depending on dy and time

I was looking for answers here but couldnt fin. Im pretty unexperienced with Javascript. Where is my error. I cant get this script to work. It’s supposed to show specific content on the website depending of the day of the week and the time of the day.

$(document).ready(function () {

var start = new Date();
var end = new Date();
var time = new Date().getTime();



let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

days.forEach((day,index)=>{
    // Check if the index of day value is equal to the returned value of getDay()
if(index == new Date().getDay()){
    if (time >= start.setHours(06,00) && time =< end.setHours(09,59)) {
    let show = "Show1";
    $(".open").show();
    $(".closed").hide();
}
else {
    $(".open").hide();
    $(".closed").show();

}
if (time >= start.setHours(10,00) && time =< end.setHours(11,59)) {
    let show = "Show2";
    $(".open").show();
    $(".closed").hide();
}
else {
    $(".open").hide();
    $(".closed").show();

}
if (time >= start.setHours(12,00) && time =< end.setHours(13,59)) {
    let show = "Show3";
    $(".open").show();
    $(".closed").hide();
}
else {
    $(".open").hide();
    $(".closed").show();
)
}}};

I want this script set conditions which i can use in to display a specific information which show is actually on.

These are the containers:

  <div class="open">Christian Music Nonstop</div>
  <div class="closed">Nope</div>

Masonry.js elements going on a single column after updating the amount of elements

I have a number of images that I have in 5 columns. I can sort those elements using tags, this dynamically changes the amount of images shown.

Issue :

All is normal and well at first. But when I select a tag, the images that are remaining get put in a single column, instead of keeping the 5 columns arrangement.


Before

Images in 5 columns


After

Images now in 1 column


Note that this doesn’t happen when the first image of the grid is included in the selected tag :

First image stays the same, the rest changes


I have explored every possibility and I don’t know how to debug this. So here’s relevant code :

<head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Cotton Mémoires</title>
        <link rel="icon" type="image/x-icon" href="files/favicon2.ico">
        <link rel="stylesheet" href="styles.css">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/masonry/4.2.2/masonry.pkgd.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/imagesloaded/4.1.4/imagesloaded.pkgd.min.js"></script>
        <script src="https://unpkg.com/imagesloaded@5/imagesloaded.pkgd.min.js"></script>
</head>

<body
        <div class="pdf-container">
                <a class="pdf-button" data-tags="IN, 2021, Didactique, Interaction"
                    href="link_to_pdf"><img src="IMAGE">
                </a>
                <a class="pdf-button" data-tags="2021, IN, Cinema" 
                    href="link_to_pdf"><img src="IMAGE">
                </a>
                <a class="pdf-button" data-tags="2021, IN"
                    href="link_to_pdf"><img src="IMAGE">
                </a>
        </div>
</body>
.pdf-container {
    padding-top: 50px;
    padding-bottom: 50px;
}

.pdf-container .pdf-button {
    max-width: 20%;
    padding: 0.9%;
    box-sizing: border-box;
}

.pdf-container .pdf-button a img {
    width: auto;
    border-radius: 10px;
    cursor: pointer;
    object-fit: cover;
}

.pdf-button:hover {
    opacity: 0.7;
}

.pdf-button {
    padding: 16px 16px;
    margin-bottom: 5px;
    margin-top: 5px;
    height: auto;
}

.pdf-container a img {
    width: 100%;
    border: 7px solid var(--accent-color2);
    border-radius: 20px;
    cursor: pointer;
}
// scripts.js

const pdfButtons = document.querySelectorAll('.pdf-button');
const tagButtons = document.querySelectorAll('.tag-button');
const pdfViewer = document.getElementById('pdf-viewer');

// Array to store selected tags
let selectedTags = [];

// Add event listeners to tag buttons
document.addEventListener('DOMContentLoaded', (event) => {
    var grid = document.querySelector('.pdf-container');
    var masonry = new Masonry(grid, {
        percentPosition: true,
    });

    tagButtons.forEach(button => {
        button.addEventListener('click', () => {
            const selectedTag = button.getAttribute('data-tag');
            if (selectedTags.includes(selectedTag)) {
                selectedTags = selectedTags.filter(tag => tag !== selectedTag);
                button.classList.remove('selected-tag');
            } else {
                selectedTags.push(selectedTag);
                button.classList.add('selected-tag');
            }
            pdfButtons.forEach(pdfButton => {
                const tags = pdfButton.getAttribute('data-tags').split(', ');
                if (selectedTags.every(tag => tags.includes(tag))) {
                    pdfButton.style.display = 'block';
                } else {
                    pdfButton.style.display = 'none';
                }
            });
            setTimeout(() => {
                masonry.layout();
            }, 50);
        });
    });

});

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

const tagArray = Array.from(pdfButtons);

const shuffledTagArray = shuffleArray(tagArray);

const tagSelector = document.querySelector('.pdf-container');
tagSelector.innerHTML = '';
shuffledTagArray.forEach(button => tagSelector.appendChild(button));

document.addEventListener('DOMContentLoaded', (event) => {
    var grid = document.querySelector('.pdf-container');
    var masonry = new Masonry(grid, {
        itemSelector: '.pdf-button',
        columnWidth: '.pdf-button',
        percentPosition: true
    });

    var images = document.querySelectorAll('.pdf-button img');

    var loadedImages = 0;

    function imageLoaded() {
        loadedImages++;
        if (loadedImages === images.length) {
            masonry.layout();
        }
    }

    images.forEach(function (image) {
        image.addEventListener('load', imageLoaded);
        if (image.complete) {
            imageLoaded();
        }
    });

    window.addEventListener('resize', function () {
        masonry.layout();
    });

    setTimeout(() => {
        masonry.layout();
    }, 100);
});

There shouldn’t be any issue in the css nor in the html as I have checked both and they are fairly straightforward.

I’m guessing the issue is in the js as it’s what I’m least familiar with, but I’ve tried and nothing seems to change.

Deleting parts of the code entirely to see which one breaks is my manner of debugging but it can only go so far.

How do I link a chtml file to a Javascript file in .net core?

So I’m wanting to create a simple dropdown list using Javascript . So I’m just wondering how do I link up the chtml file containing the structure to the right Javascript file in .net core 8. I’m using the webapp MVC template.

There is the wwwroot folder containing the Javascript file but I’m just not sure how to link that up with my page.

I know there is the _Layout file that contains the stylesheets and Js & Jquery links but I’m not sure how to link them up

I’ve tried creating a normal dropdown with @Html but it does not suit my use case.

Here is the Home Index file that I’m working with

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}



<div class="text-center">

    <label class="form-label" >Role</label>
    @Html.DropDownList("Role", 
    Html.GetEnumSelectList<ERoles>(), "Select Role", 
    new { @class = "form-control"})



</div>

Nodejs – Inserting Data to Mysql from CSV file With More Than 1000 Row

I’m trying to insert data to MySQL from a CSV file that contain atleast 100.000 row.

There are 2 approach that i have tried:

1.Parse the CSV file to JSON and insert each row to Mysql. The code will somewhat look like:

function insertData(data){  
    const connection = await pool.getConnection();  
    await connection.beginTransaction();  
    try{  
        data.map((row) => {  
        const q = "INSERT INTO table(col) VALUES(?)";  
        await connection.query(q, [row.col])
        });
        await connection.commit();  
    }catch(err){
        await connection.rollback();  
        console.log(err);  
    }  
}

the problem that i had with this approach is that the query will fail and rollback at row 1000. I guess it has something to do with max number of row inserted to Mysql? how does that even work really, since i use loop to insert the row one by one?

  1. Insert to MySQL directy using LOAD DATA INFILE QUERY. The code will look like:
const addData = async(filePath) => {
//the file is already uploaded and stored on the server using multer
    const connection = await pool.getConnection();
    try{
        const q = `LOAD DATA INFILE ${filePath}
                    INTO TABLE table1                  
                    FIELDS TERMINATED BY                 
                    ENCLOSED BY                 
                    LINES TERMINATED BY                 
                    IGNORE 1 LINES` ;
        const result = await connection.query(q);
        return result
    }catch(err){  
        await connection.rollback();
        console.log(err);
        return {err}
    }
};

This approach work just fine, with a small problem. It only work when the file is stored in the mysql folder (in my case its ‘C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/’). Now im pretty sure when i host my site remotely to production, i wont be able to store the file on that directory. Making this approach also not viable.

How do i solve this? anyone has experience on dealing with this matter? thx

problem in return function , why function is return undefined

This function most return true or false but its return undefined…

class Admin() {
  //function check if the username alredy used ,, error in return of function
  checkUserNameIsUsed(userName, tableName, proprtieName) {
    try {
      let sqlQuery = `select * from ${tableName} where ${proprtieName} = '${userName}'`;
      connectToMysql();
      connection.connect((err) => {
        if (!err) {
          connection.query(sqlQuery, (err, result) => {
            if (!err) {
              if (result.length > 0) {
                console.log("this user name is used :", userName);
                return false;
              } else {
                return true;
              }
            }
            connection.end();
          })
        } else {
          console.log(err);
          connection.end();
          return false;
        }
      })
    } catch (error) {
      console.log(error);
    }
  }
}

above in this code I ‘am try to check is the DB is already have username or not , if function found the user name it most return false and if not found it’s return true.

and in this code I check if the function return false or true but its return undefined

//check if user name is used
if (admin.checkUserNameIsUsed(adminUserName,adminTable,adminUserNameInDB)===false){
  res.status(400).send("thie user name is used please choose another username");
  return false;
}

Codemirror v6 Dynamically Add Multiple Cursors

Mobile users don’t have a CTRL key so what I’m trying to do with my project is user clicks on a button (that is dynamically created from when the editor becomes active) and it toggles a class showing if ctrlKey is active or not (which also happens to toggle a boolean in this function. Reason being is because of the clickAddsSelectionRange documentation requirements)

const jsEditor = new EditorView({
  state: EditorState.create({
    extensions: [
      basicSetup, 
      linter(esLint(new eslint.Linter(), config)),
      javascript(),
      EditorView.updateListener.of((v) => {
        if (autoupdate.checked) {
          setTimeout(() => {
            app.updatePreview(autoupdate.checked);
          }, 300);
        }
      }),
    ],
  }),
  parent: document.getElementById('jsEditor'),
  allowMultipleSelections: true,
});
activeEditor = htmlEditor;
let ctrlActive = false;

Inside the basicSetup array I call clickAddsSelectionRange.

EditorView.clickAddsSelectionRange.of(evt => ctrlActive),

The control key is toggled like so…

if (button.dataset.command === "ctrl") {
  ctrlActive = !ctrlActive; // Toggle ctrlActive variable
  button.classList.toggle('text-blue-500');
}

However the function also requires a mouse down event that I’m trying to simulate like so…

const handleTouchStart = e => {
  // Prevent default touch behavior
  e.preventDefault();
  // Simulate mouse down event
  const mouseDownEvent = new MouseEvent('mousedown', {
    bubbles: true,
    cancelable: true,
    view: window,
  });
  button.dispatchEvent(mouseDownEvent);
}
const handleTouchEnd = e => {
  // Prevent default touch behavior
  e.preventDefault();
  // Simulate mouse up event
  const mouseUpEvent = new MouseEvent('mouseup', {
    bubbles: true,
    cancelable: true,
    view: window,
  });
  button.dispatchEvent(mouseUpEvent);
  // Optionally, you can also simulate a click event if needed
  const clickEvent = new MouseEvent('click', {
    bubbles: true,
    cancelable: true,
    view: window,
  });
  button.dispatchEvent(clickEvent);
}

// Add event listeners for touch events
button.addEventListener('touchstart', handleTouchStart);
button.addEventListener('touchend', handleTouchEnd);

However I still haven’t managed to dynamically add multiple cursors using Codemirror v6 and not sure what I’m missing or doing wrong. How can I dynamically add multiple cursors to codemirror from the button class when mobile users don’t have a CTRL key to press?

Can’t click button in selenium, but can click it in regular chrome tab

I am trying to build a software solution that adds emails to my job board’s newsletter by automatically typing in an email and clicking “create alert”. When using regular google chrome, I am able to click the “create alert”, but when using selenium’s browser it doesn’t let me click the button even without automation. i’m wondering if i would have to automate the process using pure javascript. Let me share the page i am having trouble with: https://goflexboard.com/jobs/?categories[]=Manufacturing

Here I am trying to create a job alert which is a newsletter that sends recommended jobs every day. It is letting me click create alert from regular google chrome, but not from the chrome browser controlled by selenium.

I tried clicking it in regular chrome and it worked, but when i try in selenium it does not work.

Add Geocode Attribut in Firestore Document

I have this code

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

const firestore = admin.firestore();


exports.processGzipCSVMonthly = functions.runWith({ timeoutSeconds: 540 }).https.onRequest(async (req, res) => {
    try {
      
        //...
        //data is content of a CSV file
        //...
        
        const collectionRef = firestore.collection('Adresses');
        let batch = firestore.batch();
    
        data.forEach((entry) => {
            const codeInsee = entry['code_insee'];
            const nomVoie = entry['nom_voie'];
            const numero = entry['numero'];
            const lon = parseFloat(entry['lon']); 
            const lat = parseFloat(entry['lat']); 
    
            // Génération d'un ID de document aléatoire
            const docId = firestore.collection('Temp').doc().id;
    
            // Créer un objet GeoPoint avec les valeurs de lat et lon
            const geoPoint = new admin.firestore.GeoPoint(lat, lon);
    
            // Enregistrement du de la rue et de ses adresse dans le document sous la collection Adresses
            batch.set(collectionRef.doc(docId), { numero, geoPoint, codeInsee, nom_voie: nomVoie });
        });

        await batch.commit();

        res.status(200).send('Traitement terminé avec succès.');
    } catch (error) {
        console.error('Erreur lors du traitement du fichier :', error);
        res.status(500).send('Une erreur est survenue lors du traitement.');
    }
});

On execution, I have an error when creating geoPoint variable with longitud ans latitude values

 const geoPoint = new admin.firestore.GeoPoint(lat, lon);

The error say that Geopoint is not a constructor.

TypeError: admin.firestore.GeoPoint is not a constructor

I use SDK 12.0 (latest). All doc say that this method is OK. I think there is a point that I did not see …

Do you know why and can you help me ?

How can be written wp.element.createElement(‘img’ into a registerBlockType?

I am looking for a solution to this question about WordPress Blocks.
I have a plugin that create a brand new block of an img tag.
I would know how to display it in the wp.blocks.registerBlockType function.
Thanks in advice!

In the code of the js file I have put this for the result part:

save: function(props) {
return wp.element.createElement(
'img', {src: "https://api.nasa.gov/assets/img/general/apod.jpg"}
);
}

It’s not correct. WordPress display the Attempt Recovery message.
What is wrong with it?