How to read from text file and insert the data into PostgreSQL using Nodejs?

I have data in a txt file like this:-

A1085|CR01B|      |13261F001000|0000000728|      |0000000000000|      |99000|01| 

This text file contains more than 5 lakhs rows which I want to read and insert into PostgreSQL table using nodejs. These blanks spaces should also be read and saved like this empty space only.

I wrote the script like this and it is working also the data is getting inserted into table but it is taking very much time like 10 mins for 20 thousands rows only.

const readTextFile = async () => {
    const File = await fs.readFileSync('data.txt', 'utf-8');
    let arr = File.split("|");
    let modified = [];
    let temp = [];
    for (let i = 0; i < arr.length; i++) {
        if (i % 10 === 0) {
            modified.push([...temp]);
            temp = [];
            temp.push(arr[i].replace('x00rn', ''));
        } else {
            temp.push(arr[i]);
        }
    }
    console.log("modified", modified.length);
    for (let i = 0; i < modified.length; i++) {
        await insertValuesToDB(modified[i]);
    }
}

const insertValuesToDB = async (values) => {
    try {
        const text = `INSERT INTO requirement(container, module, mod_devdate, part_no, qty, tapdate, tap_qty, taptime, sup_cd, namc_id) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`;
        const result = await client.query(text, values);
        console.log("result", result);
    } catch (e) {
        console.log("ERROR", e);
    }
}

Calculate date based on provided week and day number

I want to retrieve date by providing week number and day.

E.g

Week: 1
Day: 6

This should provide me:

2023-01-05

And if I provide past day:

E.g:

Week: 1
Day: 2

This should get me next month’s date:

2023-02-02

What I have tried so far is:

var day = 6;
var date = new Date();
const dayAtDate = date.getDay()
let dayDiff = day - dayAtDate
if(dayDiff <= 0)
dayDiff = 7+dayDiff
const desiredDate = date.setDate(date.getDate() + dayDiff)
console.log(new Date(desiredDate))

But this is providing me the wrong result here.

Can anyone help me with the best possible solution for this?

count field dynamically under $bucket boundaries in mongo aggregate

I am using Mongo aggregate framework, suppose if i am having collection structure like this

[
  {
    _id: 123,
    name: "john",
    age: 30,
    fruit: "apple",
    
  },
  {
    _id: 345,
    name: "moore",
    age: 45,
    fruit: "mango",
    
  },
  {
    _id: 545,
    name: "carl",
    age: 30,
    fruit: "grape",
    
  },
  {
    _id: 96,
    name: "shelby",
    age: 25,
    fruit: "apple",
    
  },
  {
    _id: 86,
    name: "loris",
    age: 48,
    fruit: "mango",
    
  },
  {
    _id: 76,
    name: "carl",
    age: 55,
    fruit: "grape"
  }
]

I want to query and create a pipeline such that it return the count of particular fruit which lie under the duration which $bucket boudaries have created: for example result should look like this…

[
  {
    "_id": Specific_Boudary,
    "userCount": Number_Of_Users_Lie,
    "fruitsLie": [
                    {fruit_names_of_user_in_this_boundaries : fruit_counts},
                  ]
  },
  {
    "_id": 0,
    "userCount": 3,
    "fruitsLie": [
                    {apple: 2},
                    {grape: 1}
                  ]
  },
  {
    "_id": 40,
    "userCount": 2,
    "fruitsLie": [
                    {mango: 2}
                 ]
  },
  {
    "_id": "more than 50",
    "userCount": 1,
    "fruitsLie": [
                    {grape: 1}
                 ]
  }
]

so under age 30 we have 3 users, in which 2 eats apple and 1 eats grape so fruitsLie field is responsible for this calculation.

how many approaches we can have to achieve the solution for this problem with specific $bucket boudaries and please explain thoroughly each stage, I am new to aggregate and currently learning…

Google Tag Manager, How to return a class inner text if a parent tag does not have class

I have the following html code:

<li class="ais-RefinementList-item ais-RefinementList-item--selected">
 <div><label class="ais-RefinementList-label">
  <input type="checkbox" class="ais-RefinementList-checkbox" checked="" value="Software">
  <span class="ais-RefinementList-labelText">Software</span>
  <span class="ais-RefinementList-count">264</span></label></div></li

