jQuery-ui dialog dynamic buttons, change text and function

So I have a default dialog with 2 buttons defined. In my code, it looks the following:

    var defaultButtons = [{
    text: "default"
},

    {
        text: "default"
    }
    ];
    
    $(document).ready(function () {
        $("#dialog-confirm-dynamic").dialog({
            position: {
                my: "center 10%+center",
                at: null,
                of: window
            },
            autoOpen: false,
            resizable: false,
            maxWidth: 250,
            maxHeight: 150,
            width: 250,
            height: "auto",
            modal: true,
            buttons: defaultButtons
        });
    });
    
    function showConfirm() {
        document.getElementById("confirm-dyn-inner").innerHTML = "Are you sure to do this ?";
        $("#dialog-confirm-dynamic").dialog({ title: "Delete" });
        defaultButtons[] = [{
            text: "Delete",
            click: function () {
                document.form.submit();
            }
        },
            {
                text: "Cancel",
                click: function () {
                    $(this).dialog("close");
                }
            }
        ];
        $("#dialog-confirm-dynamic").dialog("open");
    }

In showConfirm() I’m trying to change the text and behaviour of the buttons, but I suspect that they have already been rendered and changing values of the array, even before “open” is not changing anything.

What is the best way to approach this?
TIA

Please help me understand the below [closed]

The question is to “In a TableViewer component you rendered earlier, render all the comments/data pulled from the backend #hint: create columns array and pass it along with other props to TableViewer component”

I have never worked with react or js like this before so its very new to me .

I am unsure if i should add the const column part in Mycomponet.js file or my premade Tableviewer.js file

Please can you help me understand how I can solve this , Its confusing me alot .

I have tried the to create the below code from my component

import React, { Component } from 'react';
import TableViewer from '../utilities/TableViewer';

class MyComponent extends Component {
    state = {
        message: '',
        response: '',
        tableData: [],
        columns: [
            { title: 'ID', field: 'id' },
            { title: 'Comment', field: 'text' }
        ]
    };

    handleChange = (event) => {
        this.setState({ message: event.target.value });
    };

    handleSubmit = async () => {
        const { message } = this.state;
        const response = await fetch('/api/message', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ message }),
        });
        const data = await response.json();
        this.setState({ response: data.message });
    };

    getMessage = async () => {
        try {
            const response = await fetch('/comments'); // Fetch comments from the backend
            const data = await response.json();
            this.setState({ tableData: data }); // Store the fetched comments in state
        } catch (error) {
            console.error('Error fetching comments:', error);
        }
    }

    componentDidMount() {
        this.getMessage(); // Fetch comments when the component mounts
    }

    render() {
        const { message, response, tableData, columns } = this.state;

        return (
            <div>
                <h1>Threat Portal Mockup</h1>
                <input
                    type="text"
                    value={message}
                    onChange={this.handleChange}
                    placeholder="Enter a message"
                />
                <button onClick={this.handleSubmit}>Submit</button>
                <p>Response: {response}</p>

                {/* New section for TableViewer */}
                <div className="table-viewer-section">
                    <h2>Table Viewer Section</h2>
                    <TableViewer
                        data={tableData} // Pass the fetched comments data
                        columns={columns} // Pass the defined columns
                        keyField={"id"} // Use 'id' as the unique key field
                    />
                </div>
            </div>
        );
    }
}

export default MyComponent;

Excluding package using externals causes “Cannot use ‘in’ operator to search for ‘core’ in undefined” error

I am creating a razor class library that wraps the azure-maps-control npm package.

I use TypeScript to build the *.js and Webpack to bundle the *.js.

When I use the RCL in my Blazor web app it works great.

However, I don’t want to distribute the azure-maps-control with my RCL
So I add this line to webpack.config.js:

externals: 'azure-maps-control'

When I do that and build, I now get the “Cannot use ‘in’ operator to search for ‘core’ in undefined” error.

