apkinfo is working on local but not working on aapanel

I have created a simple Post API, Where I received the name, nameSpace, image_icon, and apk_attachment from the frontend, and then inside the controller, I extract(using apkinfo module) packageName from apk_attachment and validate accordingly, from the below code you will have the idea.

HERE IS THE CONTROLLER FUNCTION:

const apkinfo = require('apkinfo');
const appData = async (req, res) => {
try {
    console.log('inside post controllers');
    const { name, nameSpace, status } = req.body;
    

   
    // Check if required fields are provided
    if (!name || !nameSpace || !req.files['apk_attachment'] || req.files['apk_attachment'].length === 0 || !req.files['icon_image']) {
        return res.status(400).json({
            success: false,
            error: 'Bad Request',
            message: 'All fields (name, namespace, apk_attachment, icon_image) are required.',
            data: null
        });
    }

    const iconImage = req.files['icon_image'] ? req.files['icon_image'][0].filename : null;
    const apkAttachment = req.files['apk_attachment'] ? req.files['apk_attachment'][0].filename : null;
    

    // Extract information from the uploaded APK file
    const apkFilePath = `uploads/${apkAttachment}`; 
    const apkInfo = await extractApkInfo(apkFilePath);
    
...rest of the code


 } catch (error) {
    console.log(error);
    if (error.name === 'SequelizeDatabaseError' && error.message.includes('Data truncated')) {
        return res.status(400).json({ 
            success: false,
            error: 'Bad Request',
            message: 'One or more fields contain invalid data. Please check your input.',
            data: null
        });
    }

    return res.status(500).json({
        success: false,
        error: error,
        message: 'An unexpected error occurred | Internal Server Error',
        data: null
    });
}

}

fucntion to extrect APK information using apkinfo

const extractApkInfo = async (apkFilePath) => {
return new Promise((resolve, reject) => {
    apkinfo.get(apkFilePath, (error, info) => {
        if(error) {
            console.error('Error in apkinfo.get:', error);
            reject(error)
        } else {
            console.log('APK Info from apkinfo.get:', info);
            resolve({
                appName: info.appName,
                packageName: info.packageName,
                versionCode: info.versionCode,
                versionName: info.versionName,
            });
        }
    });
});

};

NOTE: without apk_attachment it returns ‘All fields (name, namespace, apk_attachment, icon_image) are required.’ because of the validation but with apk_attachemt it shows the below ERROR from catch block:

{
"success": false,
"error": {
    "killed": false,
    "code": 127,
    "signal": null,
    "cmd": "/www/wwwroot/deazitech.com/updater/node_modules/apkinfo/lib/aapt_linux d badging uploads/9be87de64c55cc4276c80e5a33ee601a"
},
"message": "An unexpected error occurred | Internal Server Error",
"data": null

}

The same code on the local machine works perfectly fine.

Print a pattern in Js

If we call printPattern(n), It should print a pattern like the ones below.
(n could be any positive integer)

if n is 10, print the pattern:

1
23
4
56
7
8910

if n is 8, print the pattern:

1
23
4
56
7
8

There should be * between each elements.
n is 7, first line should just print 1, second line should print 2 and 3 and a * between them, third line should print 4, 5, 6 with ‘*’ between them and the fourth line with just 7.

(I have also added the question as an image because sometimes the question is not shown as I expect)
https://i.stack.imgur.com/9tfQy.png

I don’t even know where to start. I’ve been stuck with this.
It would be a great help if helps me with the logic.

‘ER_NOT_SUPPORTED_AUTH_MODE’ trying to connect to a SQL database (8.2.0) using node.js (v20.10.0)

My First question on stack overflow, and I must say this is a bit of a last resort. I’m trying to complete a school project where I’m making an instant messaging platform using socket.io, express.js and a MySQL database to store and retrieve messages. I run the js file like normal using node index.js and then get hit with this error:

code: ‘ER_NOT_SUPPORTED_AUTH_MODE’,
errno: 1251,
sqlMessage: ‘Client does not support authentication protocol requested by server; consider upgrading MySQL client’,
sqlState: ‘08004’,
fatal: true

Versions:
MySQL database 8.2.0
Node.js v20.10.0
MySQL workbench 8.0.0 (apparently this is the latest)
OS Windows

