Validation with alpine.js

In my form, I am trying to implement validation for checkboxes using Alpine.js.
When I fill out the form correctly (when the validation passes without displaying any error messages), the result of $request->all() returns an array containing values of 1 for checked fields and 0 for unchecked ones:

"myown" => "0"
"manager" => "1"
"supervisor" => "1"
"planningoutbound" => "0"

However, when the checkbox validation is triggered—meaning, for example, the ‘myown’ checkbox is checked along with another checkbox or none of the checkboxes are checked—it displays an error (indicating that the validation works correctly). The problem arises when I then re-check the checkboxes correctly and submit the form; the values for the checked checkboxes turn into null, while the unchecked fields still return a value of 0.

"myown" => "0"
"manager" => null
"supervisor" => null
planningoutbound" => "0"

a snippet of my form code:

<div x-data="addTask" class="dark:text-white-dark/70 text-base font-medium text-[#1f2937]">
    <form action="{{ route('action.list.store') }}" method="post" x-ref="myForm" @submit.prevent="submitFormAddNewTask()">
        @csrf
        <div class="mb-3">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
            
        <div class="mb-3">
            <h5>Task for</h5>
            @php
                $grupsChunks = $userGroups->chunk(4);
            @endphp
            <div class="flex flex-row">
                @foreach ($grupsChunks[0] as $group )
                <div class="mr-5">
                    <input type="hidden" name="{{ $group->name }}" value="0" :value="selectedCheckboxes.{{ $group->name }} ? 1 : 0" />
                    <input type="checkbox" name="{{ $group->name }}" class="form-checkbox text-success peer" id="{{ $group->name }}" x-model="selectedCheckboxes.{{ $group->name }}" value="1"  @change="selectedCheckboxes.{{ $group->name }} = $event.target.checked ? 1 : 0"/>
                    <label class="text-sm peer-checked:text-success" for="{{ $group->name }}">{{ ucfirst($group->name) }}</label>
                </div>
                @endforeach
            </div>
            @isset($grupsChunks[1])
            <div class="flex flex-row">
                @foreach ($grupsChunks[1] as $group )
                <div class="mr-5">
                    <input type="hidden" name="{{ $group->name }}" value="0" :value="selectedCheckboxes.{{ $group->name }} ? 1 : 0" />
                    <input type="checkbox" name="{{ $group->name }}"  class="form-checkbox text-success peer" id="{{ $group->name }}" x-model="selectedCheckboxes.{{ $group->name }}" value="1" @change="selectedCheckboxes.{{ $group->name }} = $event.target.checked ? 1 : 0"/>
                    <label class="text-sm peer-checked:text-success" for="{{ $group->name }}">{{ ucfirst($group->name) }}</label>
                </div>
                @endforeach
            </div>
            @endisset
            <template x-if="isSubmitForm1">
                <p class="text-danger mt-1 text-xs" x-text="validateCheckboxes(selectedCheckboxes)"></p>
            </template>
        </div>
        <div class="flex justify-end items-center mt-8">
            <button type="button" class="btn btn-outline-danger" @click="toggle">Discard</button>
            <button type="submit" class="btn btn-primary ltr:ml-4 rtl:mr-4">Save</button>
        </div>
    </form>
</div>

code snippet of my .js file:

document.addEventListener("alpine:init", () => {
    /*
    Validate Add new task in Action List
    */
Alpine.data("addTask", () => ({
    
    selectedCheckboxes: {},
    
    isSubmitForm1: false,
    
    validateCheckboxes(selectedCheckboxes){
        
        Object.keys(selectedCheckboxes).forEach(group => {
            selectedCheckboxes[group] = selectedCheckboxes[group] ? 1 : 0;
        });
        const selectedGroups = Object.keys(selectedCheckboxes).filter(group => selectedCheckboxes[group] === 1);
        const myownSelected = selectedGroups.includes('myown');
        const otherSelected = selectedGroups.filter(group => group !== 'myown').length > 0

        if(myownSelected && otherSelected){
            return 'You cannot select "myown" with other groups'
        } else if(!myownSelected && !otherSelected){
            return 'Please select at least one group'
        }
        return ''
    },

    submitFormAddNewTask() {
        if(this.validateCheckboxes(this.selectedCheckboxes)){
            
            this.isSubmitForm1 = true;
            console.log('Not ok')
            
            return false
        }
    
        console.log('ok');
        this.$refs.myForm.submit()
    },
}))
});