index.js:

import * as atlas from "azure-maps-control";

export interface Authentication {
    authType: atlas.AuthenticationType;
    aadAppId: string;
    aadTenant: string;
    clientId: string;
    subscriptionKey: string;
}

export class core {
    private static maps: Map<string, atlas.Map> = new Map<string, atlas.Map>();

    public static addMap(
        mapId: string,
        configuration: Authentication): void {

        if (this.maps.has(mapId)) {
            console.error(`Map with ID ${mapId} already exists.`);
            return;
        }
        const map = new atlas.Map(mapId, {
            authOptions: {
                authType: configuration.authType,
                subscriptionKey: configuration.subscriptionKey,
                aadAppId: configuration.aadAppId,
                aadTenant: configuration.aadTenant,
                clientId: configuration.clientId,
            },
            center: [-122.33, 47.6],
            zoom: 12,
            view: "Auto",
        });
        this.maps.set(mapId, map);
    }
}

webpack.config.js:

const path = require('path');

module.exports = {
    entry: "./dist/index.js",
    output: {
        path: `${__dirname}/wwwroot/dist`,
        filename: "bundle.js",
        library: 'azMaps'
    },
    externals: 'azure-maps-control'
};

bundle.js:

var azMaps;(()=>{"use strict";var e={d:(a,t)=>{for(var o in t)e.o(t,o)&&!e.o(a,o)&&Object.defineProperty(a,o,{enumerable:!0,get:t[o]})},o:(e,a)=>Object.prototype.hasOwnProperty.call(e,a),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},a={};e.r(a),e.d(a,{core:()=>o});const t=azure-maps-control;class o{static maps=new Map;static addMap(e,a){if(this.maps.has(e))return void console.error(`Map with ID ${e} already exists.`);const o=new t.Map(e,{authOptions:{authType:a.authType,subscriptionKey:a.subscriptionKey,aadAppId:a.aadAppId,aadTenant:a.aadTenant,clientId:a.clientId},center:[-122.33,47.6],zoom:12,view:"Auto"});this.maps.set(e,o)}}azMaps=a})();

If I remove externals: 'azure-maps-control' it works fine, but the package gets bundled.

Any suggestions?

Axios and fetch return different values for a nested object

If I make the same API request in axios and fetch, I get different values for a deeply nested value, even though the network tab shows the correct value for both network calls:

    const { data } = await axios.get(`/my/api/path/`, {
      headers: {
        Accept: 'application/json'
      }
    });
    const axiosIntermediatePath = data.root.nested.path;
    console.log('axiosIntermediatePath:', axiosIntermediatePath);

    const fetchResponse = await fetch(`/my/api/path/`, {
      headers: {
        Accept: 'application/json'
      }
    });
    const fetchData = await fetchResponse.json();
    const fetchIntermediatePath = fetchData.root.nested.path
    console.log('fetchIntermediatePath:', fetchIntermediatePath);
axiosIntermediatePath: 
{
  ...
  "foo": {
    "bar": "",
  },
  ...
}
fetchIntermediatePath: 
{
  ...
  "foo": {
    "bar": "myCorrectData",
  },
  ...
}

Even stranger, if I then immediately access the property, it
returns correctly:

    console.log('axiosEditor:', axiosIntermediatePath.foo.bar);
    console.log('fetchEditor:', fetchIntermediatePath.foo.bar);
axiosEditor: myCorrectData
fetchEditor: myCorrectData

I found this problem because I was using axios and assigning data.root to a React.Context variable, then passing it around a bit, and I wasn’t able to access the correct value in a nested component.

Edit: (with some help from the comments) I discovered that this only happens in a Redux action context. The line before the block reproduced above is dispatch(getAPIRequest());. If I remove that line the problem goes away. So the question now is why Redux changes the value returned by the API call, and how to fix it.

Replace multiple matches