Here is the relevant code for the error:

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const mysql = require('mysql'); // I also tried it with mysql2 


const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234', //not the actual password 
database: 'MySQL82',
port: '3306',

});
db.connect((err) => {
if (err) throw err;
    console.log('Connected to MySQL database');
});`

Tried many different ways of fixing it such as Checking that the MySQL package version is up to date.
I also tried to update the mysql server settings

ALTER USER ‘username’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘password’;

but I was unable to do it successfully with the workbench as it would keep giving me errors and then not updating my password for some reason.

I also tried this but it didn’t work
const db = mysql.createConnection({
host: ‘localhost’,
user: ‘root’,
password: ‘1234’,
database: ‘MySQL82’,
port: ‘3306’,
authSwitchHandler: (data, callback) => {
if (data.pluginName === ‘caching_sha2_password’) {
callback(null, Buffer.from(‘YOUR_OLD_PASSWORD’));
}
},
});

This is all new stuff to me and I’m pretty much at a complete loss as every effort I make to try and solve the error just results in more issues – and there is definitely the possibility that I’m just being a bit stupid! There were other posts that had similar issues but all the answers that I saw either didn’t work for me, was posted many years ago or resulted in an error.

Why transition is not working in this code

I have a navbar and I want that when someone clicks on the button, it will be open with transition in tailwindcss.

<div className="md:hidden mt-1 mx-3">
      {/* Mobile Menu Content */}
      <ul className="font-medium p-4 bg-gray-50 border border-gray-100 rounded-lg overflow-hidden duration-300 scale-y-4 transition-all">
        <li>
          <Link
            to="/"
            className={` ${
              location.pathname === "/"
                ? "text-blue-700 font-bold"
                : "text-black font-normal"
            }`}
            onClick={() => setMobileMenuOpen(false)}
          >
            Home
          </Link>
        </li>
        <li>
          <Link
            to="/about"
            className={` ${
              location.pathname === "/about"
                ? "text-blue-700 font-bold"
                : "text-black font-normal"
            }`}
            onClick={() => setMobileMenuOpen(false)}
          >
            About
          </Link>
        </li>
        <li>
          <Link
            to="/contact"
            className={` ${
              location.pathname === "/contact"
                ? "text-blue-700 font-bold"
                : "text-black font-normal"
            }`}
            onClick={() => setMobileMenuOpen(false)}
          >
            Contact
          </Link>
        </li>
      </ul>
    </div>
  )}

I am tried but it is not working.

How to highlight specific words from an array within a paragraph?

Within a paragraph I want to highlight all words that are present within an array like …

var highlightword  = ["This", "field","need ", "examples","may"];

How would one approach a solution. The problem specific code I came up with so far does access the paragraph’s text-content, splits the string at every whitespace-sequence and wraps each word into a -tag. How does one achieve the highlighting of the array specific words?

This is what I came up with so far …

const words = $("p").text().split(/s+/);
const text = words.join("</span> <span>");

let incorrectWord = null;

$("p")
  .first()
  .html("<span> " + text + "</span>");
 p span {
  background-color: #fc0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<blockquote id="a1" contenteditable="true">
  <p>
    This domain is established to be used for illustrative examples in documents. You may use this domain in examples
    without prior coordination or asking for permission.
  </p>
</blockquote>

custom ban reason with discord.js

I’m trying to make a bot that works with only one command, the bot sends a message with two buttons, one for muting and one for banning, after selecting an option the bot updates the message with other buttons for the reasons, some of them are premade and one button is for custom reasons, after one is selected, will appear a confirmation or cancellation button
i dont undestand how to make the bot to listen to a message that the user sends after the custom reason button is clicked

i tried something with filters and collectors but i don’t understand how to arrange them correctly

Is there a way to convert MD5 calculation in Java to Postman Pre-request script?

Is there a way to convert the following Java code below to a Postman Pre-Request script?

        String payload = "{}";
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(payload.getBytes());
        byte[] digest = md.digest();
        StringBuilder hexString = new StringBuilder();
        byte[] var4 = digest;
        int var5 = digest.length;

        for(int var6 = 0; var6 < var5; var6++) {
            byte b = var4[var6];
            hexString.append(Integer.toHexString(255 & b));
        }

        System.out.println(hexString);

Value of hexString is 99914b932bd37a50b983c5e7c9ae93b

Sending request to the controller using ajax

I’m working on ASP.NET Core MVC application, I have a registration page as below, I want to return View with errors when the model state is false :

@model WebApplication2PROP.Entities.UserRegister
@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
<section id="RegSection">
    <div class="container">
        <div class="row justify-content-center align-items-center">
            <div class="col-lg-6 col-md-6 col-sm-12 justify-content-center text-start ">


                    <span asp-validation-for="FirstName" class="Validation"></span>
                    <br />
                    <label for="FirstName" class="form-label">First Name</label>
                    <input type="text" id="FirstName" class="form-control" value="@Model.FirstName" name="FirstName" />
                    <br />

                    <span asp-validation-for="LastName" class="Validation"></span>
                    <br />
                    <label for="LastName" class="form-label">Last Name</label>
                    <input type="text" id="LastName" class="form-control" value="@Model.LastName" name="LastName"/>

                    <br />

                    <span asp-validation-for="UserName" class="Validation"></span>
                    <br />
                    <label for="UserName" class="form-label">User name</label>
                    <input type="text" id="UserName" class="form-control" value="@Model.UserName" name="UserName" />

                    <br />
                    <span asp-validation-for="Phonenumber" class="Validation"></span>
                    <br />
                    <label for="PhoneNumber" class="form-label">PhoneNumber</label>
                    <input type="text" id="PhoneNumber" class="form-control" value="@Model.Phonenumber" name="Phonenumber"/>

                    <br />
                    <span asp-validation-for="Password" class="Validation"></span>
                    <br />
                    <label for="Password" class="form-label">Password</label>
                    <input type="password" id="Password" class="form-control" value="@Model.Password" name="Password" />

                    <br />
                    <span asp-validation-for="ConfirmPassword" class="Validation"></span>
                     <br />
                    <label for="ConfirmPassword" class="form-label">Confirm Password</label>
                    <input type="password" id="ConfirmPassword" class="form-control" value="@Model.ConfirmPassword" name="ConfirmPassword" />


                    <div class="text-center"> <button class="btn text-center RegBut" id="RegBut">Register</button></div>
                    <div class="text-center">
                        Already have an account? @Html.ActionLink("Login","LoginPage","Home",null,new {@class ="btn RegBut"})
                    </div>


                
                 
            </div>
            
        </div>
    </div>
</section>

controller:

[HttpPost]
        public async Task <IActionResult>  SubmitLogin([FromBody]LogIn user)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { data = false });
                }
                else
                {
                    return Ok(new { data = true });
                }
                await operations.Login(user);
                return RedirectToAction("MainPage","Home");
            }
            catch (Exception ex) 
            {
                ModelState.AddModelError(nameof(user.UserName), ex.Message);
                return View("HomePage", user);
            }
        }

Now, I want to send the data using ajax:

 $("#RegBut").click(function () {
         //   alert("clicked")
            var FirstName=$("#FirstName").val();
            var LastName = $("#LastName").val();
            var UserName = $("#UserName").val();
            var PhoneNumber = $("#PhoneNumber").val();
            var Password = $("#Password").val();
            var ConfirmPassword = $("#ConfirmPassword").val();
            var Data = { FirstName: FirstName, LastName: LastName, UserName: UserName, PhoneNumber: PhoneNumber, Password: Password, ConfirmPassword: ConfirmPassword }
            $.ajax({
                type: "POST",
                url: "/Home/SubmitRegister",
                contentType: "application/json",
                data: JSON.stringify(Data),
                success:function(data)
                {
                    if (data.success)
                    {
                     // Registration was successful, redirect to MainPage
                      window.location.href = '/Home/MainPage';
                     }
                 else 
                 {
                     // Registration failed, update UI with validation errors
                     alert("Data is not success");
                     console.log(data)
                  }
                 },
                error: function (data) 
                {
                    console.log(data);
                }

            });
        });

**
The issue is, when the user submit the data to the controller, if ModelState is false, how to redirect to the above view and make each validation error above related input field ?**

I tried to return view as below:

[HttpPost]
        public async Task <IActionResult> SubmitLogin([FromBody]LogIn user)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return View("Register",user);
                }
                else
                {
                    return Ok(new { data = true });
                }
                await operations.Login(user);
                return RedirectToAction("MainPage","Home");
            }
            catch (Exception ex) 
            {
                ModelState.AddModelError(nameof(user.UserName), ex.Message);
                return View("HomePage", user);
            }
        }

but it does not work, it returns the HTML to the ajax.

i had used event feature of java script and it worked but it become a mess so if you have any suggestions to solve it [closed]

i had used event feature of java script and it worked but it become a mess as i had to repeat the .parentElement twice which is not a good option so if you have any suggestions to solve it. or some new feature of java to get the element.enter image description here

i was trying to build a basic todo list web app and it word but got a lot messy due to which i want to make it a good and readable code.

Optimizing User Authentication Flow: Google OpenID to Notion API Integration in Chrome Extension

iam currently developing a chrome extension that involves user authentication using Google OpenID. Following the initial authentication, the user is directed to the Notion API where a second authentication step is required to grant permissions from their Notion page to my extension.

I am exploring ways to optimize this process by transmitting the information obtained during the extension’s authentication to the Notion API, facilitating automatic user authentication without the need for a second manual step.

Is there a method or best practice for securely transmitting and utilizing the authentication data from the Google OpenID process to seamlessly authenticate the user in the Notion API? I would greatly appreciate any insights, code examples, or recommended approaches to achieve a more streamlined authentication experience for the user.

Why JavaScript’s getMonth function behaves differently for dates with day equals 1?

Can someone explain why the getMonth function in JavaScript behaves differently when a date with 1st day of the month is passed as argument?

Examples:

new Date("2024-12-02").getMonth() // returns 11

new Date("2024-12-01").getMonth() // returns 10

I know that months are zero-based indexes, so it’s expected the returned number won’t match the actual month number. But I don’t understand why the first day of each month will return the previous index.

Issue copying formatted HTML text to clipboard from Developer Console

I’m facing an issue while trying to implement the functionality to copy formatted HTML text to the clipboard using JavaScript. I’ve created an interface that displays a ‘Copy as HTML’ icon when I select text, but when I click the icon, not only does it not copy anything, but the icon disappears immediately.

Here’s the code I’m using

function copyHtmlToClipboard() {
  const selectedText = window.getSelection();
  const range = selectedText.getRangeAt(0);
  const parentElement = range.commonAncestorContainer.parentElement;
  const formattedHtml = parentElement.outerHTML;

  navigator.clipboard.writeText(formattedHtml)
    .then(() => {
      console.log('HTML copiato con successo nella clipboard');
    })
    .catch((err) => {
      console.error('Errore durante la copia nell'appunti:', err);
    });
}

document.addEventListener('selectionchange', function () {
  const selectedText = window.getSelection().toString();
  const copyButton = document.getElementById('copyButton');

  if (selectedText.length > 0) {
    const range = window.getSelection().getRangeAt(0);
    const rect = range.getBoundingClientRect();
    copyButton.style.display = 'block';
    copyButton.style.left = `${rect.left}px`;
    copyButton.style.top = `${rect.top - copyButton.offsetHeight}px`;
  } else {
    copyButton.style.display = 'none';
  }
});

let copyButton = document.getElementById('copyButton');
if (!copyButton) {
  copyButton = document.createElement('div');
  copyButton.id = 'copyButton';
  copyButton.textContent = 'Copy as HTML';
  copyButton.style.position = 'fixed';
  copyButton.style.display = 'none';
  copyButton.style.cursor = 'pointer';
  copyButton.style.background = '#3498db';
  copyButton.style.color = '#fff';
  copyButton.style.padding = '10px';
  copyButton.style.borderRadius = '5px';
  copyButton.style.zIndex = '9999';

  copyButton.addEventListener('click', function () {
    copyHtmlToClipboard();
  });

  document.body.appendChild(copyButton);
}

I noticed the problem might be related to using document.execCommand('copy'), which is deprecated. I’ve modified the code using the Clipboard API, but the issue persists.
I’m testing this code directly from the developer console. Could this be a factor influencing behavior?

enter image description here

useCallBack wrapped onSelect function is causing all components that have this function as a prop to re-render

I have the following onSelect function, wrapped in useCallback…


const [descriptive, setDescriptive] = useState({})

  const handleSelectionsCall = useCallback((event, inputLabel) => {
    const { target: { value }} = event;
    var newVal = typeof value === "string" ? value.split(",") : value;
    const lastItem = newVal[newVal.length -1]
    if (lastItem === 'Unselect') newVal = []
    const update = descriptive[inputLabel];
    const updatedDescriptive = {
      ...descriptive,
      [inputLabel]: {
        ...update,
        selected: newVal,
        error: newVal.length === 0 && ["Exchange", "Industry", "Sector"].includes(inputLabel) ? "At least one selection must be made" : ""
      }
    };
    setDescriptive(updatedDescriptive);
  }, [descriptive, setDescriptive]);

I am passing it to these three drop-down check select Material UI components.

<div className={colSize}>
  <CheckSelect
    selected={descriptive.Sector.selected}
    allSelections={allSectors}
    allSelected={
      descriptive.Sector.selected.length === allSectors.length
    }
    inputLabel="Sector"
    onSelect={handleSelectionsCall}
    labelFontSize={"120%"}
    extraOutlineSpace={"fil"}
    validationWarning={descriptive.Sector.error}
    size={smallWidth ? "small" : "medium"}
  />
</div>
<div className={colSize}>
  <CheckSelect
    selected={descriptive.Industry.selected}
    allSelections={descriptive.Industry.allSelections}
    allSelected={
      descriptive.Industry.selected.length === descriptive.Industry.allSelections.length
    }
    inputLabel="Industry"
    onSelect={handleSelectionsCall}
    labelFontSize={"120%"}
    extraOutlineSpace={"fill"}
    validationWarning={descriptive.Industry.error}
    size={smallWidth ? "small" : "medium"}
  />
</div>
<div className={colSize}>
  <CheckSelect
    selected={descriptive.Exchange.selected}
    allSelections={exchanges}
    allSelected={descriptive.Exchange.selected.length === 2}
    inputLabel="Exchange"
    onSelect={handleSelectionsCall}
    labelFontSize={"120%"}
    extraOutlineSpace={"filll"}
    validationWarning={descriptive.Exchange.error}
    size={smallWidth ? "small" : "medium"}
  />
</div>

The CheckSelect components are memoized (the following is a shortened version of full component)

export default memo(function CheckSelect({
    allSelections,
    selected,
    onSelect,
    inputLabel='',
    labelFontSize,
    extraOutlineSpace='',
    validationWarning='test',
    size,
    allSelected=false
  }) {
    console.log('render ' + inputLabel)

return (
<Select
  labelId="demo-multiple-checkbox-label"
  id="demo-multiple-checkbox"
  sx={selectFieldStyles(validationWarning)}
  multiple
  value={selected}
  onChange={e => onSelect(e, inputLabel)}
  input={<OutlinedInput label={inputLabel+extraOutlineSpace} />}
  renderValue={(selected) => {
    if (allSelected) return 'Any'
    return selected.join(', ')
  }}
  MenuProps={MenuProps}
>
{map selections}
</Select>
)
})

When I change one of the selections, the other two selections re-render, even though their props are not changing. Why is this happening?

I know it has to do with the handleSelectionsCall because if I comment this out from being passed to the CheckSelect, the other CheckSelects do not re-render when another CheckSelect is updated.

Thanks!

MUI5 drawer on top of a modal Dialog

Using MUI5 I need to open a side drawer on top of a modal dialog that triggers it. Is that possible? Currently, the dialog triggers the side drawer but it opens behind this.

It seems like a modal dialog (drawer) is trying to open over an already-opened modal dialog.

how to create a date from a given string with a specific format

My problem is the following:
I have a var in javascript that represents a date in the following format in the following format ‘dd/mm/yyyy’
so, if I have 01/03/2024, this would be 1st of March, 2024

I am trying to manipulate this, my problem:
var test = "01/03/2024";
if I create avar myDate = new Date(test);
and I see what’s inside myDate it will point to the 3rd of January, 2024.
Is there any way to format the date when creating a new Date object?

I explored with moment.js but it’s erroring somewhere
I tried the following var myDate=moment(test, ‘dd/mm/yyyy’).toDate();
but it errors when trying to manipulate myDate at a later stage.