I want to do the following: if the class ais-RefinementList-item–selected” exists to not do anything and if it does not exists then to continue to extract the ais-RefinementList-labelText.

I used the following function which worked to always get the labeltText even if the click element was on the count to always get the text value for the analytics and it works fine:

function () { return {{Click Element}}.parentNode.lastChild.previousSibling.innerText }

Therefore i want to have this function run only if ais-RefinementList-item–selected” does not exist in the li as it is added when a checkbox is clicked on the website search filters.

Another thing i noticed was that when the checkbox is not clicked, checked does not appear.

checked=""

I tried doing a DOM ELEMENT trigger variable but it then stopped counting when multiple filters were checked.

Yup keeps running validators on the same property when .required() is false

I’m a bit confused about how yup is working.

I have the following schema to validate the register

export const registerValidationSchema = yup.object().shape({
    first_name: yup.string().trim().required(),
    last_name: yup.string().trim().required(),
    date_of_birth: yup.string().required().test('DOB', 'You must be at least 18 to register', value => {
        return value.setFullYear(value.getFullYear() + 18) < Date.now()
    }),
    email: yup.email().trim().required()
});

When the object to validate is the following

const data = {
    email: "[email protected]"
}

The validation will crash because value is undefined and the function value.setFullYear will fail. But why? I assume that yup will stop this line on .required() part and go to the next property.

I know the issue can be fixed by adding if(!value) return false; inside .test() but what’s the point of the required function?

From the yup documentation:

string.required(message?: string | function): Schema

The same as the mixed() schema required, except that empty strings are also considered ‘missing’ values.

mixed.required(message?: string | function): Schema

Mark the schema as required, which will not allow undefined or null as a value. Note that unless a schema is marked as nullable() a null value is treated as a type error, not a missing value. Mark a schema as mixed().nullable().required() treat null as missing.

So I read this as an undefined, null or '' value should fail on the .required() rule.

How to add hyperlink using json-as-xlsx library?

I want to export the json data into an excel data and there is one column (name = Link) and in each data there should be a clickable link . i want to set hyperlink on that link

(Library used => json-as-xlsx )

``````````````````````````````````````````````````````````````````
   
 
data = [
           {
             sheet: "Tasks",
             columns: [
             { label: "Status", value: (row) =>row.status_description==="completed"?"Pending                 Approval":"Accepted"},
            { label: "Req Date", value: (row) => moment(row.created_at).format('DD-MM-YYYY hh:mm:ss')},
             { label: "Task Name", value: (row) => row.fields.find(o=>o.label==="Task name")?.value },
             { label: "Title", value: (row) => row.name },
            { label: "Content Type", value: (row) => row.fields.find(o=>o.label==="Content type")?.value },
            { label: "Final word count", value: (row) => row.word_count },
            { label: "Link", value: (row) =>  `https://docs.google.com/document/d/${row.doc}`,type:"hyperlink"}
                                        
                                    ],
                                    content: response.items,
                                }
                            ]
let filename = `${reqData.query.project_name}-${moment().format('DD-MMM-YYYY')}`
                        let settings = {
                            fileName: filename, // Name of the resulting spreadsheet
                            extraLength: 1, // A bigger number means that columns will be wider
                            writeMode: 'writeFile', // The available parameters are 'WriteFile' and 'write'. This setting is optional. Useful in such cases https://docs.sheetjs.com/docs/solutions/output#example-remote-file
                            writeOptions: {}, // Style options from https://github.com/SheetJS/sheetjs#writing-options
                            RTL: false, // Display the columns from right-to-left (the default value is false)
                        }
        
                        let filepath = path.join(__dirname, `../../../${filename}.xlsx`);
                        
                        
        
                        let callback = function (sheet) {
                            
                            console.log("Download complete:",sheet)
                            resolve({filepath: filepath, filename: `${filename}.xlsx`});
                        }
                        
        
                        jsonAsXlsx(data, settings, callback)
                        
        
                    }).catch((err) => reject(err));

Removing all child nodes of a div with a while loop doesn’t work within event listener fucntion

So I am using the following code to remove all child nodes of a div.

    while (colorInputContainer.firstChild) {
        console.log(1);
        console.log(colorInputContainer);
        console.log(colorInputContainer.firstChild)
        colorInputContainer.removeChild(colorInputContainer.firstChild);
    }

