What’s the best way to leverage the event-loop for concurrent work?

I’ve been giving some thought at what could be the best way to deal with a batch of heavy operations with Javascript and I came up with the following:

const results: Promise<void>[] = [];

// Start all pieces of work concurrently
for (const record of await getData()) {
  results.push(doSomeHeavyWork(records));
}

// Collect the results
for (const result of results) {
  // Isolate the failures so one doesn't break another.
  try {
    await result;
  } catch (error) {
    console.log(JSON.stringify(error));
  }
}

My understanding is that the above snippet takes as long as the longest operation, and that’s as good as it’s going to get AFAIK. However, is there a better or more idiomatic way of going about this problem?

I’m not really looking necessarily at node here. This could be node, Deno or browser code.

Make form send email with PHP and jQuery validation – not working

I want a form to send an email where jQuery validates the form and then forwards the data to PHP which should send an email. Only validation works, but nothing else. The jQuery Form Submit script doesn’t work, as well as PHP code. I just can’t figure out what is wrong.

Of course, I know PHP can’t send an email from localhost but I’m using XAMPP for that instance. So it should also work, but the problem is in the code.

// Form Validation - WORKS

$(document).ready(function() {

  $("form").validate({

    errorPlacement: function(error, element) {
      $(element)
        .closest("form")
        .find("label[for='" + element.attr("id") + "'] > span")
        .append(error);
    },

    errorElement: "span",

    rules: {
      firstname: "required",
      lastname: "required",
      email: {
        required: true,
        email: true
      },
      subject: "required",
      msg: "required",
      checkbox: "required",
    },

    messages: {
      firstname: "*required",
      lastname: "*required",
      email: {
        required: "*required",
        email: "*invalid email address"
      },
      subject: "*required",
      msg: "*required",
      checkbox: "*required",
    },

    submitHandler: function(form) {
      form.submit();
    }
  });

});


// Form Submit - DOESN'T WORK

$('form').on('submit', function(e) {

  e.preventDefault();

  $.ajax({
    type: 'post',
    url: 'http://127.0.0.1:5500/php/base.php',
    data: $('form').serialize(),
    success: function() {
      alert('Form was submitted.');
      $('.send').addClass('send-up');
      $('.sent').addClass('sent-up');

      setTimeout(function() {
        $('.send').removeClass('send-up');
        $('.sent').removeClass('sent-up');
      }, 2000);
    }
  });

  return false;

});
.form {
  text-align: right;
  font-family: sans-serif;
  background: #000;
  color: #FFF;
  padding: 50px;
}

form {
  text-align: left;
}

form li {
  position: relative;
  margin-bottom: 55px;
  list-style-type: none;
}

.li-firstname,
.li-lastname {
  width: 44%;
  display: inline-block;
}

.li-firstname {
  margin-right: 68px;
}

input,
textarea {
  background: transparent;
  border: 0;
  outline: 0;
  border-bottom: 2px solid #FFF;
  display: block;
  color: #FFF;
  width: 100%;
  padding: 15px 0 15px 30px;
  box-sizing: border-box;
  transition: border-bottom 0.3s ease-in-out;
  resize: none;
}

.label {
  position: absolute;
  right: 0;
  margin-top: 10px;
}

form i {
  position: absolute;
  bottom: 16.5px;
  transition: color 0.3s ease-in-out;
}

.submit {
  outline: 0;
  border: 0;
  color: #FFF;
  padding: 0;
  width: 243px;
  height: 60px;
  cursor: pointer;
  position: relative;
  background: #704DFA;
  border-radius: 50px;
  text-transform: uppercase;
}

.submit span {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transition: all 0.7s ease-out;
}

.send-up {
  margin-top: -30px;
  opacity: 0;
}

.sent {
  margin-top: 30px;
  opacity: 0;
}

.sent-up {
  margin-top: 0;
  opacity: 1;
}

input:focus,
textarea:focus {
  border-bottom: 2px solid #704DFA;
}

input:focus+i,
textarea:focus+i {
  color: #704DFA;
}

span.error {
  font-family: sans-serif;
  font-style: italic;
  font-size: 13px;
  color: #704DFA;
  margin-right: 10px;
}

