Sorting elements after push in aggregation pipeline of mongodb

I have a series of documents in MongoDB that look like this:

{
    "_id" : ObjectId("63ceb466db8c0f5500ea0aaa"),
    "Partner_ID" : "662347848",
    "EarningsData" : [ 
        {
            "From_Date" : ISODate("2022-01-10T18:30:00.000Z"),
            "Scheme_Name" : "CUSTOMERWINBACKJCA01",
            "Net_Amount" : 256,
        }, 
        {
        "From_Date" : ISODate("2022-02-10T18:30:00.000Z"),
            "Scheme_Name" : "CUSTOMERWINBACKJCA01",
            "Net_Amount" : 285,
        }
    ],
    "createdAt" : ISODate("2023-01-23T16:23:02.440Z")
}

Now, what I need to do is to get the date of “Net_Amount” payment per month per “Scheme_Name”. This date and month will be from the field “From_Date”. Now, there could be multiple dates in a particular month on which the payment has been made for a scheme. We just need to get the latest date.

I have tried below query for the aggregation operation in mongo and I am getting the desired results but the problem is that I need to sort the Date array so that I can get the last date of the payment.

var projectQry = [
        {
          $match: {
            "Partner_ID": userId
          }
        },
        {
          $unwind: "$EarningsData"
        },
        {
          $group: {
            _id: {
              Scheme_Name: "$EarningsData.Scheme_Name",
              Month: {
                $month: "$EarningsData.From_Date"
              }
            },
            Day: { 
              "$push": {
                "$dayOfMonth": "$EarningsData.From_Date" 
              }
            },
          }
        },
        {
          $project: {
            _id: 0,
            Scheme_Name: "$_id.Scheme_Name",
            Month: "$_id.Month",
            Day: 1
          }
        }
      ];

How to change color or customize header arrow for expandableRow in Mui Datatable

I have a MUI data table with the expandable rows Option. I have also enabled the ExpandAll button on the header row which displays an arrow in the title row which is similar to the arrows in all the rows. This gets confusing for the user. SO i want to change the header arrow to a different color by overriding its properties or adding some text below it. However I am not able to find any documentation to change its properties. What do i do?

   options={{
                download: false,
                expandableRows: true,
                expandableRowsOnClick: true,

                renderExpandableRow: (rowData, rowMeta) => {}
}}

The arrow that I want to change is highlighted in the image.

Image

When internet connection lost, MVC page(view) returns “the page can not be displayed”

My page gets data from db and when internet connection lost, the page return “the page can not be displayed”. The point is, page is used on a monitor without control panel. So, page must get datas automatic.

The script that i used for refreshing page:

<meta http-equiv="refresh" content="@ViewBag.AndonRefreshSec" />

But it can’t provide that i want. How can i solve the problem?

What is the use of dispatchEvent() in WebSocket?

I notice WebSocket extends EventTarget and EventTarget.dispatchEvent()sends an Event to the object“. But it is not clear from that MDN document who the object is.

I had thought maybe that object was the receiver on the WebSocket server side and dispatchEvent() is another way to send a message to the ws server like WebSocket.send()

So I did the following test in the browser console, using https://github.com/websockets/ws for ws server.

const ws = new WebSocket('ws://localhost:3000');

//instead of using ws.send('hello world'); I use dispatchEvent here

ws.addEventListener('open', (evt) => {
      let event = new MessageEvent('message', {
          data: "hello world",
          lastEventId: '101'
       });
  ws.dispatchEvent(event);
});

ws.addEventListener('message', (event) => {
    console.log('Message from server ', event.data);
});

But as it turns out the console immediately prints out “Message from server hello world” while ws server didn’t get that event.

So what is the use of dispatchEvent() in WebSocket ?

how to play gif whenever button is clicked in javascript modal

i have a modal in javascript, when user clicks the modal button, the modal opens with a gif:

var modal = document.getElementById("myModals");


var btn = document.getElementById("myBtns");


var span = document.getElementsByClassName("closes")[0];

btn.onclick = function() {
  modal.style.display = "block";

}


span.onclick = function() {
  modal.style.display = "none";
}

modal.onclick = function() {
  modal.style.display = "none";
}


window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
<a href="#" id="myBtns"></a>

<div id="myModals" class="modals">

  <!-- Modal content -->
  <div class="modal-contents">
    <img src="sample.gif" style="margin-top:-25%;margin-left:20%;width:60%">
    <span class="closes">&times;</span>
  </div>

</div>

so the issue here is the gif is played the first time, when user closes it and clicks button again the gif is displayed as it is without playing, can anyone please tell me what is wrong in here, thanks in advance

