How to know if a select2 has options

I don’t need to know if you have options selected, I just need to know if you have options available. In case I have one or more options, I want to manually add another option that is “all”. And by default it is selected.

I have seen that the following is used on the internet, but I have tried it and it always gives me 1. It does not matter if there are 2 options, 1 or none.

$('#myselect option').length == 0

$('#myselect').has('option').length == 0

var menu = getElementById("select_id");
if(menu.options.length) {
    // has children
} else {
    // empty
}

$("#myselect option").length > 0

Naturally I have changed the identifier for mine.

Would someone know how to do it?

Thanks in advance

__clone method called on non-object why aim getting this error when I am trying to get user id from event

I am trying to send a notification to the enrolled users in an event a day before the event’s start date. I have a user table events table that contains the start date of each event. Also, I have an enrollment table that includes the user_id and event_id as foreign keys and the start date of these events. However, while I was trying to code the logic of this function and executing it, I got this error.

<?php

namespace AppConsoleCommands;
use AppModelsEnrollment;
use IlluminateConsoleCommand;
use AppModelsUser;
use AppModelsevent;
use IlluminateSupportFacadesDB;
use CarbonCarbon;
use IlluminateNotificationsNotifiable;
class SendNotification extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send:notification';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'send automatic notification to users that enrolled in events a day before the event date';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
      //  $users = User::all();
       // dd(count($users));

        $enrolls = Enrollment::all()->keyBy('user_id')->all();
    
       $events = DB::select('SELECT start_date , user_id FROM events , enrollments where events.id= event_id');
        
         

                foreach($events as $event) {
              
                $created = new Carbon($event->start_date);
                 $now = Carbon::now();
                 if((($created->diffInHours($now))>=24 )&& (($created->diffInHours($now))<=48)){
//$user = User::where('id', $event->user_id['user_id'])->first();
                $user = User::where('id', isset($event->user_id))->first();
             // $user = DB::select('SELECT * FROM users where id='.$event->user_id);
//dd($user);
                 $user->notify("Your deadline is in  day!"); 
                 }
            }        
        
    }
}

How to fix eslint error which Doesn’t allow for in

for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array.eslintno-restricted-syntax

The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype.eslintguard-for-in

const data = tableData.map((row, index) => {
        const rowData = [];
        let i = 0;
        const keys = Object.keys(row);
        const values = Object.values(row);
        

        for (const key in row) {
            rowData.push({
                key: headingColumns[i],
                val: row[key]
            });
            i++;
        }
        return (
            // eslint-disable-next-line react/no-array-index-key
            <tr key={index + i}>
                {rowData.map((item) => (
                    <td key={item.id} data-heading={item.key}>
                        {item.val}
                    </td>
                ))}
            </tr>
        );
    });

array.reduce and null values

I am developing a javascript-based application, therein I have an array as below:

[-12.66, 268.2, 48.99, -1264.5, 20550, 91.2, 0, 0, 0, 0, 0, 0, 0, 0, 9235.5, 1500, 0, 0, 18.99, 0, 0, null, null, null, null, null, null, null, null, null, null]

now I want to do cumulative summation of below error until it returns null value, once it has started reading null value it should return null from there or should return as it is and should not do cumulative summation from there.

I have done as below using array.reduce:

let resultArray=[];
array1.reduce(function (acc, curr, index) {  return resuleArray[index] = acc + curr }, 0); 
// here array1 is source array.

However, this returns as below

[-12.66, 255.54, 304.53, -959.97, 19590.03, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 28916.73, 30416.73, 30416.73, 30416.73, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72];

What I would like to have is like below :

[-12.66, 255.54, 304.53, -959.97, 19590.03, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 28916.73, 30416.73, 30416.73, 30416.73, 30435.72, 30435.72, null, null, null, null, null, null, null, null, null, null, null];

Please note that I will always have trailing values as null.

save json object in there provided json file using javascript/ node js