This code in itself works inside the console. But when I use it in the full context (pastebin) it does not. And I have no idea why.

discord bot not able to ping minecraft server for information

when running the bot command in the discord server, it says unable to ping the server and I do not know how to fix it. please help (also got this from a template) Im not sure why it doesnt work or if im doing something wrong

code :

const { Client, Intents, Message} = require('discord.js');
const util = require('minecraft-server-util');
const {EmbedBuilder} = require('discord.js');
const options = {
    timeout: 1000 * 5, 
    enableSRV: true 
};
const prefix = "!mcstatus"; 
const client = new Client({
    intents: [
        "Guilds",
        "GuildMessages",
        "MessageContent"
    ]
});
client.on('ready', () => {
    console.log('bot started');
    
    client.user.setPresence({ activities: [{ name: `${server_ip}`, type: 'WATCHING' }], status: 'active' });
});
const server_ip = "mc.hypixel.net"; 
const server_port = 25565; 
client.on('messageCreate', (message) => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;
    if(message.content.startsWith(prefix)){
          util.status(server_ip, server_port, options)
    .then((result) => {
        const embed = new EmbedBuilder()
    .setColor("#FF0000")
    .setTitle("example server status")
    .setDescription(`This will show the status and info about the minecraft server n **Server ip:** ${server_ip} n **Server port:** ${server_port}`)
    .addFields(
        {name:"Server Version", value: `${result.version.name}`},
        {name:"Server Protocol Version", value:`${result.version.protocol}`},
        {name:"Players Online", value:`${result.players.online}`},
        {name:"Max Players", value:`${result.players.max}`},
        {name:"MOTD (May Not Display Accurately)", value:`${result.motd.clean}`},
        {name:"Latency", value:`${result.roundTripLatency}`},
    )
    .setTimestamp()
    message.channel.send({embeds: })
    })
    
    .catch((error) => {
    console.log(error);
    const embed = new EmbedBuilder()
    .setColor("#808080")
    .setTitle("example server status")
    .setDescription(`The server was unable to be pinged or you mis-typed the info`)
    .setTimestamp()
    message.channel.send({embeds: })
    
    })}});
client.login("token");

i have tried searching online for fixes but all of them are for older versions that no longer works

log:

PS C:UsersjasonDocumentsdiscord minecraft bot test> node .
bot started
AssertionError [ERR_ASSERTION]: Expected 'options' to be an object or undefined, got number
    at C:UsersjasonDocumentsdiscord minecraft bot testnode_modulesminecraft-server-utildiststatus.js:46:25
    at Generator.next (<anonymous>)
    at C:UsersjasonDocumentsdiscord minecraft bot testnode_modulesminecraft-server-utildiststatus.js:8:71
    at new Promise (<anonymous>)
    at __awaiter (C:UsersjasonDocumentsdiscord minecraft bot testnode_modulesminecraft-server-utildiststatus.js:4:12)
    at status (C:UsersjasonDocumentsdiscord minecraft bot testnode_modulesminecraft-server-utildiststatus.js:40:12)
    at Object.<anonymous> (C:UsersjasonDocumentsdiscord minecraft bot testnode_modulesminecraft-server-utildiststatus.js:113:17)
    at Generator.next (<anonymous>)
    at C:UsersjasonDocumentsdiscord minecraft bot testnode_modulesminecraft-server-utildiststatus.js:8:71
    at new Promise (<anonymous>) {
  generatedMessage: false,
  code: 'ERR_ASSERTION',
  actual: false,
  expected: true,
  operator: '=='
}

If i upload an image in React app , please how do i get the preview after upload?

import { useEffect, useRef } from “react”;
import {Image, Transformation} from ‘cloudinary-react’;

const UploadWidget = () => {

const widgetRef = useRef();
const cloudinaryRef = useRef();

useEffect(() => {
cloudinaryRef.current = window.cloudinary;
  widgetRef.current = cloudinaryRef.current.createUploadWidget(
    {
      cloudName: "dxgrkvzyr",
      uploadPreset: "iozcsw7d",
    },
    (error, result) => {
      if (!error && result && result.event === "success") {
        console.log("Done! Here is the image info: ", result.info);
      }
    }
  );
} , []);
<Image cloudName="demo" publicId="sample">
<Transformation crop="scale" width="200" angle="10" />
return (
   
    <button className="upload"
  onClick={() => widgetRef.current.open()}>
        Upload Image
    </button>
)

}