Using data-* to get the values of html tag

For example, i have this below code

  <ul data-country="A">
      <li data-province="1">USA</li>
      <li data-province="2">LA</li>
  </ul>
  <ul data-country="B">
      <li data-province="3">NY</li> 
  </ul>

How can i use javascript to get the value USA by using the data-attributes.

For example, by calling function getValue(‘A’,’1′) , i will get the return value of USA.

Failed to load the js file component in console[Magento 2]

I am trying to show current time with running seconds on a page under adminhtml. I wrote the code for js in Namespace_Module/view/adminhtml/web/js/timejs.js And the code is

define(
['jquery', 'uiComponent', 'ko']
,function ($, Component, ko) {
    'use strict';
        return Component.extend({
      defaults: {
        template: 'Pixelnet_Blog/time'
      },

      initialize: function () {
            this._super();
            this.currentTime();
        },


      currentTime: ko.computed(function () {
        setInterval(function(){
          var currentTime = new Date().toLocaleTimeString();
          // console.log(currentTime);
        }, 1000);
        return currentTime;
      })
    });
}
);

To render the js function I created a PHTML in the place of Namespace_Module/view/adminhtml/templates/js_time.phtml and the code is

<div id="time_show" data-bind="scope:'time_show'">
<!-- ko template: getTemplate() --><!-- /ko -->
<script type="text/x-magento-init">
{
    "*": {
        "Magento_Ui/js/core/app": {
            "components": {
                "time_show": {
                    "component": "Pixelnet_Blog/js/timejs"
                }
            }
        }
    }
}
</script>
</div>

I called the template in the phtml and put the template in the position of Namespace_Module/view/adminhtml/web/template/time.html. And HTML code is

<div>
    <h4>Current Time is:</h4><span id="time_show" data-bind="text: currentTime()"></span>
</div>

lastly, I put a require js file in the location of Namespace_Module/view/adminhtml/requirejs-config.js and the code snippet is

var config = {
    map: {
        '*': {
            timejs: 'Pixelnet_Blog/js/timejs'
        }
    }
};

But when I render the page it does not show the time with running seconds. In console, it shows an error named Failed to load the “Pixelnet_Blog/js/timejs” component. I cannot figure out the problem.

Javascript that works outside an Alpine.js template doesn’t work inside it

I have a page that uses Alpine.js for dynamically creating and removing blocks of content with form elements in them.

Part of the block is two sets of radio buttons. At the moment, people can select options from both groups, but I want to change it so that if they select an option from one group, it unchecks the value from the other and vice versa.

At the moment, what I have is:

const shirtSizes = document.querySelectorAll('.shirt-sizes'); // scope only to the parent

shirtSizes.forEach((player) => {
  const kidsRadios   = player.querySelectorAll('.size-kids');
  const adultsRadios = player.querySelectorAll('.size-adults');

  kidsRadios.forEach((kid) => {
    kid.addEventListener('change', (event) => {
      adultsRadios.forEach((adult) => {
        adult.checked = false;
      });
    });
  });

  adultsRadios.forEach((adult) => {
    adult.addEventListener('change', (event) => {
      kidsRadios.forEach((kid) => {
        kid.checked = false;
      });
    });
  });

});

(That could probably be written better but that’s not the problem at the moment.)

I have a CodePen that shows that working fine.

But my actual project is constructed like this:

<div x-data="addPlayers()" x-init="addNewPlayer">
  <div class="mb-8">
    <template x-for="(field, index) in fields" :key="index">
      <input
        x-model="field.kids"
        type="radio"
        :name="`size_kids_${index + 1}`"
        :id="`size-kids-8_${index + 1}`"
        value="8"
      >
      …
    </template>
  </div>
  <button type="button" @click="addNewPlayer()">Add player</button>
</div>

<script>
  function addPlayers() {
    return {
      fields: [],
      addNewPlayer() {
        this.fields.push({
          kids: '',
          adults: ''
        });
        calcTotal(count);
        count++;
      },
      removePlayer(index) {
        this.fields.splice(index, 1);
        count = index;
        calcTotal(count);
      }
    }
  }
</script>

I’ve created another CodePen which might illustrate better how it’s all put together and you can see in this one that the same js for resetting the radios doesn’t work.

So why doesn’t it work in the Alpine version? And what do I need to do to get it to work?

not able to make multiple work group working and causing freeze

I am doing create multiple worker threads, in my case, i am trying to create 2:

This is my code to create work thread