I don’t understand why this is happening and how to resolve this issue.

Updating Oracle database using AJAX

I have created a project where my interface fetch data from my Oracle SQL database using springboot, Jquery and AJAX and displays it on a table. What I couldn’t find online is to how to do basic operations(Post, Delete) on my table using HTML forms. All sources mostly focuses on php mySQL projects. I would appreciate any help or guidance on this matter.

$(function(){ //fetching data from oracle

    var $patientsfn = $('#firstname');
    var $patientsln = $('#lastname');
    var $patientsno = $('#patientno');
    var $patientsage = $('#age');
    var $patientsg = $('#gender');
    var $patientsad = $('#adresses');
    var $patientsrd = $('#registerdate');
    var $patientsadd = $('#attendeddoctors');
    $.ajax({
        type: 'GET',
        url: 'http://localhost:8080/api/v1/patients',
        success: function(patients) {
            $.each(patients, function(i, patient){
                $patientsfn.append('<li>'+ patient.firstNames+ '</li>');
                $patientsln.append('<li>'+ patient.lastName+ '</li>');
                $patientsno.append('<li>'+ patient.patientNo+ '</li>');
                $patientsage.append('<li>'+ patient.ages+ '</li>');
                $patientsg.append('<li>'+ patient.genders+ '</li>');
                $patientsad.append('<li>'+ patient.adresses+ '</li>');
                $patientsrd.append('<li>'+ patient.registerDate+ '</li>');
                $patientsadd.append('<li>'+ patient.attendedDocs+ '</li>')
            })
        }
    });
    function submitData(){
        var submitfn = $('input[submitfn = firstNames]').val();
    }
    
});
<script <!-- code for table and  --> src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<a href="backup.html" class="btn btn-secondary text-light">add data</a>
    <div class="container">
      <table id="example" class="table table-striped" style="width: 100%">
        <thead>
          <tr>
            <th>FIRSTNAME</th>
            <th>LASTNAME</th>
            <th>PATIENTNO</th>
            <th>AGE</th>
            <th>GENDER</th>
            <th>ADRESSES</th>
            <th>REGISTERDATE</th>
            <th>ATTENDEDDOCTORS</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td id="firstname"></td>
            <td id="lastname"></td>
            <td id="patientno"></td>
            <td id="age"></td>
            <td id="gender"></td>
            <td id="adresses"></td>
            <td id="registerdate"></td>
            <td id="attendeddoctors"></td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <th>FIRSTNAME</th>
            <th>LASTNAME</th>
            <th>PATIENTNO</th>
            <th>AGE</th>
            <th>GENDER</th>
            <th>ADRESSES</th>
            <th>REGISTERDATE</th>
            <th>ATTENDEDDOCTORS</th>
          </tr>
        </tfoot>
      </table>
    </div>
    
    
    <body id="second">
    <h1 id="header">Veri ekleme</h1>
    <img id="backupimg" src="images/akgun.png" alt="" />


    <form> <!--code for html form-->
      <label for="firstNames">First name:</label><br />
      <input type="text" id="firstNames" name="firstNames" /><br />
      <label for="lastName">Last name:</label><br />
      <input type="text" id="lastName" name="lastName" /><br /><br />
      <label for="ages">Age:</label><br />
      <input type="text" id="ages" name="ages" /><br /><br />
      <label for="genders">Gender:</label><br />
      <input type="text" id="genders" name="genders" /><br /><br />
      <label for="adresses">Adress:</label><br />
      <input type="text" id="adresses" name="adresses" /><br /><br />
      <label for="attendedDocs">Attended Doctor:</label><br />
      <input type="text" id="attendedDocs" name="attendedDocs" /><br /><br />
      <label for="registerDate">Register Date:</label><br />
      <input type="date" id="registerDate" name="registerDate" /><br /><br />
      <input id="submit" type="submit" />
    </form>
    

Retrieving data for Power Apps Person Card from MS GraphAPI

I’m working on a project using Power Pages where I need to display person cards. These cards should pull user information via an API call, specifically using Microsoft Graph API to get details like name, email, and job title. Here’s what I have tried so far:

const options = {
    authProvider,
};

const client = Client.init(options);