export default UploadWidget;

Javascript web browser based tool to extract local files from gzip (tgz)

As part of a bigger log file analysis tool that I want to write in Javascript I need to extract text files (log files) from a tgz archive that are on the local hard drive.

I have a html page with a drag n drop field which provides the file in JS. I understood there is a decompression API in modern web browsers that I can use to decompress the gzip portion. My problem is: I cannot use the pipeThrough function on a file. What is the most efficient way to do what I want to do?
Thanks

Why is my javascript code not working as expected? [duplicate]

I am expecting the code to generate values of string as “sounds/tom-1.mp3”,”sounds/tom-2.mp3″… etc. and play that audio. But the code is generating value of string as “sounds/tom-8.mp3” each time the button is clicked.

I tried commenting out the addEventListener and looked at the values of i inside and outside function fn and the code worked just fine. Problem arises only when value of i is 8
var num_of_btn = document.querySelectorAll(“.drum”).length;

code:

for(var i=0;i<num_of_btn;i++){
  var btn = document.querySelectorAll(".drum")[i];
  btn.addEventListener("click",fn);
  function fn(){
    alert("This is inside the function" + (i+1).toString());
    var string = "sounds/tom-"+(i+1).toString() + ".mp3";
    alert(string);
    var audio = new Audio(string);
    audio.play();
  }
}

Navlink not working is not working in react fi

I have created a navbar using bootstrap class but navlink is not working and no error generated in terminal
Here is my Navbar.js file

import React from "react";
import "bootstrap/dist/css/bootstrap.css"
import { NavLink } from "react-router-dom";

const Navbar = ()=>{
  return (
    <div>
      <nav className="navbar navbar-expand-lg bg-body-tertiary" >
  <div className="container-fluid">
    <NavLink className="navbar-brand" href="#">Navbar</NavLink>
    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span className="navbar-toggler-icon"></span>
    </button>
    <div className="collapse navbar-collapse" id="navbarSupportedContent">
      <ul className="navbar-nav ms-auto mb-2 mb-lg-0">
        
        <li className="nav-item">
          <NavLink className="nav-link" href="/">Home</NavLink>
        </li>
        <li className="nav-item">
          <NavLink className="nav-link" href="/about">About</NavLink>
        </li>
        <li className="nav-item">
          <NavLink className="nav-link" href="/contact">Contact</NavLink>
        </li>
        <li className="nav-item">
          <NavLink className="nav-link" href="/login">Login</NavLink>
        </li>
        <li className="nav-item">
          <NavLink className="nav-link" href="/signup">Register</NavLink>
        </li>
      </ul>
    </div>
  </div>
</nav>
    </div>
  )
}

export default Navbar;

This is App.js file code

import React from "react";
import { Route, Routes } from "react-router-dom";
import Navbar from "./components/Navbar";
import Home from "./components/Home";
import Contact from "./components/Contact";
import About from "./components/About";
import Login from "./components/Login";
import Signup from "./components/Signup";

const App = ()=>{
  return (
    <>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
        <Route path="/login" element={<Login />} />
        <Route path="/Signup" element={<Signup />} />
      </Routes>
    </>
  )
}

export default App;

and this is home.js file

import React from "react";
import { Route, Routes } from "react-router-dom";
import Navbar from "./components/Navbar";
import Home from "./components/Home";
import Contact from "./components/Contact";
import About from "./components/About";
import Login from "./components/Login";
import Signup from "./components/Signup";

const App = ()=>{
  return (
    <>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
        <Route path="/login" element={<Login />} />
        <Route path="/Signup" element={<Signup />} />
      </Routes>
    </>
  )
}

export default App;

Similar to home.js I have created contact and about.js. simple anchor tags are working on the navbar but navlink is not working.

Range across different Word.run contexts using OfficeExtension.TrackedObjects class

I am trying to use the OfficeExtension.TrackedObjects class to access a range across different contexts (documentation and similar questions set out below – although slightly outdated). The goal is to have a taskpane search list the results in the taskpane, then select the specific result in-text when clicking the listed result (using javascript).

