How can I get the value of specific cases of i into an array or something similar?

I would like to go through each of the Rows then each of the points and capture a value tied to ColNum equaling to each iteration of j then get the max of these values. In easier terms I want to get Width of all object that have attribute ColNum = 2 then get the max of that.

This code is a modified javascript/html for Schneider electric TGML editior.

function load(evt) {
  var TGMLDocument;
  var comp;
  var Point;
  var Row;
  var Row_;
  var colNum;
  var testArr1 = {};
  var testArr2;

  TGMLDocument = evt.getCurrentTarget().getOwnerDocument().getDocumentElement();
  comp = evt.getCurrentTarget();
  Row = nodeFilter(TGMLDocument, "Id", "GlobalRowsX");
  // Point = nodeFilter(comp, "Id", "Point");

  for (var i = 0; i < Row.length; i++) {
    // console.log("The Row is", i);

    Point = nodeFilter(Row[i], "Id", "Point");

    for (var j = 0; j < Point.length; j++) {
      console.log("The Row is " + i + ", The Point is " + j);
      Point[j].setAttribute("ColNum", j);
      console.log("The Column Number is " + Point[j].getAttribute("ColNum"));
    }
  }
}

function nodeFilter(cComp, attrName, attrValue, searchType) {
  try {
    var returnArr = [];
    switch (searchType) {
      case 'children':
        var children = cComp.getChildNodes();
        break;
      case 'nested':
        var children = cComp.getElementsByTagName('*');
        break;
      default:
        var children = cComp.getChildNodes();
    }
    for (var i = 0; i < children.length; i++) {
      try {
        if (children.item([i]).hasAttribute(attrName)) {
          if (children.item([i]).getAttribute(attrName) == attrValue) {
            returnArr.push(children.item([i]));
          }
        }
      } catch (err) {}
    }
    if (returnArr.length > 1) {
      return returnArr;
    } else if (returnArr.length > 0) {
      return returnArr[0];
    } else {
      return null;
    }
  } catch (err) {}
}

I have tried using arrays, obj {}, and eval to create dynamic variables declarations.
Row and Point are returned as arrays.

convert dates to timestamp according to JS function within a website

I’m trying to scrape the following website Where i need to select start and end dates.

Here, i noticed an API call to that end-point holding a JSON data as below.

enter image description here

1712089716000 is equal to 04/03/2024

and

1713907716000 is equal to 04/23/2024

The point here those dates got converted into timestamp but am not sure which JS function is handling that in order to replicate the same using Python.

Force page breaks for printing within a td tag

I’m currently styling for print in our application. We want repeating headers/footers on each page. After looking at pagedjs, and trying to milk something out of the barely implemented @page spec, I found the easiest way to get the repeating headers and footers was to just nest the whole structure in a table.

By default the contents of thead and tfoot get printed as the header and footer on each page.

<table>
  <thead>
   <tr>
     <th>This header will repeat on each page!</>
   </tr>
  </thead>
  <tbody>
    <tr>
     <td>All page content goes here</td>
    </tr>
  </tbody>
  <tfoot>
   <tr>
    <th>This footer gets printed on each page!</th>
  </tr>
  </tfoot>
</table>

However it seems when taking this approach all the methods for controlling page breaks within the content td don’t work.

Elements with break-inside: avoid will still break inside. Neither break-before: all or page-break-before: always force page breaks.

I think the only way to make this solution work would be to chop the content into tds, but that would send me back to the drawing board on the whole solution.

Has anyone faced this, if so how’d you get around this issue?

Threejs dynamically create box with text inside

I’ve come up into such a problem I can’t decide what to do:
I’m using ThreeJS for data visualization and I need to create a list of boxes with text labels, a box width should be equal to text width ( plus some padding on sides ).