let user = await client.api('/users/email.de').get();
<div id="email-container" data-email="{{ employee.new_email }}">
  Email: {{ employee.new_email }}
</div>
<div id="user-info"></div> <!-- Hier wird das API-Ergebnis angezeigt -->

I’m not sure how to correctly authenticate and connect to the API in Power Pages using JavaScript. Specifically, I don’t know how to implement the authProvider in this context to get access to Microsoft Graph without requiring user login each time.

I would also like to display the result dynamically once the API call is made.

How do I authenticate correctly within Power Pages using the Microsoft Graph API? Can I securely make API calls from the client side, or do I need a server-side implementation for this?

Is there a best practice for handling authentication when working with APIs in Power Pages?

Any guidance or examples would be much appreciated!

Unable to reopen YouTube iframe embed full screen after open-exit full screen mod fast

Whenever i try to open and exit youtube embed video in full screen mode fast, button full screen in youtube frame stop working even when i reload the page

It can only work if i close and reopen the page

This is the page code

<!DOCTYPE html>
<meta charset="utf-8">
<title>Demo</title>
<body>

    <iframe width="100%" src="https://www.youtube.com/embed/kWi1beTiVig" frameborder="0" allowFullScreen="allowFullScreen"></iframe>
    <br />

</body>

Is there any solution for this?

I had already try to add attributes in iframe but nothing fix the problem

SyntaxError: Unexpected token in JSON.parse – Invalid JSON format being sent in to the Backend

To give you some context:

I am trying to implement a simple Crud with a Client/Server architecture.
While doing so I tried making a multi-step form, since alot of the forms became quite long,
But, I soon realized error checking while having a multistep form was harder than a simple onepage form.

In order to check if the Unique values of the form were indeed unused in the DB I created a react-query that will check it for me and display a message if the return message was false, meaning there is a duplicate in the DB.

As I was trying to implement said API endpoint I ran into a curious Error:

The value that is being send into the backend is a json that contains values suchs as:

{“name”: “”xValue””}

Which completely crashes my backend.

I could probably try to do some string manipulation to “clean up” the string before turning it into a json and sending it back to the backend.

But I figured before I patch my error up I should probably address the real problem:
The way I am capturing the value. I think…

These are some of the relevant code that I used for this “Unique Checking”

//useState that will hold the value:

  const [carnetValue, setCarnetValue] = useState('');

//React Query and onChange reaction function:

  const { data: isUnique } = useQuery(["checkCarnet", carnetValue], () => apiClient.checkCarnet(carnetValue), {
    enabled: !!carnetValue
  });


  const handleChange = (value: string) => {
    setCarnetValue(value);
  }

//The input itself:

  <input
          type="text"
          className="border border-blue-500 w-full py-1 px-2 font-normal"
          {...register("carnet", { required: "Este campo es necesario", onChange: e => handleChange(e.target.value) })}
        />

//The API Client:

export const checkCarnet = async (carnet: string): Promise<RevisarDato> => {
  console.log(carnet);
  const response = await fetch(`${BASE_API_URL}/api/auth/check-carnet`, {
    method: "POST",
    body: JSON.stringify(carnet),
    headers: {
      "Content-type": "application/json",
    },
  });
  if (!response.ok) {
    throw new Error("Something went wrong");
  }
  const returnData = await response.json();
  return returnData;
};

// In case necessary or relevant this is the Backend Endpoint

export const checkCarnet = async (req: Request, res: Response) => {
  const { carnet } = req.body;
  try {
    const yaExiste = await pool.query(
      "SELECT * FROM Personas WHERE carnet = $1",
      [carnet]
    );
    if (yaExiste.rows.length != 0) {
      return res.status(400).json({ result: false });
    }
    return res.status(200).json({ message: true });
  } catch (error) {
    console.log(error);
    res.status(500).json({ result: "Internal Server Error 500" });
  }
};

This is an example of the displayed Error itself:

SyntaxError: Unexpected token '"', ""asdasda"" is not valid JSON
    at JSON.parse (<anonymous>)

Based on it I can only assume that It has something to do with the way The values are being captured. Maybe its becouse I am using both a custom onChange as well as react-hook-form. Maybe some form of string manipulation is always necesary. I am not really sure.

Aside from the error that inspired this post I would also appreciate any feedback or input about the code itself or how to Error Check Uniqueness in Forms.