Given a JSON object which contains tags identified by {{, I need to find all matches in the payload and replace them. The following code works, but only returns the 1st match, and if I turn on the gim flags to replace all matches, the code breaks. It is worth noting that the application uses ECMA5 engine (SpiderMonkey)

For the sake of demoing, I’m using the window variables, as with the application I am working for, I should also be replacing with workflow variables, so works similarly.

var Obj = {
  hostname: "Test 1 {{window.location.hostname}}",
  protocol: "Test 2 {{window.location.protocol}}"
}
var myObj   = JSON.stringify(Obj)
var regex   = /{{window.location.(.+?)}}/       //gmi flag breaks code
var match   = myObj.match(regex)[1];
var enrich  = Function('return '+"window.location."+match)();
var _Obj    = myObj.replace(regex,enrich)


console.log(JSON.parse(_Obj))

The regex works as follows (https://regex101.com/r/BPFnKK/1) I am using index [1] to select the value.

enter image description here

JS regex replace multiple matches

given an JSON object which contains tags identified by {{ I require to find all matches in the payloadand replace them. The following code works, but only returns the 1st match, and if I turn on the gim flags to replace all matches, code breaks. below is what I’ve tried so far, i guess is worth noting the application uses ecma5 engine (SpiderMonkey)

For the sake of demoing, Im using the window variables, as with the application I am working for, I should also be replacing with workflow variables, so works similarly.

var Obj = {
  hostname: "Test 1 {{window.location.hostname}}",
  protocol: "Test 2 {{window.location.protocol}}"
}
var myObj   = JSON.stringify(Obj)
var regex   = /{{window.location.(.+?)}}/       //gmi flag breaks code
var match   = myObj.match(regex)[1];
var enrich  = Function('return '+"window.location."+match)();
var _Obj    = myObj.replace(regex,enrich)


console.log(JSON.parse(_Obj))

Jquery datetimepicker last day of month not working

I have a filter page with 2 datetimepicker as Start date (first day of month) and End date (last day of month). This is what I’m trying to do:

$(document).ready(function () {

    var date = new Date(2025, 3, 22);
    var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
    var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

    console.log("date");
    console.log(date);
    console.log("firstDay");
    console.log(firstDay);
    console.log("lastDay");
    console.log(lastDay);
    
    $('#StartDate').datetimepicker({
        defaultDate: firstDay,
        locale: 'en-ie',
        format: 'DD/MM/YYYY',
        showClose: true,
        showClear: true,
        ignoreReadonly: true,
        minDate: '1900-01-01',
        allowInputToggle: true
    });

    $('#EndDate').datetimepicker({
        defaultDate: lastDay,
        locale: 'en-ie',
        format: 'DD/MM/YYYY',
        showClose: true,
        showClear: true,
        ignoreReadonly: true,
        minDate: '1900-01-01',
        allowInputToggle: true
    });
}

The error:

For example, if the date is 22/04/2025, the firstDay will be 01/04/2025 and the lastDay will be 30/04/2025.
But my datimepickers showing fistDay as 31/03/2025 and lastDay as 29/04/2025.
1 day before the correct dates.
In console log my variables is correct but when I try to query my components value, I see the wrong days.

Console log

Console log variables

I’ve looked in several places and I can’t find the reason for this error.

Do platforms like LeetCode benchmark official solutions to set time limits? [closed]

I’ve heard that platforms like LeetCode (and similar online judges) create an official or optimal solution for each problem and then run it to determine execution time. Based on that, they set the time limit for submissions slightly higher.
Is this accurate?
online-judges
Do platforms actually do this?

Are there any official articles, documentation, or blog posts from LeetCode, Codeforces, HackerRank, etc., that explain this process?

Is it standard practice across most competitive programming platforms?

I’m building a custom judge (similar to Judge0) and want to understand how professionals design fair time limits. Any authoritative reference or practical experience would be appreciated.

When i expand a card in page top part of page becomes inaccessible

<div className="flex flex-col w-4/5 ">
        <button
          onClick={() => {
            setiscardopened(!iscardopened);
          }}
          className="w-full h-11 mt-3 bg-green-500 rounded-xl cursor-pointer"
        ></button>
        {rndnum ? (
          <div
            id="card-container"
            className={
              iscardopened
                ? "flex flex-col justify-center items-center border-2 transition-all duration-500 opacity-100 scale-100  max-h-full h-1/3  overflow-hidden"
                : "flex flex-col justify-center items-center border-2 transition-all    duration-500 opacity-0 scale-95    h-0 overflow-hidden"
            }
          >
            <img
              src={`onlystates/${rndnum[0]}.png`}
              className="border-2 w-auto h-20"
            ></img>
            <div className="flex-row flex">
              <InputandList
                inputref={inputref}
                setquery={setcardquery}
                statenames={CardsNames}
                filterednames={filteredCardNames ? filteredCardNames : [""]}
                widthofinput={"3/4"}
                placeholder={
                  {placeholders}}
              ></InputandList>
              <button
                className=" w-4/11 rounded-2xl mt-2 h-11 text-sm border-5 border-gray-800 bg-gray-700 z-50"
                // onClick={handlesubmit}
              >
                GUESS
              </button>
            </div>
            <CardGuesContainer></CardGuesContainer>
          </div>
        ) : (
          ""
        )}

Page with Card opened

)

page without card opened

tried to add overflow style to parent classes and card’s class but everytime pages top part is becomes inaccessible

How to store data in an array in row/column format using javascript

I am trying to bring all the columns of a table from database and want to store whole data (retrieved from webform) in an array with column names.
For Example Following is my database Table.
StudentName     Roll_No     Subject     Marks
Rock                     101             English      98

I want to store above data in same structure in my array.
Here is my code…

function Insert(FormName, DivName) {
    $.ajax({
        type: "POST",
        url: "" + FormName + ".aspx/GetData",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var xmlDoc = $.parseXML(response.d);
            var xml = $(xmlDoc);
            var Records = xml.find("Table");
            if (Records.length > 0) {
             
                var DetailData = new Array();  // I want to store table in same structure in this array.
                
                $.each(Records, function () {
                    var record = $(this);
                    var ColName = record.find("Column_name").text();   //Getting Column names from database
                    var ColValue = GetColumnsValue(ColName, DivName);  // getting columns value in webform.

                });
            }
        },
        error: function (d) {
            alert(d.responseText);
        }
    });
}

Vite react failed to import dynamic component in production. just after deployment throwing error once.on refresh error goes way

i am working on vite react project and with ci/cd when i deploy app on server just after that error with message ‘Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of “text/html”. Strict MIME type checking is enforced for module scripts per HTML spec.’ comes and with this comes failed to import dynamic component. and on hard refresh this error goes away

Declaring variable in every time when function declaring

Not every time we need the declaration of variables in function that using many time. how to separate the declaration of variables and functions in the time that variables is necessary for functions .

function Help(text, color) {
    var help = document.getElementById("help");
    help.style.color = color;
    help.innerText = text;
}

document.getElementById("button").addEventListener("click", function() {
        Help(Math.floor(Math.random() * 360), ["red", "blue", "white"][Math.floor(Math.random() * 2)]);
});

In this simple example : the variable “help” is declaring every time when i click on button. So this what i no need . I know i can declare this variable like a global variable but that no need also . so can you give me a solution . I believe the solution is to learn the functions__closures. I looked that and i can’t know the solution.

Character replacement loop

I am sharing a piece of code.

const str = "This is very long road"
const newChar = {
  s: "S",
  o: "O"
};

let newStr = "";

for (const char of str){
  newStr += newChar[char] || char;
}
console.log(newStr);

Can someone please explain me what is this code means?

newChar[char] || char

Can’t we just write newChar?