let obj={
 print:{
  us:{
  "2343192u4":{
     id:"01",
     name:"linux file",
     location:"System config"
    },
   "23438ufsdjh8":{
     id:"02",
     name:"windows file",
     location:"System config"
    },
   },
   uk:{
    "23438ufsdjh8":{
     id:"01",
     name:"windows",
     location:"System"
    },
  }
   
 },
 hardware:{
  ja:{
   "9058t05":{
     no:"ct-01",
     refrence:"down-tPO-01"
    }
  }
 }
};


let Array=[{
  filepath:"print"
 },
 {
  filepath:"hardware"
 },
 {
  filepath:"stack"
 },
 {
  filepath:"backupdir"
 },
];

let cont = {
  "45434dsdfsfv": {
    name: "us",
  },
  "4wer23434": {
    name: "uk",
  },
  "6vfkn23421": {
    name: "ja",
  },
  "9dnfjkn23e": {
    name: "ru",
  },
};


Object.values(cont).map((i) =>{
for (const [key, values] of Object.entries(obj)) {
            for (const [localeKey, localeValues] of Object.entries(values)) {
              console.log(localeValues);
             // fs.writeFile(path.join(__dirname,file.filepath,`${i.name}.json`), JSON.stringify(localeValues, null, 4)
            }
          }
});

I am trying to fetch key from the obj JSON object and compare it with the Array filepath so I can push the value in created json file

here by using fs I am trying to create folder which I got from the array

fs.writeFile(path.join(__dirname,file.filepath,`${cont.name}.json`));

by which I created folder and file with the name which are present inside the cont json
and trying to put like this

print/us.json

{
   "2343192u4":{
     id:"01",
     name:"linux file",
     location:"System config"
    },
   "23438ufsdjh8":{
     id:"02",
     name:"windows file",
     location:"System config"
   }
 }

print/uk.json

{
  "23438ufsdjh8":{
     id:"01",
     name:"windows",
     location:"System"
    },
}

hardware/ja.json

{
  "9058t05":{
     no:"ct-01",
     refrence:"down-tPO-01"
    }
}

and so on …

but the problem is when I do this I am not able to save data in there respective json file
I am getting same output in every json file

print/us.json

{
   "2343192u4":{
     id:"01",
     name:"linux file",
     location:"System config"
    },
   "23438ufsdjh8":{
     id:"02",
     name:"windows file",
     location:"System config"
   }
 }

print/uk.json

{
   "2343192u4":{
     id:"01",
     name:"linux file",
     location:"System config"
    },
   "23438ufsdjh8":{
     id:"02",
     name:"windows file",
     location:"System config"
   }
 }

and so on …

here print hardware stack backupdir always get changed and there are multiple more files as this is system random generated name that why I have to compare and the key from object and make a directory of this name

how can I push them in different different folder with there respective value

Tracking traffic sent to clients

I have a new directory website with Google Analytics 4.

I am trying to record website_click events when someone clicks a link that takes them to the external website. This is to understand and report on how much traffic I am sending to these clients.

Unfortunately, I can’t see the event being recorded. I have tried installing and using Google Analytics Debugger but I see no new output in my Console.

Here is the code I am using

 <head>
<script async src="https://www.googletagmanager.com/gtag/js?id=G-HIDDENTAG"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-HIDDENTAG');
</script>
 <script>
    $( document ).ready(function(event) {
      $( ".link_to_provider" ).click(function(event) {
        event.preventDefault();
        setTimeout(visitProvider, 1000);
        var visited = false;

        function visitProvider() {
          if (!visited) {
            visited = true;
            window.open('{{ $company->website }}');
          }
        }

        // Sends the event to Google Analytics and
        // resubmits the form once the hit is done.
        ga('send', {
          hitType: 'event',
          eventCategory: 'provider',
          eventAction: 'website_visit',
          eventLabel: '{{ $company->id }}',
          hitCallback: visitProvider
        });
      });
    });
  </script>
  </head>
  <body>
  ....
                          <a href="https://www.example.com" rel="nofollow" class="link_to_provider"><button class="btn btn-primary px-4 mb-1 mt-0">Visit Website</button></a>
.....
  </body>