With that being said I appreciate your time to see my post!

Functions written inside the File not getting mocked in Node js Test case

I have following file which I am trying to write test cases for .

VehicleAssign.ts

expot const vehicleAssignSPO = async(gettersetter, input) => {
 //some code
 try {
    await checkExpiredSPO(getterSetter, "some value")
}
}


 export const checkExpiredSPO = async(getterSetter, flmt) => {
  
  //some code
   
  }

Now I am trying to write a test case for this file.

VehicleAssign.test.ts

  it('Should be able to call the Function Successfully', async () => {
        const input = mockInput();

         jest.mock('../helpers/vehicleAssignSPO.helper', () => ({
            checkExpiredSPO: jest.fn().mockResolvedValue({})
        }))
       
        const result = await vehicleAssignSPO(getterSetterMock, input)
    })

But here I am mocking the function checkExpiredSPO but still is calling the actual function and the mocked one.

How Can I fix this ?

Non-async function call inside an async function

import { useState } from 'react';

export default function Form() {
  const [text, setText] = useState('');

  function sleep(milliseconds) {
    const start = Date.now();
    while (Date.now() - start < milliseconds) {
    }
  }

  async function handleSubmit(e) {
    sleep(5000);
  }

  function handleTextareaChange(e) {
    setText(e.target.value);
  }

  return (
    <>
      <h2>Test</h2>
      <form onSubmit={handleSubmit}>
        <textarea
          value={text}
          onChange={handleTextareaChange}
        />
        <br />
        <button>
          Submit
        </button>
      </form>
    </>
  );
}

I edited this component from the react docs to make it to the point.

I was learning react and JavaScript and ran into async functions in the react docs.

Here when I submit the form I can not edit it until the sleep runs out, but my confusion is that the sleep(5000) was called inside an async function.

Calling functions inside async functions does not make them non-blocking?
Or, does the form also call await on the handleSubmit as well?

My knowledge on JavaScript and react is low, so I may not be using terms correctly.

Document doesn’t get deleted after expiration

I’m trying to expire the document after one minute its been created but after creating a document it does not get deleted after one minute

const mongoose = require('mongoose');

const textSchema = new mongoose.Schema({
  id: {
    type: String,
    required: true,
    unique: true  
  },
  text: {
    type: String,
    required: true,
  },
  createdAt: {
    type: Date,
    default: Date.now,
    expires: '60s'
  }
});

const Text = mongoose.model('Text', textSchema);

module.exports = Text;

vue3.5 Pass a value to a child component but the child component has not yet been mounted

Parent component :

When clicked, the dialog map component opens and updates the values that need to be passed

function editPowerStationChooseMap() {
    mapVisible.value = true;
    mapForm.address = null
    mapForm.fullDddress = editPowerStationForm.value.address;
    editAddressInfo.value = editPowerStationForm.value.address;
}
<el-dialog v-model="mapVisible" title="选择位置" width="70%">
        <template #header>
            <el-form  :inline="true" ref="mapFormRef" :model="mapForm">
                <el-form-item label="省市区" prop="address">
                    <el-cascader v-model="mapForm.address" :filterable="true" :options="addressOption.option" :props="cascaderProps" class="custom-cascader" @change="chooseAddress" style="width: 240px"/>
                </el-form-item>
                <el-form-item label="详细地址" prop="fullDddress">
                    <el-input v-model="mapForm.fullDddress" placeholder="请输入详细地址" style="min-width: 400px"/>
                </el-form-item>
            </el-form>
        </template>
        <Map @mapReady="handleMapReady" :addressInfo="addressInfo":editAddressInfo="editAddressInfo"/>
        <span slot="footer" class="dialog-footer">
  <el-button @click="mapVisible = false">取消</el-button>
  <el-button type="primary" @click="confirmAddress">确定</el-button>
</span>
    </el-dialog>

children component:

const emit = defineEmits(["mapReady"]);
const { addressInfo, editAddressInfo } = defineProps({
    addressInfo: {
        type: String,
    },
    editAddressInfo: {
        type: String
    }
});
watch([() => addressInfo, () => editAddressInfo], ([newAddress, newEditAddress], [oldAddress, oldEditAddress]) => {
    let addressToGeocode = '';
    // 判断是哪个值发生了变化
    if (newAddress !== oldAddress) {
        addressToGeocode = newAddress;
    } else if (newEditAddress !== oldEditAddress) {
        addressToGeocode = newEditAddress;
    }
    if (addressToGeocode) {
        geocoder.getLocation(addressToGeocode, function (status, result) {
            if (status === 'complete' && result.info === "OK") {
                const lnglat = result.geocodes[0].location;
                map.setCenter(lnglat);
                positionPicker.on('success', function (positionResult) {
                    detailedAddress.value = positionResult.address;
                    emit("mapReady", {
                        map,
                        geocoder,
                        detailedAddress,
                        positonInfo: [positionResult.position.lng, positionResult.position.lat]
                    });
                });
                positionPicker.on('fail', function (positionResult) {
                });
                positionPicker.start(lnglat);
            } else {
                console.error('根据地址查询位置失败');
            }
        });
    }
});

onMounted(() => {
    window._AMapSecurityConfig = {
        securityJsCode: '61ed75a46aa0cc6a2860aa025fd22ed5',
    };

    AMapLoader.load({
        key: '9c4e9341d7408b1241277ae9d7498df9',
        version: "2.0",
        AMapUI: {
            version: "1.1"
        }
    })
        .then((AMap) => {
            map = new AMap.Map("container", {
                viewMode: "2D",
                zoom: 11,
                center: [116.397428, 39.90923], // 默认中心点
            });


            // 拖拽选址插件
            AMapUI.loadUI(['misc/PositionPicker'], function (PositionPicker) {
                positionPicker = new PositionPicker({
                    mode: 'dragMarker',//设定为拖拽地图模式,可选'dragMap'、'dragMarker',默认为'dragMap'
                    map: map, //依赖地图对象
                    iconStyle: {//自定义外观
                        url: ikun,
                        size: [48, 48],  //要显示的点大小,将缩放图片
                        ancher: [24, 40],//锚点的位置,即被size缩放之后,图片的什么位置作为选中的位置
                    }
                });
            });

            // Geocoder 插件
            AMap.plugin('AMap.Geocoder', () => {
                geocoder = new AMap.Geocoder({city: '全国'});
                emit("mapReady", {map, geocoder, detailedAddress: ''});
            });

        })
        .catch((e) => {
            console.error(e);
        });
});

When I click, the dialog opens but the watch code does not execute. When I add the delayer, the code executes normally. like this:

function editPowerStationChooseMap() {
    mapVisible.value = true;
    setTimeout(()=>{
        mapForm.address = null
        mapForm.fullDddress = editPowerStationForm.value.address;
        editAddressInfo.value = editPowerStationForm.value.address;
    },500)
}

Trying nextTick didn’t work either, was it because the map component took so long to load?

how to handle seperate FormData in the replicated form?

I am trying to creating a dashboard with panels of different sizes and re-arrange able according to the users will also the panel have different formData inside the same panel Form.

Dashboard and panels

Expected : to get the formData from the first panelform and i have stored it in a hidden input element inside the first formData and likewise for n number of panel i want to achieve this, then for saving the panels i want to iterate over the each panels and get the formData that is stored in each panels.

Dashboard 1

  • panel 1 {“type”:”1″,”chartType”:”bar”,”panellogsource”:”19″,”fieldSelected”:[“dst_as”,”dst_mask”],”timeWindow”:”Last 15 Minutes”}
  • panel 2 {“type”:”2″,”aggregateType”:”count”,”panellogsource”:”19″,”fieldSelected”:[“dst_port”,”dst_tos”],”timeWindow”:”Last 15 Minutes”}

Actual : i am able to set the data for the first panel but after populating the second panel the form is retrieving the previous(first) panel data. i want to separate the panels formData for each panel.

Dashboard 1

  • panel 1 {“type”:”1″,”chartType”:”bar”,”panellogsource”:”19″,”fieldSelected”:[“dst_as”,”dst_mask”],”timeWindow”:”Last 15 Minutes”}
  • panel 2 {“type”:”1″,”chartType”:”bar”,”panellogsource”:”19″,”fieldSelected”:[“dst_as”,”dst_mask”],”timeWindow”:”Last 15 Minutes”} (same content for the second panel)