function createWorker(data1, data2) {
  return new Promise((resolve) => {
    let worker = new Worker();
    worker.postMessage(data1, data2);
    worker.onmessage = (event) => {
      postMessageRes = event.data;
      if (postMessageRes == 200) {
        // loadCOPC();
      } else {
        workerCount += 1;
        let position = postMessageRes[0];
        let color = postMessageRes[1];
        for (let i = 0; i < position.length; i++) {
          positions.push(position[i]);
          colors.push(colors[i]);
        }
        resolve(true);
      }
    };
  });
}

and using it in my loop

 for (let m = 0; m < keyCountMap.length; ) {
    let remaining = totalNodes - doneCount;
    let numbWorker = Math.min(chunk, remaining);
    for (let i = 0; i < numbWorker; i++) {
      promises.push(createWorker([keyCountMap[m], keyCountMap[m + 1]]));
      m += 2;
    }
    Promise.all(promises).then((response) => {
      console.log("one chunk finishes");
    });
  }

The code works fine if i instead of all these use one static work thread and call postMessage in the loop for only one but not while i am trying to make chunk like here in the code.

When i run the code, my browser freeze

Trigger Form Submission from inside React useEffect hook?

In my React component, I need to listen for a value to change then trigger a form to be submitted.

Currently I’m using a useEffect hook to listen for changes to a state variable mediaBlob,

import { useEffect, useState } from "react";

export function Foo({
  handleSubmit,
  ...props
}) {

  let { mediaBlob, setMediaBlob } = useState(null)

  useEffect(() => {
    if (mediaBlob) {
      // how to trigger the form submission here?
      // Cant call the form's handleSubmit() method without an event
    }
  }, [mediaBlob]);

but I cant call the form’s handleSubmit function because the function needs to accept an event object e.

async function handleSubmit(e) {
  e.preventDefault()
  // ...
}


return (
  <form onSubmit={handleSubmit}>
    <Foo handleSubmit={handleSubmit} />
  </form>
)

Is it still possible to trigger the form submission from within the useEffect hook?

How to prevent from slack connection error?( We had some trouble connecting. Try again?)

I’m working on a Slack bot. I’m using a model to get data from the user and using two functions (lambdas) to schedule events based on the data provided by the user, however every time I hit the submit button for the model, I get the following error: “We had some problems connecting.” Try again? ), and I believe this is happening because two lambda functions are being called simultaneously, causing the computing to take longer than 3 seconds to complete. Since calling both lambda functions simultaneously is necessary, how can I do this without encountering any errors?
I’m using javascript.

if (isPermission) {
    let privacy = setPrivacy(employee_id, bdDate, orgId, anniDate, DOB, BYear, token);
    let invokeAnni = Invoke(employee_id, orgId, Empinfo[0].Employee.firstName, action1, anniDate, Local, payloadData.user.id);
    let a =  Invoking(employee_id, orgId, bdDate, Empinfo[0].Employee.firstName, action, Local, payloadData.user.id);
    let update = botreply(payloadData.user.id);
    flag = 0;
    await privacy;
    await invokeAnni;
    await a;
    await update;
    return {
        statusCode:200
    }

}
else {
    let privacy = setPrivacy(employee_id, bdDate, orgId, anniDate, DOB, BYear, token);
    flag = 0;
    await privacy;
    return {
        statusCode:200
    }

}

invoke and invoking are two lambda function which i’m calling simultaneously.

JSDoc: how to document a returned object function which must be invoked first

I have following function:

function carModel() {
    return {
        brand: "NIO",
        model: "ET5"
    }
}

I need documenting a returned carModel() in another function:

/**
 * @returns {carModel}
 */
function another() {
    //some unpredictable code but returned as invoked carModel()
}

But I can’t using another function by JSDoc as expected, need extra ().
Must call like this to work by JSDoc:

another()().brand

I need call another function by JSDoc like this:

another().brand

How to check if the directory is not empty and contains and image in React using custom hooks

I’m working on a custom hook for checking directories of specific markets and I want to check if there’s an existing image inside. If there is then import the image if not then return a default. This is my code so far without returning the default image.

import { useState, useEffect } from 'react';
import { brand, country } from '../resources';
    
const useImgFromDir = (fileName: string) => {
  const [image, setImage] = useState<string>('');

  useEffect(() => {
    const importFile = async () => {
      try {
        const image = await import(`../dir/images/${brand}/${country}/${fileName}.png`);
        // I'm not sure how to use the condition here
        // For now the code is working on not empty directory
        setImage(image.default);
      } catch {
        setImage('');
      }
    };

    importFile();
  }, [brand, country, fileName]);

  return image ?? '';
};

export default useImgFromDir;