Here is what I have:


var items = [];
function basicSearch() {
   Word.run(function (context) {
    const results = context.document.body.search("Online");
    results.load("length, text, items");
     return context.sync().then(function () {
      context.trackedObjects.add(results);
    for (let i = 0; i < results.items.length; i++) {
      let x = results.items[i].text;
      createtable("TestList", i, x, x);
      items.push(results.items[i]);
    }
     });
    return context.sync();
   });
}

function createtable(id, x, y, z) {
  var table = document.getElementById(id);
  var row = table.insertRow(-1);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);
  cell1.type = "button";
  cell1.onclick = function () { selectrange(x) };
  cell2.type = "button";
  cell2.onclick = function () { selectrange(x) };
  cell3.type = "button";
  cell3.onclick = function () { selectrange(x) };
  cell1.innerHTML = x;
  cell2.innerHTML = y;
  cell3.innerHTML = z;
}


function selectrange(x) {
  results.load("text");
  results.items[x].select();
  results.context.sync();
}

Could someone show me where I have gone wrong, or provide a full working example of how to track and call an object (or collection of objects) for use?

Resources:

https://learn.microsoft.com/en-us/javascript/api/office/officeextension.trackedobjects?view=common-js-preview&viewFallbackFrom=office-js
How can a range be used across different Word.run contexts?
Word Online Add-In: Using objects across multiple contexts
Tracked Objects throwing errors in Word Online
https://leanpub.com/buildingofficeaddins
(Building Office Add-ins using Office.js has a working example, but it is in typescript and does not use trackedObjects – I have not been able to replicate it in my add-in).

When I run the above code, it says “ReferenceError: Can’t find variable: results”. I want it to select the specific search results displayed and pressed in the list. Any assistance would be greatly appreciated.

I need to upload to Google Drive file using js or php, without the need to use command prompt

can someone help me with this? i have this code to upload to google drive folder and i got it to work. but the thing is that i need it to run without using commandpromt “node index.js”. i want it to run or work normally when i press the upload button.

`//router.js

const stream = require("stream");
const express = require("express");
const multer = require("multer");
const path = require("path");
const { google } = require("googleapis");

const uploadRouter = express.Router();
const upload = multer();

const KEYFILEPATH = path.join(__dirname, "credentials.json");
const SCOPES = ["https://www.googleapis.com/auth/drive"];

const auth = new google.auth.GoogleAuth({
  keyFile: KEYFILEPATH,
  scopes: SCOPES,
});

const uploadFile = async (fileObject) => {
  const bufferStream = new stream.PassThrough();
  bufferStream.end(fileObject.buffer);
  const { data } = await google.drive({ version: "v3", auth }).files.create({
    media: {
      mimeType: fileObject.mimeType,
      body: bufferStream,
    },
    requestBody: {
      name: fileObject.originalname,
      parents: ["xxfolder-idxx"],
    },
    fields: "id,name",
  });
  console.log(`Uploaded file ${data.name} ${data.id}`);
};

uploadRouter.post("/upload", upload.any(), async (req, res) => {
  try {
    console.log(req.body);
    console.log(req.files);
    const { body, files } = req;
 
    for (let f = 0; f < files.length; f += 1) {
      await uploadFile(files[f]);
    }
 
    console.log(body);
    res.status(200).send("Form Submitted");
  } catch (f) {
    res.send(f.message);
  }
});

module.exports = uploadRouter;` 






`//index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
  </head>

  <body>
    <form>
      <input type="file" name="Files" required multiple />
      <button type="submit">Submit</button>
    </form>
  </body>

  <script>
    const formElem = document.querySelector('form');
    formElem.addEventListener('submit', async (e) => {
        console.log("form submitted")
      e.preventDefault();
      await fetch('/upload', {
        method: 'POST',
        body: new FormData(formElem),
      });
    });
  </script>
</html>`





`index.js

const express = require('express');
const uploadRouter = require('./router');
const app = express();

app.get('/', (_, res) => {
  res.sendFile(`${__dirname}/index.html`);
});

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(uploadRouter);

app.listen(8080, () => {
  console.log('Form running on port 8080');
});`

I need this to be placed in the html/php code without the need to launch a server or use command prompt in general.