<div class="panel-container col-lg-${layoutSize}">
  <div class="card">
    <div class="panel card-body ibox">
      <div class="panel-heading card-title ibox-title">
        <h5>Drag&amp;Drop ${layoutSize}</h5>
        <div class="ibox-tools d-flex">
          <a class="collapse-link" onclick="return collapseIbox(event, this);">
            <i class="fa fa-chevron-up"></i>
          </a>
          <div class="dropdown options ms-auto">
            <a class="dropdown-toggle" data-bs-toggle="dropdown">
              <i class="fa fa-wrench"></i>
            </a>
            <ul class="dropdown-menu">
              <li>
                <a href="#" onclick="editPanel()" class="dropdown-item"
                  >Edit Content</a
                >
              </li>
              <li>
                <a href="#" class="dropdown-item">
                  Size:
                  <button
                    class="btn btn-l btn-primary"
                    onclick="changeSize(this, 'lg');"
                    title="Full Row"
                  >
                    <i class="fa fa-square-o fs-6"></i>
                  </button>
                  <button
                    class="btn btn-m btn-primary"
                    onclick="changeSize(this, 'md');"
                    title="2 Column Row"
                  >
                    <i class="fa fa-square-o fs-5"></i>
                  </button>
                  <button
                    class="btn btn-s btn-primary"
                    onclick="changeSize(this, 'sm');"
                    title="3 Column Row "
                  >
                    <i class="fa fa-square-o fs-4"></i>
                  </button>
                  <button
                    class="btn btn-xs btn-primary"
                    onclick="changeSize(this, 'xs');"
                    title="4 Column Row"
                  >
                    <i class="fa fa-square-o fs-3"></i>
                  </button>
                </a>
              </li>
            </ul>
          </div>
          <a class="close-link" onclick="return closeIbox(event, this);">
            <i class="fa fa-times"></i>
          </a>
        </div>
      </div>
      <div class="ibox-content">
        <!-- add new content to the panel -->
        <button type="button" class="btn btn-light ms-2" onclick="editPanel()">
          Edit Panel
        </button>
      </div>
    </div>
  </div>
</div>
<!-- Panel Loading Modal -->
<div class="modal fade" id="panelCreateModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Panel Data</h5>
        <button
          id="icon-modal-close"
          type="button"
          class="btn-close"
          data-bs-dismiss="modal"
          aria-label="Close"
        >
          <i class="bx bx-x text-white font"></i>
        </button>
      </div>
      <div class="modal-body">
        <%@ include file="../dashboard/panel_create.jsp"%>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          Close
        </button>
      </div>
    </div>
  </div>
</div>

panel_create.jsp