Thanks for the help.

How to open pdf in a popup in php

Basically I am using BSK PDF Manager Plugin in WordPress and want to open the the pdfs in a popup when someone click them.

 
 /* This is the href code of the plugin and what I tried to open 
 
$pdf_title_str = '<a href="'.esc_url($file_url).'"'.esc_attr($open_target_str.$nofollow_tag_str).'  title="'.esc_attr($pdf_item_obj_title).'" class="bsk-pdfm-pdf-link-for-title pdf-id-'.esc_attr($pdf_item_obj->id).'">'.$pdf_title_str.'</a>';

how to wait for the request to be sent and then send a new request?

i have a problem. im creating a chat app with react and react redux and im using supabase library for sending request to my supabase database. now for sending users entered message, i have a problem. when user enters ten messages together at the same time, those ten messages wont be sent to the database correctly and maybe the last message will be sent correctly. now to fix this problem, i want to implement this: if user enter his/her message, if an other request is sending at the same time, wait for that request to be sent. when that request is sent, send the new request. so when user enter 10 messages for example, the messages will be sent to the database one by one. each request wait for the sending request and when that request is sent to database successfully or it got an error, then send the next pending request. i tried to implement this but i couldnt. because the function that is sending the users message to the database is an event handler and i dont know how to wait for the sending request thre. here is that functions codes:

      //a function to store users message in database 
  const sendMessageHandler = async (e) => {
    e.preventDefault();
    
    //here i want to check if an other request is sending, wait for that request to be sent and 
    then send the new request.
     
    //create an object with users message infos
    const userMessage = {
      from: username,
      text: messageRef.current.value,
      time: `${new Date().getHours()}:${new Date().getMinutes()}`,
    };

    //create an id with the value of current chats length
    const id = chats[currentIndex].chats.length;

    //store the users message in sending messages state
    dispatch(
      chatsActions.addSendingChat({
        ...userMessage,
        id,
        name: chats[currentIndex].name,
      })
    );

    //create the current messages object to update the group row
    let currentChats = {
      name: chats[currentIndex].name,
      users: chats[currentIndex].users,
      onlines: chats[currentIndex].onlines,
      chats: chats[currentIndex].chats,
      unreads: chats[currentIndex].unreads,
    };

    //add users message to current chats
    currentChats.chats = [...currentChats.chats, userMessage];

    //update the chats of the selected group with the new values
    const { error } = await supabase 
      .from("chats")
      .update(currentChats)
      .eq("id", apiChatId);

    //after updating the row, delete the users message that was in sending messages state from there 
    dispatch(chatsActions.removeSendingChat(id));
  };

thanks for your help.

React Testing Library is ignoring media query in styled component

I have a button component that is hidden on <768px and displayed on >768px

import { styled } from '@mui/material/styles';
import Button from '@mui/material/Button';

interface TestButtonProps {
  buttonLabel: string;
}

const MyButton = styled(Button)(
  ({theme: {breakpoints} }) => ({
    display: 'none',

   [breakpoints.up('md')]: {
     display: 'block',
    }
  })
)

const TestButton = ({
  buttonLabel
  } : TestButtonProps) => {
    return (
      <div>
        <MyButton>
          {buttonLabel}
        </MyButton>
      </div>
    )
  }
  export default TestButton;

I’m trying to use React Testing Library to test that this component is displayed on >768px (so that I can later add a fireEvent test)

import { render, screen } from '@testing-library/react';
import TestButton from './test-button';

const mandatoryProps = {
  buttonLabel: 'Button Label',
};

describe('MyBupaHelpDrawer', () => {
  it('it should render the button above md screensize', () => {
  render(<TestButton {...mandatoryProps} />);
    screen.getByRole('button', { name: 'Button Label'}); 
  });
});

However, the test is failing.

TestingLibraryElementError: Unable to find an accessible element with the role “button” and name “Button Label”

Seems that the styling first rule “display: none” is picked up but the media query rule is not.

How can I modify my test to pick up the media query?

Should I be approaching this in a different way?

I want to change text from table to a link

I wanted to change the value of attachment in the table to a clickable link because the links are very long, i got the link from Firebase firestore and i wanted to change it to a clickable link

this is the JavaScript file

var attendantNumber = 0;
var tbody = document.getElementById('tbody1');

function AddItemToTable(fname, lname, email, phoneNumber, country, attachment){

    let trow = document.createElement('tr');
    let td1 = document.createElement('td');
    let td2 = document.createElement('td');
    let td3 = document.createElement('td');
    let td4 = document.createElement('td');
    let td5 = document.createElement('td');
    let td6 = document.createElement('td');
    let td7 = document.createElement('td');

    td1.innerHTML = ++attendantNumber;
    td2.innerHTML = fname;
    td3.innerHTML = lname;
    td4.innerHTML = email;
    td5.innerHTML = phoneNumber;
    td6.innerHTML = country;
    td7.innerHTML = attachment;

    trow.appendChild(td1);
    trow.appendChild(td2);
    trow.appendChild(td3);
    trow.appendChild(td4);
    trow.appendChild(td5);
    trow.appendChild(td6);
    trow.appendChild(td7);
    tbody.appendChild(trow);
}

function AddAllItemsToTable(TheAttendant) {
    attendantNumber = 0;
    tbody.innerHTML = "";
    TheAttendant.forEach(element => {
        AddItemToTable(element.FirstName, element.LastName, element.Email, element.PhoneNumber, element.Country, element.attachment);
    });  
}


async function GetAllData() {
    const querySnapshot = await getDocs(collection(db, "attendants"));
    var attendants = [];
    querySnapshot.forEach(doc => {
        attendants.push(doc.data());
    });

    AddAllItemsToTable(attendants);
}

window.onload = GetAllData;

HTML canvas not producing image from web cam

I want to capture image every time socket.on(‘takePic’) gets triggered. It works fine for the first time. but when the socket.on(‘takePic’) gets triggered second time,the canvas div is just blank and so the ima tag.
I have copied the takePicture() function from somewhere and added the setInterval() and localstream variable to stop camera.
how can I fix this?

here is my js code.

const socket = io('http://localhost:3001');


const params = new Proxy(new URLSearchParams(window.location.search), {
    get: (searchParams, prop) => searchParams.get(prop),
  });
  let roomId = params.roomId; 

socket.emit('joinRoom',roomId);





var takePicture = function () {
    // The width and height of the captured photo. We will set the
    // width to the value defined here, but the height will be
    // calculated based on the aspect ratio of the input stream.
    var width = 320;    // We will scale the photo width to this
    var height = 0;     // This will be computed based on the input stream
    
    // |streaming| indicates whether or not we're currently streaming
    // video from the camera. Obviously, we start at false.
  
    var streaming = false;
    var localstream;
    // The various HTML elements we need to configure or control. These
    // will be set by the startup() function.
  
    var video = null;
    var canvas = null;
    var photo = null;
    var startbutton = null;
  
    function showViewLiveResultButton() {
      if (window.self !== window.top) {
        // Ensure that if our document is in a frame, we get the user
        // to first open it in its own tab or window. Otherwise, it
        // won't be able to request permission for camera access.
        document.querySelector(".contentarea").remove();
        const button = document.createElement("button");
        button.textContent = "View live result of the example code above";
        document.body.append(button);
        button.addEventListener('click', () => window.open(location.href));
        return true;
      }
      return false;
    }
  
    function startup() {
      if (showViewLiveResultButton()) { return; }
      video = document.getElementById('video');
      canvas = document.getElementById('canvas');
      photo = document.getElementById('photo');
      startbutton = document.getElementById('startbutton');
  
    navigator.mediaDevices.getUserMedia({video: true, audio: false})
      .then(function(stream) {
        video.srcObject = stream;
        localstream = stream;
        video.play();
      })
      .catch(function(err) {
        console.log("An error occurred: " + err);
      });
  
      video.addEventListener('canplay', function(ev){
         
        if (!streaming) {
         
          height = video.videoHeight / (video.videoWidth/width);
        
          // Firefox currently has a bug where the height can't be read from
          // the video, so we will make assumptions if this happens.
        
          if (isNaN(height)) {
            height = width / (4/3);
          }
        
          video.setAttribute('width', width);
          video.setAttribute('height', height);
          canvas.setAttribute('width', width);
          canvas.setAttribute('height', height);
          streaming = true;
        }
      }, false);
  
      startbutton.addEventListener('click', function(ev){
        takepicture();
        ev.preventDefault();
    
        clearInterval(attendanceInterval);

        $('#heading').css('display','none')
    
        video.pause();
        video.src = "";
        localstream.getTracks()[0].stop();
        
      }, false);
      
      clearphoto();
    }
  
    // Fill the photo with an indication that none has been
    // captured.
  
    function clearphoto() {
      var context = canvas.getContext('2d');
      context.fillStyle = "#AAA";
      context.fillRect(0, 0, canvas.width, canvas.height);
  
      var data = canvas.toDataURL('image/png');
      photo.setAttribute('src', data);
    }
    
    // Capture a photo by fetching the current contents of the video
    // and drawing it into a canvas, then converting that to a PNG
    // format data URL. By drawing it on an offscreen canvas and then
    // drawing that to the screen, we can change its size and/or apply
    // other changes before drawing it.
  
    function takepicture() {
      var context = canvas.getContext('2d');
      if (width && height) {
        canvas.width = width;
        canvas.height = height;
        context.drawImage(video, 0, 0, width, height);
      
        var data = canvas.toDataURL('image/png');
        photo.setAttribute('src', data);
      } else {
        clearphoto();
      }
    }
  
    // Set up our event listener to run the startup process
    // once loading is complete.
   startup();
    var i = 10;
   let attendanceInterval = setInterval(()=>{
      i -= 1;
      $('#heading').html(`taking picture in ${i}`);
      if(i==0){
        $('#startbutton').click()
      }
    }, 1000)


  }

  socket.on('takePic',()=>{
    takePicture()
})

and this is the html code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>StudentVideo</title>
    <link rel="stylesheet" href="css/studentVideo.css">
</head>
<body>
    <div class="contentarea">
        <h1 id="heading">
          
        </h1>
        <p>
         This example demonstrates how to set up a media stream using your built-in webcam, fetch an image from that stream, and create a PNG using that image.
        </p>
        <div class="camera">
          <video id="video" width="320" height="240">Video stream not available.</video>
          <button id="startbutton">Take photo</button> 
        </div>
        <canvas id="canvas" width="320" height="240">
        </canvas>
        <div class="output">
          <img id="photo" alt="The screen capture will appear in this box." src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAAAXNSR0IArs4c6QAABGlJREFUeF7t1AEJADAMA8HVv5Oa3GAuHq4KwqVkdvceR4AAgYDAGKxASyISIPAFDJZHIEAgI2C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lUJSoCAwfIDBAhkBAxWpipBCRAwWH6AAIGMgMHKVCUoAQIGyw8QIJARMFiZqgQlQMBg+QECBDICBitTlaAECBgsP0CAQEbAYGWqEpQAAYPlBwgQyAgYrExVghIgYLD8AAECGQGDlalKUAIEDJYfIEAgI2CwMlUJSoCAwfIDBAhkBAxWpipBCRAwWH6AAIGMgMHKVCUoAQIGyw8QIJARMFiZqgQlQMBg+QECBDICBitTlaAECBgsP0CAQEbAYGWqEpQAAYPlBwgQyAgYrExVghIgYLD8AAECGQGDlalKUAIEDJYfIEAgI2CwMlUJSoCAwfIDBAhkBAxWpipBCRB46/vA5AUJNVYAAAAASUVORK5CYII="> 
        </div>
        <p>
          Visit our article <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Taking_still_photos"> Taking still photos with WebRTC</a> to learn more about the technologies used here.
        </p>
      </div>

</body>
<script src="https://cdn.socket.io/socket.io-3.0.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="js/video.js"></script>
</html>