The problem is very trivial when using HTML, but in ThreeJs world I’ve encountered some problems:

  1. First I was using TextGeometry and managed to dynamically get text’s width and calculate box parameters. But then, I read that TextGeometry is not very performant and might crash if many are rendered (in my app, it should be a lot of boxes, some hundreds)
  2. Then I created HTML canvas, drawText on it and loaded it with Texture. And it worked again, everything awesome, but I coudldn’t calculate Texture’s width in ThreeJS units, I get pixels and don’t know how to “transform” it..Maybe it’s not bad idea to use pixels as ThreeJS unit, but not sure…
  3. At last, I tried CSS2DRenderer (and it also worked). So, I used const boundingBox = new THREE.Box3().setFromObject(myCssObject); and was very dissapointed to see that result isn’t ok: both boundingBox.max and boundingBox.min were {x: Infinity, y: Infinity, z: Infinity vectors…

So maybe someone has already done similiar things and can suggest something? Very grateful in advance

Loading/playing two separate videos with two different buttons

I have two videos embedded on a WordPress site built in Elementor. Each button hides an image and reveals a video embed. Button 1 needs to play Video 1, Button 2 needs to play Video 2, etc. Right now, both buttons play Video 1 because the videos are accessed via querySelectorAll which I know stores them as an array. What I can’t figure out is how to iterate through them so each button plays its respective video.

j(".image-video-swap .play").click(function(){
    var video = document.querySelectorAll('iframe[src^="https://www.youtube.com/embed/"]');
    if (j(this).closest('.image-video-swap').find(".video-column .elementor-element:visible").next().length != 0)
        j(this).closest('.image-video-swap').find(".video-column .elementor-element:visible").fadeOut(function(){
            j(this).next().fadeIn();
                video.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
                video.contentWindow.postMessage('{"event":"command","func":"mute","args":"1"}', '*');
                video.contentWindow.postMessage('{"event":"command","func":"setLoop","args":"1"}', '*');
        });
    else {
        j(this).closest('.image-video-swap').find(".video-column .elementor-element:visible").fadeOut(function(){
            j(this).closest('.image-video-swap').find(".video-column .elementor-element:first").fadeIn();
                video.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
                video.contentWindow.postMessage('{"event":"command","func":"mute","args":"0"}', '*');
                video.contentWindow.postMessage('{"event":"command","func":"setLoop","args":"1"}', '*');
        });
    }
    return false;
});

Collocated Javascript files fail to load when ASPNETCORE_ENVIRONMENT set to Production

In a .NET 8 razor pages app, when I switch my ASPNETCORE_ENVIRONMENT environment variable to Production, my app works perfectly normally except that it does not load javascript files that aren’t located directly in the wwwroot folder.

All my appsettings.json files are identical and do not change depending on ASPNETCORE_ENVIRONMENT.

For example, I have a razor page in the path AreasAdminPagesDashboardIndex.cshtml, and an accompanying javascript file AreasAdminPagesDashboardIndex.cshtml.js. This works great when ASPNETCORE_ENVIRONMENT is set to Development, but when set to Production, I get the following error in my browser: Failed to load resource: the server responded with a status of 404 (Not Found).

In addition to this, styles.css(which I assume is generated during the build process) also fails to load in the Production environment.

My script is included in the following way:


@section Scripts {
    <script src="~/Areas/Admin/Pages/Dashboard/Index.cshtml.js" asp-append-version="true"></script>
}

Additionally, after inspecting the publish folder, it seems the scripts are correctly placed in their file path: binReleasenet8.0publishwwwrootAreasAdminPagesDashboardIndex.cshtml.js

Any ideas about what might be causing this are welcome.

Svelte component in plain HTML

I have a function that returns the HTML code for a custom component. That code, together with more HTML code, is then rendered somewhere else with {@html codeToDisplay}.

My firsts two guesses where:

  1. Return the code for the component as I would write it in a Svelte file and hope for Svelte to do it’s magic
  2. Return the code for the component but using the special element svelte:component

I also checked out the Custom element API but it didn’t work.

I made a small REPL to see what I did.

So my question is: can Svelte render a custom component from valid HTML code?

Use object key values as keys on new object [closed]

Trying to get better with data mutating in vanilla JS and have not been successful here.

I am just trying to use the values of one object to create keys for another format.

Also tried things like string interpolation ${} etc, can someone please show my error? The example in comment is what I’m after so like

var = { x: 'left', y: 'top', z: 'front' } => becomes => {left: top, extra: { front: true }

but obviously struggling with syntax, thank you!

const obj1 = {
  aKey: 'a_value',
  bKey: 'b_value',
  cKey: 'c_value'
}

/************************* pseudo what I want to turn this into:
  obj2 = {
    [a_value]: [b_value],
    adhocKey: {
      [c_value]: true
    }
  }
*/

const obj2 = {
  obj1[aKey]: obj1[bKey],
  adhocKey: {
    obj1[cKey]: true
  }
}
console.log(obj1)

const obj3 = {
  obj1.aKey: obj1.bKey,
  adhocKey: {
    obj1.cKey]: true
  }
}
console.log(obj2)

See description details

JavaScript heap out of memory during npm install on Azure pipeline

I’m recently updating my angular projects from angular 16 to angular 17. npm install works perfectly with angular 17 on my laptop. But on Azure pipeline, it throws an error saying “FATAL ERROR: Reached heap limit Allocation failed – JavaScript heap out of memory”. How can I solve this?

In one repo, I solved this issue by changing “npm install” as a script to “npm install” as an in-built task: Npm@1.

But it doesn’t work in another repo. I also removed package-lock.json before npm install but it didn’t help.

AngularJS ngrepeat run function across 2 or more products

I have an angular app that lists out multiple products. Each item is added to the users cart through a function, selectProduct.

<div ng-repeat="item in items">
  <div>{{item.name}}</div>
  <div ng-click="selectProduct(item)">Add Product</div>
</div>

I want to be able to add 2 or more products (e.g. add baseball, baseball bat, baseball glove), by clicking one add product, sort of like a bundle. Problem is, I don’t have access to the original selectProduct function, so I have to develop custom javascript to make this happen.

In an ideal deal world, I want to do something like this
selectProduct(item1).then(selectProduct(item2));

Any thoughts on how I can make something like this work, knowing my limitations?

Thanks

Preserving Markdown Styling in XLSX Generation

I am attempting to generate an XLSX file from a JSON object, where one of the fields contains Markdown text. While generating the XLSX file, I want to preserve the styling present in the Markdown text. I’ve tried using the xlsx module, but I haven’t been successful in retaining the styling.

const data = [
    {
        id: 1,
        markdownField: "Testing **How** to format the *data* n1. Point 1n2. Point 2"
    },
    {
        id: 2,
        markdownField: "Another **example** of *Markdown* text n- Item 1n- Item 2"
    }
];

const XLSX = require('xlsx');

const ws = XLSX.utils.json_to_sheet(data);

const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Data');

XLSX.writeFile(wb, 'output.xlsx');

In the resulting XLSX file, the Markdown styling (e.g., bold, italic, list) is not retained. How can I preserve the Markdown styling when generating the XLSX file?

Also, I tried to convert markdown text to HTML and then generate xlsx but still no luck, Here is the generated html

Testing <strong>How</strong> to format the <em>data</em><ol><li>Point 1</li><li>Point 2</li></ol>

Sorting an array of objects by date with some dates being null

I have a huge array of objects called steamData that look like this:

 {
        "sid": 1690,
        "store_url": "https://store.steampowered.com/app/1690",
        "store_promo_url": null,
        "store_uscore": 69,
        "published_store": "2006-10-16",
        "published_meta": "2006-10-16",
        "published_stsp": "2006-10-16",
        "published_hltb": "2020-04-18",
        "published_igdb": "2006-09-01",
        "image": "https://steamcdn-a.akamaihd.net/steam/apps/1690/header.jpg",
        "name": "Space Empires V",
        "description": "Space Empires V is the latest edition in the Space Empires series. This new chapter completely updates the UI and takes ...",
        "full_price": 1999,
        "current_price": 499,
        "discount": 75,
        "platforms": "WIN",
        "developers": "Malfador Machinations",
        "publishers": "Strategy First",
        "languages": "English",
        "voiceovers": null,
        "categories": "Single-player,Multi-player",
        "genres": "Strategy",
        "tags": "Strategy,4X,Space,Sci-fi,Turn-Based,Singleplayer,Turn-Based Strategy,Multiplayer",
        "achievements": null,
        "gfq_url": "https://gamefaqs.gamespot.com/pc/927958-space-empires-v?ftag=MCD-06-10aaa1f",
        "gfq_difficulty": "Just Right-Tough",
        "gfq_difficulty_comment": "<a href="/games/rankings?platform=19&amp;genre=45&amp;list_type=diff&amp;dlc=1&amp;page=22&amp;game_id=927958&amp;min_votes=2#1114"><b>#1114</b></a> hardest PC strategy game (<a href="/games/rankings?platform=19&amp;list_type=diff&amp;dlc=1&amp;page=122&amp;game_id=927958&amp;min_votes=2#6145"><b>#6145</b></a> on PC, <b>#24997</b> overall)",
        "gfq_rating": 3.54,
        "gfq_rating_comment": "<a href="/games/rankings?platform=19&amp;genre=45&amp;list_type=rate&amp;view_type=1&amp;dlc=1&amp;page=16&amp;game_id=927958&amp;min_votes=2#818"><b>#818</b></a> lowest rated PC strategy game (<a href="/games/rankings?platform=19&amp;list_type=rate&amp;view_type=1&amp;dlc=1&amp;page=163&amp;game_id=927958&amp;min_votes=2#8199"><b>#8199</b></a> on PC, <b>#33932</b> overall)",
        "gfq_length": 68.6,
        "gfq_length_comment": "<a href="/games/rankings?platform=19&amp;genre=45&amp;list_type=time&amp;dlc=1&amp;page=2&amp;game_id=927958&amp;min_votes=2#119"><b>#119</b></a> longest PC strategy game (<a href="/games/rankings?platform=19&amp;list_type=time&amp;dlc=1&amp;page=12&amp;game_id=927958&amp;min_votes=2#618"><b>#618</b></a> on PC, <b>#1757</b> overall)",
        "stsp_owners": 75000,
        "stsp_mdntime": null,
        "hltb_url": "https://howlongtobeat.com/game?id=8846",
        "hltb_single": 10,
        "hltb_complete": null,
        "meta_url": "https://www.metacritic.com/game/pc/space-empires-v?ftag=MCD-06-10aaa1f",
        "meta_score": 68,
        "meta_uscore": 77,
        "grnk_score": 65,
        "igdb_url": "https://www.igdb.com/games/space-empires-v",
        "igdb_single": null,
        "igdb_complete": null,
        "igdb_score": 65,
        "igdb_uscore": 50,
        "igdb_popularity": 1.89
    },

I’m trying to sort this array by it’s published_meta date newest to oldest:

 if (!loading) {
    // Sort from oldest to youngest
    steamData.sort((a, b) => (b)?.published_meta.localeCompare((a)?.published_meta));

    // Get today as milliseconds
    let today = new Date().toLocaleDateString('en-CA');
    let todayMS = Date.parse(today);

    // Get index of closest element to today
    let closestIndex = steamData.reduce((acc, obj, index) => {
      let diff = Math.abs(Date.parse(obj?.published_meta) - todayMS);
      return acc.diff > diff ? { diff, index } : acc;
    }, { diff: Infinity, index: null }).index;

    // Move closest element to start of array
    steamData.unshift(newTrending.splice(closestIndex, 1));
  }

I keep running into the error “Cannot read properties of null (reading ‘localeCompare’)”

Some of the objects are have null as their published dates (published_meta seems to have the fewest of these). I thought optional chaining would fix this but it has not.

How can I sort the steamData array to use?

the endpoints like /logout isnt working with localhost 3000 but working with 3001

I am making an admin panel for my telegram bot using React and Nest.js

The logout endpoint should be handled by the backend server which is localhost:3000 (localhost:3001 is my frontend) but calling localhost:3001/auth/logout works and localhost:3000/auth/logout does not

using await fetch(`localhost:3001/auth/logout`, works but await fetch(`${process.env.REACT_APP_API_URL}/auth/logout`, doesnt work, it should work with 3000(backend) not 3001(frontend), its the same with all the other endpoints too.
 REACT_APP_API_URL=http://localhost:3000
const handleSignOut = async () => {
        await fetch(`${process.env.REACT_APP_API_URL}/auth/logout`, {
            method: 'GET',
            credentials: 'include' // necessary for cookies if sessions are used
        })
            .then(response => {
                if (response.ok) {
                    localStorage.removeItem('user'); // Clear local storage if used
                    sessionStorage.removeItem('user'); // Clear session storage if used
                    window.location.href = `http://localhost:3001/admin`; // Redirect after successful logout
                } else {
                    throw new Error('Logout failed with status: ' + response.status);
                }
            })
            .catch(error => {
                console.error('Logout failed:', error);
            });
    };
 @Get('logout')
    async logout(@Req() req, @Res() res, @Session() session) {
        req.session.destroy((err) => {
            if (err) {
                console.error('Session destruction failed:', err);
                res.status(500).json({ message: 'Failed to log out' });
            } else {
                res.redirect(`${process.env.REACT_APP_DASHBOARD_URL}/admin`);
            }
        });
    }

CORs is enabled still isnt working

JavaScript time subtraction only equals 0 [closed]

I am attempting to get the difference in time to print to screen

var start = new Date();
var end = new Date();

//code
start = new Date();
//code 
end = new Date();

<p>
  Time: <span>{(start.getTime()) - (end.getTime())}</span>
</p>

The only result I am getting is zero but if I just print out the start and end times, they are different numbers.

highcharts tooltip arrow – how to do dynamic positioning?

I have a bar-style high chart for which I am trying to position its tooltip to come on the left-hand side when hovering on the bar. Instead, the tooltip is coming over the bar on hover.
I want to make this positioning dynamic instead of hardcoded. I also want to add an arrow along the border of the tooltip to point to the right bar data from which the tooltip is originating.

Sharing the minimum code snippet that I have tried so far (due to code restrictions sharing policy):

tooltip: {
  useHTML: true,
    headerFormat: `<strong ></strong><table>`,
      formatter: function () {

        var result = "<strong >" + obj.getname() + "</strong><table>";
        for (var i = 0; i < placementTypeSeries.length; i++) {
          var point = placementTypeSeries[i];
          var name = point.name && point.name[0] ? point.name[0] : "N/A";
          var data =
            point.data && point.data[0] !== undefined
              ? point.data[0]
              : "N/A";

          let normalizedDataValue =
            ((data !== "N/A" ? data : 0) * 95) / maxDataValue;

          var color = point.color ? point.color : this.series.color;

          result +=
            '<tr><td style="color:black;">' +
            name +
            " </td>";
          result +=
            '<td style="padding:0 2px"><span style="border-radius:2px;height:18px; vertical-align:middle; margin:3px; display:inline-block; width:' +
            normalizedDataValue +
            "px; background-color:" +
            color +
            ';"></span></td>';
          result += '<td style="padding:0"><b>' + data + "</b></td></tr>";
        }
        return result;
      },

  footerFormat: "</table>",
    shared: true,
      positioner: function (labelWidth, labelHeight, point) {
        console.log({ labelWidth, labelHeight, point });

        return { x: 0, y: 0 }
      },
  followPointer: false,
}

This is how currently it looks like:
current_view

The console.log() for point outputs plotX, plotY, which I tried to use like this:

return { x: point.plotX, y: 0 }

But that is also not working.

This is how I want my tooltip arrow to look something like this:

to_achieve

I have tried all possible highchart properties and followed other existing examples but those are also not working. If anyone can help to provide the fix for this?

Thanks in advance!