<div class="panel">
    <form class="row g-3" id="PanelCreationForm" onsubmit="return false;">
        <!-- TYPE-> CHART,AGGREGATION -->
        <div class="col-md-6">
            <label for="type" class="form-label">Type<span style="color: red;">*</span></label> <select name="type" id="type" class="form-control" required
                onchange="toggleType(this.value)">
                <option value="select" selected disabled>Select</option>
                <option value="1" ${panel ne null and panel.type eq '1' ? 'selected' : ''}>Chart</option>
                <option value="2" ${panel ne null and panel.type eq '2' ? 'selected' : ''}>Aggregation</option>
            </select>
        </div>
        <!-- CHART OPTION / AGGREGATE OPTION -->
        <div class="col-md-6">
            <label for="type" class="form-label">Chart / Aggregate<span style="color: red;">*</span></label><select name="chartType" id="chartType"
                class="form-control" required>
                <option value="select" selected disabled>Select Chart</option>
                <c:forEach var="option" items="${chartOptions}">
                    <option value="${option.value}" <c:if test="${option.value == panel.typeData}">selected</c:if>>${option.displayText}</option>
                </c:forEach>
            </select> <select name="aggregateType" id="aggregateType" class="form-control" required>
                <option value="select" selected disabled>Select Aggregate</option>
                <c:forEach var="option" items="${aggregateOptions}">
                    <option value="${option.value}" <c:if test="${option.value == panel.typeData}">selected</c:if>>${option.displayText}</option>
                </c:forEach>
            </select>
        </div>
        <div class="col-md-2">
            <!-- LogSource -->
            <label for="logsource" class="form-label">Log Source<span style="color: red;">*</span></label> <select name="panellogsource" id="panellogsource"
                class="form-control" required>
                <option value="select" selected disabled>Select</option>
                <c:forEach var="logSource" items="${LogSource.sources()}">
                    <option value="${logSource.logId}" <c:if test="${logSource.logId eq panel.logSource}">selected</c:if>>${logSource.name}</option>
                </c:forEach>
            </select>
        </div>
        <!-- FIELD -->
        <div class="col-md-10">
            <!-- Field Multi Select -->
            <label class="form-label">Field<span style="color: red;">*</span></label>
            <div id="fieldSelectDiv">
                <select multiple name="fieldSelected" class="form-control form-control-cust" id="fieldSelect" required>
                </select>
            </div>
        </div>
        <div class="col-md-2">
            <!-- Time Window -->
            <button type="button" style="margin-left: 4px" data-popover-content="#pop-time-window-content" data-toggle="popover" tabindex="0"
                class="btn btn-sm btn-light btn-icon-custom time-window-pop" id="wTimeWindowCalendar" title="Time Window">
                <i class="bx bx-calendar font-20"></i>
            </button>
            <input style="min-width: 300px !important; max-width: 300px !important;" type="text" name="timeWindow" id="timeWindow"
                class="form-control form-control-cust timeWindowInput" placeholder="Time Window" data-time-window="last-1-year"
                value="${panel ne null ? panel.timeWindow: ''}" readonly>
            <!-- Time Window End -->
        </div>
        <div class="col-md-12">
            <!-- Panel Data type="hidden"  -->
            <input type="text" class="form-control" id="panelData" value=" ">
        </div>
        <div class="col-12" style="padding-top: 25px; display: flex; justify-content: center;">
            <c:if test="${page eq 'new'}">
                <button type="submit" onclick="javascript:addPanelData()" class="btn btn-light px-5" id="btnSubmit">Add</button>
            </c:if>
            <c:if test="${page eq 'edit'}">
                <button type="submit" onclick="javascript:updatePanelData()" class="btn btn-light px-5" id="btnSubmit">Update</button>
            </c:if>
        </div>
    </form>
</div>

js function to add the formData to each panel


function addPanelData() {
    console.log("addPanelData");
    // Iterate over each panel container
    $('.panel').each(function(index) {
        var formDataObject = {};
        // Serialize the form data for the current panel
        var formData = $(this).find('form').serializeArray();
        console.log("formData: ", formData);
        $.each(formData, function(i, field) {
            if(field.name==='fieldSelected'){
                if(!formDataObject[field.name]){
                    formDataObject[field.name]=[];  
                }
                formDataObject[field.name].push(field.value);
            }else{
                formDataObject[field.name] = field.value;
            }
        });

        console.log(`Form Data for Panel ${index}:`, formDataObject);

        // Convert formDataObject to JSON string and store it in the hidden input field panelData
        $(this).find('input[id="panelData"]').val(JSON.stringify(formDataObject));
        $(this).find('form')[0].reset();
    });
}

Why callback function showing “Undefined” result?

I have been learning javascript test scripts in Postman.Here I am just learning about callback functions and I wanted to check return value is showing in the last line of print statement but the result shows ‘undefined’. Below is the code:

function add(a,b)
{
    console.log(a+b);
    return a+b;
}
function test(testname,callbackfunction,m,n)
{
    console.log(testname);
    callbackfunction(m,n);
}
console.log
(test("THis is addition",add,12,12));

Console shows:

THis is addition
24
undefined

Why it showing undefined in the last line instead of showing 24 the return value?
Thanks in advance.

I tried to store the return value in a variable but it showing the same ‘unfined’ result.

let stu=test("THis is addition",add,12,12);

Error: Exported bands must have compatible data types; found inconsistent types: Float64 and Float32. (Error code: 3)

#I cant export the layer to my google drive because of this error:Exported bands must have compatible data types; found inconsistent types: Float64 and Float32. (Error code: 3). can anyone help me with this problem.

var band = ['B11','B8', 'B4', 'B3', 'B2'];
var image = ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED").select(band).filterBounds(table)
            .filterDate('2023-12-01','2023-12-31').filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE",20)).median()
            .clip(table);
            
var visparams = {min:0.0, max:3000, bands:['B8','B4', 'B3']};
print(image, visparams,'image');

Map.addLayer(image,visparams, 'image');

var nd= function(image){
          
        var ndwi= image.normalizedDifference(['B3','B8']).rename('NDWI');
          return image.addBands(ndwi);
};

var nd1 = nd(image);