span.error:not(#checkbox-error) {
  float: left;
  margin-right: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://kit.fontawesome.com/a671c6b423.js" crossorigin="anonymous"></script>

<div class="form">
  <form id="form">
    <ul>
      <li class="li-firstname">
        <input type="text" name="firstname" id="firstname" required>
        <i class="far fa-user"></i>
        <label for="firstname" class="label"><span>First Name</span></label>
      </li>
      <li class="li-lastname">
        <input type="text" name="lastname" id="lastname" required>
        <label for="lastname" class="label"><span>Last Name</span></label>
      </li>
      <li class="li-email">
        <input type="email" name="email" id="email" required>
        <i class="far fa-envelope"></i>
        <label for="email" class="label"><span>Email Address</span></label>
      </li>
      <li class="li-subject">
        <input type="text" name="subject" id="subject" required>
        <i class="far fa-question-circle"></i>
        <label for="subject" class="label"><span>Subject</span></label>
      </li>
      <li class="li-message">
        <textarea name="msg" id="msg" wrap="hard" rows="5" maxlength="2000" required></textarea>
        <i class="far fa-comment-dots"></i>
        <label for="msg" class="label"><span>Job Proposal</span></label>
      </li>
      <li class="li-checkbox">
        <input type="checkbox" name="checkbox" id="checkbox" required>
        <label for="checkbox">
You want to work with me specifically because you feel my style fits perfectly to your business.
       </label>
      </li>
    </ul>
  </form>

  <button class="button submit" type="submit" form="form">
     <span class="send">Submit</span>
     <span class="sent">Sent</span>
  </button>
</div>
<?php

  $firstname = $_POST['firstname'];
  $lastname = $_POST['lastname'];
  $visitor_email = $_POST['email'];
  $visitor_subject = $_POST['subject'];
  $message = $_POST['msg'];
  $checkbox = $_POST['checkbox'];


  $email_from = '[email protected]';

  $email_subject = $visitor_subject;

    $email_body = "You have received a new message from the user $firstname $lastname.n".
                            "Here is the message:n $message".

                            
  $to = "[email protected]";

  $headers = "From: $email_from rn";

  $headers .= "Reply-To: $visitor_email rn";

  mail($to,$email_subject,$email_body,$headers);

?>

Randomly place images and move their position on hover [closed]

I need foxes to randomly spawn in a certain place in the bush. When you hover the mouse over a bush where there is a fox, the fox should hide and random spawn on other place.

let item1 = document.createElement('div');

item1.className = "item1";
item1.innerHTML = '<div class="lisa1"><img src="*https://forumstatic.ru/files/0019/3c/8c/22179.png?v=1"></div><div class="kust1"><img src="*https://forumstatic.ru/files/0019/3c/8c/35365.png?v=1"></div>';
document.body.append(item1);

let item2 = document.createElement('div');

item2.className = "item2";
item2.innerHTML = '<div class="lisa2"><img src="*https://forumstatic.ru/files/0019/3c/8c/62333.png"></div><div class="kust2"><img src="*https://forumstatic.ru/files/0019/3c/8c/67140.png"></div>';
document.body.append(item2);

let item3 = document.createElement('div');

item3.className = "item3";
item3.innerHTML = '<div class="lisa3"><img src="*https://forumstatic.ru/files/0019/3c/8c/50942.png"></div><div class="kust3"><img src="*https://forumstatic.ru/files/0019/3c/8c/56314.png"></div>';
document.body.append(item3);

Uncaught TypeError: x.attr is not a function [duplicate]

so in my HTML i got this:

<li data-target="#multi-item-example" data-slide-to="2" class="m-0 mr-2 active"></li>

my JS makes this:

var x = document.getElementsByClassName("m-0 mr-2 active");
var y= x.getAttribute("data-slide-to");
alert(y);

but I get:

Uncaught TypeError: x.getAttribute is not a function

want to get the value of data-slide-to with as little code as possible.

This works but is way too long:

var nodes=[], values=[];
for (var att, i = 0, atts = x.attributes, n = atts.length; i < n; i++){
    att = atts[i];
    nodes.push(att.nodeName);
    values.push(att.nodeValue);
}

Regarding Column Chart issues

For 10 and 1.0 in series data. The graph columns are plotting in same length..Kindly help me where I am making mistakes.. I want to correct it.. Thank you

I have written this code to generate Bar chart. Last column is displaying wrongly. How to fix that issue.

Check if string contains a character followed by digits

I have the following string that start with specific letters only, A, B, C, D, followed by digits. The example of string is always the following:

"<A12 id='something>444</A12>"

or

"<B991 id='somethingsomething'>12311</B991>"

Can anyone help me to correctly check if the string contains one of those letters followed by digits in a string?

moment.js returns invalid Date for moment (String, string)

Wants to compare the timestamp. Tried lots of ways but it is throwing an Invalid Date error. The variables startDate /endDate/testDate returns a same timestamp format in 'DD.MM.YYYY HH:MM:ss' i.e. '21.12.2021 08:29:00'

var startDate = cy.get('[data-placeholder="Select time range (from)"]').invoke('val')
var endDate = cy.get('[data-placeholder="Select time range (to)"]').invoke('val')
var testDate  = cy.get('td:nth-child(5)>span').invoke('text')

1. moment(startDate ,'DD.MM.YYYY HH:MM:ss' ).format('DD.MM.YYYY HH:MM:ss')  ///  returns Invalid Date 
2.  moment(startDate ,'DD.MM.YYYY HH:MM:ss' ).format('DD.MM.YYYY HH:MM:ss').valueOf() ///  returns Invalid Date
3. moment(startDate ,'DD.MM.YYYY HH:MM:ss' ).format()  ///  returns Invalid Date 
4. moment(startDate ,'DD.MM.YYYY HH:MM:ss' ) ///  returns Invalid Date 

Also tried using isBetween() function. But for all the conditions it is throwing result as false.

       cy.log( moment(testDate , 'DD.MM.YYYY HH:MM:ss').isBetween(
            (moment(startDate,'DD.MM.YYYY HH:MM:ss')), (moment(endDate,'DD.MM.YYYY HH:MM:ss'))
            ) )

please correct me.

How do we rearrange elements in an array so that no two adjacent elements are the same?

I want to sort the elements that are the same in the array so that they do not come one after the other.

E.G

Input*: [‘A’,’A’,’A’,’B’,’B’,’B’,’C’,C’]

Output: [‘B’,’A’,’C’,’B’,’A’,’C’,’B’,’A’]

I tried the solution here it works most of the time but not always :
https://www.geeksforgeeks.org/rearrange-numbers-in-an-array-such-that-no-two-adjacent-numbers-are-same/

E.G

Input: [‘A’, ‘A’, ‘A’, ‘A’, ‘B’, ‘B’, ‘B’, ‘B’, ‘B’, ‘B’, ‘B’, ‘B’, ‘C’, ‘C’, ‘C’, ‘C’, ‘C’, ‘C’, ‘C’, ‘C’, ‘C’, ‘C’, ‘C’]

Output: Not valid Array

How do I get it to work in all situations?

I’ve seen similar questions but couldn’t find a clear answer.

Thank you in advance for your help.

How do these two different position of return statements affect the code and why? [duplicate]

Notice the different positions of the words return. How do they actually affect the output differently?

let babyNames = []
const convertToBaby = (arr) => {
  for (let i = 0; i < arr.length; i += 1) {
    babyNames.push('baby ' + arr[i])
  }
  return babyNames
}

const animals = ['panda', 'turtle', 'giraffe', 'hippo', 'sloth', 'human'];
console.log(convertToBaby(animals))
let babyNames = []
const convertToBaby = (arr) => {
  for (let i = 0; i < arr.length; i += 1) {
    babyNames.push('baby ' + arr[i])
    return babyNames
  }
}

const animals = ['panda', 'turtle', 'giraffe', 'hippo', 'sloth', 'human'];
console.log(convertToBaby(animals))

Create an array of object with spread syntax and useState

Hi I am trying to create a very easy array of number using a loop and the spread syntax,
the goal :

    const [numbers, setNumbers] = useState([
        {numberName: 1, key: 1},
        {numberName: 2, key: 2},
        {numberName: 3, key: 3},
        {numberName: 4, key: 4},
    ])

but it dosen’t work, my loop seems to work properly but it dosent assign the value to the array.

const number = props.numberProp

const [numbers, setNumbers] = useState([])

let i = 0;
while(i < number){
    setNumbers(...numbers, {numberName: i, key: i})
    i++      
}

I looked for tutorials and videos but didn’t manage to solve my problem.

Creating a treeview of google drive folders

I want to create a JSON database of folders (only) from google drive for a tree view pane,
I have tried to extract the database using google sheets using this code

var level=0;
getFnF()

function getFnF(folder) {
  var folder= folder || DriveApp.getFolderById(" ID HERE");
  var sh=SpreadsheetApp.getActiveSheet();
  var subfolders=folder.getFolders() 
  while(subfolders.hasNext()) {
    var subfolder=subfolders.next();
    var forg=sh.getRange(sh.getLastRow() + 1,level + 1);
    forg.setValue(Utilities.formatString(subfolder.getName() + "      "+ subfolder.getId()));
    level++;
    getFnF(subfolder);
  }
  level--;
}

but i stuck on how transforming it to a database such this formate :

export const treeMenu = [
  {
    key: "Folder id",
    label: "folder1",
    nodes: [
      {
        key: "Folder id",
        label: "sub-folder",
        nodes: [
          {
            key: "Folder id",
            label: "sub-sub-folder",
            nodes: [],
          },
        ],
      },
    ],
  },
  {
    key: "Folder id",
    label: "folder",
  },
];

Javascript: Recursively remove select keys

I have a huge Javascript array (20MB).
The following code doesn’t work, I need to recursively search the big array, and delete any entrie where the array key matching an item in the removal list.

let largeArray = //Call's to API.
smallArray = clean(largeArray);
let removal = ["geocoded_waypoints", "request", "routes"];
console.log("Routes: " + smallArray);


function clean(obj) {
    // For each item in the multidomensional array.
    Object.keys(obj).forEach(key => {

        // For each item in the removal array. Check it if needs to be removed.
        let removeThis = false;
        removal.every((element) => {
            if (key === element) {
                removeThis = true;
            }
        });

        // Check if the array is a value, or an array. loop recursively as required.
        if (removeThis === false) {
            if (typeof obj[key] === 'object') {
                // Item needs to be kept, if it's an array, recurse.
                obj[key] = clean(obj[key]);
            }
        } else {
            console.log("Removing: Key: " + key + ", Value: " + obj[key]);
            delete obj[key];
        }
    });

    return obj;
}

Including file in head using PHP string replace

I am trying to include a head.php file in index.php using PHP string replace.

My Code (index.php) :

$headin = include "head.php";

$context = stream_context_create(
    array(
        "http" => array(
            "header" => "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
        )
    )
);

$homepage = file_get_contents("https://www.example.com/", false, $context);
$homepage = str_replace("<head>", "<head>". $headin, $homepage);
echo $homepage;

The problem is, the content of head.php displaying above the <html> instead of displaying inside <head>. Please help to get it fixed.

Copy to clipboard: What is the correct type?

Attempting to copy a chunk of HTML to clipboard from VSCode extension view during copy event (to be able to strip off the background theming when pasted into apps like GMail).

      /**
      Based off of: 
      * https://stackoverflow.com/a/64711198/7858768
      * https://stackoverflow.com/a/57279336/7858768
      */
      function copyToClipboard(html) {
        const container = document.createElement('div');
        container.innerHTML = html;
        container.style.position = 'fixed';
        container.style.pointerEvents = 'none';
        container.style.opacity = 0;
        
        const blob = new Blob([html], {type: "text/html"});
        const item = new ClipboardItem({"text/html": blob});
 
        navigator.clipboard.write([item]).then(function() {
          
        }, function(error) {
          console.error("Unable to write to clipboard. Error:");
          console.log(error);
        });
      }

This code works well when working with GMAIL but for some reason does not appear to allow pasting into Editors, like VSCode or Intelij.

When trying to get contents of clipboard from JS also appears not to be working.

const clipboardy = require('clipboardy');  
clipboardy.readSync();
// Gives a string with zero length.

Inspecting the contents of the clipboard with MAC OS Clipboard Shows type as unknown.

enter image description here

While normal copy event shows up as text:
enter image description here

Is there some other type that is required to be used when using navigator.clipboard.write or some other API to be used to be able to copy HTML without theming?