Map.addLayer(nd1.select('NDWI'),{palette: ['red', 'yellow', 'green', 'cyan', 'blue']},'nd2');

Export.image.toDrive({
  image: nd1,
  description: "NDWI_2023",
  region: table,
  maxPixels:380681498 ,
  scale: 10, 
})

Error [ERR_STREAM_WRITE_AFTER_END]: write after end (NodeJS)

I’m trying to make an api endpoint using nodejs. When i hit the route using postman i got error. First time the code runs and then the server is crashed.

My code is:

const http = require('http');
const {handleReqRes} = require('./helpers/handleReqRes');

const app = {};

app.config = {
    port: 5000,
};

app.createServer = () => {
    const server = http.createServer(app.handleReqRes);
    server.listen(app.config.port, () => {
        console.log(`listening to port ${app.config.port}`);
    });
};

app.handleReqRes = handleReqRes;

app.createServer();

On terminal when i request anyting the error showing:

node:events:491
      throw er; // Unhandled 'error' event
      ^

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at new NodeError (node:internal/errors:387:5)
    at ServerResponse.end (node:_http_outgoing:968:15)
    at IncomingMessage.<anonymous> (/home/rafid/Desktop/personal_akam/Node/raw_node_api/helpers/handleReqRes.js:52:13)
    at IncomingMessage.emit (node:events:525:35)
    at endReadableNT (node:internal/streams/readable:1358:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
Emitted 'error' event on ServerResponse instance at:
    at emitErrorNt (node:_http_outgoing:827:9)
    at processTicksAndRejections (node:internal/process/task_queues:84:21) {
  code: 'ERR_STREAM_WRITE_AFTER_END'
}```


Trying to make an api endpoint using nodejs.

EJS Rendering Issue: Status Column Value Not Displaying from MySQL Query

I am building a student management system using Node.js, MySQL, and EJS to render views. I want to display a list of students with their status value in a table, but the status column isn’t showing any value, even though the data exists in the database.

MySQL Query:

SELECT s.stuNIC as NIC, s.stuUserName as username, u.intendedMajor, u.status
FROM student s 
JOIN university_registration u ON s.stuNIC = u.NIC;

The query works correctly when I run it directly on MySQL, and it returns the status value as expected.

EJS Template (uni-view-student.ejs):

<% data.forEach(function(student) { %>
    <tr onclick="window.location.href='/uni-notification/<%= student.NIC %>'">
        <td><%= student.NIC %></td>
        <td><%= student.username %></td>
        <td><%= student.intendedMajor %></td>
        <td><%= student.status %></td> <!-- This is not showing any value -->
    </tr>
<% }); %>

Node.js Code (server.js):

app.get('/uni-view-student', (req, res) => {
    const query = `
        SELECT s.stuNIC as NIC, s.stuUserName as username, u.intendedMajor, u.status
        FROM student s 
        JOIN university_registration u ON s.stuNIC = u.NIC
    `;
    connection.query(query, (err, results) => {
        if (err) {
            console.error('Error querying the database:', err);
            return res.status(500).send('Database query error');
        }
        res.render('uni-view-student', { data: results });
    });
});

Even though student.status is part of the query and has values in the database, the status column shows up empty on the page.

What could be causing this issue, and how can I fix it so that the status value shows up correctly in the EJS template?

enter image description here
enter image description here

How to check a scroll-to button in Cypress?

I have a series of menu items that scroll to different elements on my page.

I’d like to loop through each item and ensure it scrolls to the correct element on the page. To do this I would like to get the href value to use as the target element to scroll to.

The first time works, however I then get an error:

TypeError: Timed out retrying after 4000ms: Cannot read properties of undefined (reading 'toLowerCase')

Which is odd because I am not using that function in my code (I’m guessing it’s within Cypress its self).

Would anyone know the correct way of doing this?

My HTML looks like:

<a class="subnav_item" href="#item-1">Item 1</a>
<a class="subnav_item" href="#item-2">Item 2</a>
<a class="subnav_item" href="#item-3">Item 3</a>

And my Cypress test looks like:

cy.get(".subnav_item").each(($submenuItem) => {
    let targetEl = cy.get($submenuItem).invoke('attr', 'href');
    cy.get($submenuItem).click();
    cy.wait(500);
    cy.get(targetEl).should('be.visible');
});