Problem with an undefined file in ext.js (main.js)

I am on a project where there is a stage, dev and localhost. on stage and dev, when the page loads, I get an error enter image description here

it does not break anything, but you need to get rid of it, I changed the bootstrap file, but after the build it resets to its original state, as I understand it, this is a problem with ext.js itself, but what should I do, how to make sure that this error does not happen

Ag grid custom text editor with dropdown list

Ag grid currently does not support a cell editor that has capability to text edit and have a drop down list.

I would like to have a cell editor that user can edit by text AND have a drop down list to choose from as they type where user does not have choose from the drop down list.

I have looked at several solutions

But these solutions don’t allow the user to store values they typed into the cell. Has anyone tried to implement such custom cell editor for ag grid?

I have looked at several solutions

How do I send the following API POST request with JavaScript? [closed]

I need to send the following POST request with JavaScript (preferably with fetch() method since I am most familiar with it):

 POST /login?format={format} HTTP/1.1
    Host: authservice.priaid.ch
    Authorization: Bearer {api_key}:{hashed_credentials}

I know the api_key and took care of the hashed_credentials part already. (Here is more documentation on this API in case you need it.) I just need to send the fetch request, but don’t know how (I am very new to APIs).

I tried doing the following:

fetch('authservice.priaid.ch/login?format=json', {
      method: 'POST',
      headers: {
        Authorization: `Bearer {my_api_key}:{computedHashString}`,
      },
    })
      .then(response => response.json())
      .then(data => console.log('Success:', data))
      .catch(error => console.error('Error:', error));

but it returns an error:
POST http://127.0.0.1:5500/authservice.priaid.ch/login?format=json 405 (Method Not Allowed)

Can Vue devtools cause high CPU usage if app/tab left open for long time?

I have a Vue app where on one page all it does is sets an interval on mounted to fetch something from an API every minute. Now if I leave it like this for a long time, CPU usage starts creeping, while the app is doing nothing. In the performance tab in chrome dev tools, I recorded a 2 seconds timespan, and I see a lot of stuff that originates from backend.js which if I click I see the source is vue-devtools related: handshake, sendListening, postMessage. My suspicion is that this is what’s causing the high CPU usage as nothing else is really happening as seen in the performance tab. I noticed the same although in production from the same browser, where devtools inspection is disabled – but the devtools extension was still in by browser, hence my suspicion.

I will test it in other browser, with and without extensions (so like open the app and just leave it for a day), but I can’t really think of anything else, since the app is literally not doing anything other than doing one request every minute. If I refresh the tab the symptom goes away. My first suspicion because of this was maybe some classic memory leak or such, but memory footprint is roughly the same after I refreshed – and again, the page does nothing computation heavy.

chrome performance tab drilldown

Delete button and Add Drink not working as expected

1.I’ve got a purchase history screen where you can see all the orders. There’s a delete button for each order, but when I tap it… nothing happens. The order just sits there, mocking me.

2.I’ve also got this “Add Drink” screen where you’re supposed to be able to pick a drink and its size. But when I tap on a drink, it’s like the app is ignoring me. No selection, no nothing.

const handleDeleteOrder = useCallback((orderNumber) => {
  console.log('Delete button pressed for order:', orderNumber);
  Alert.alert(
    "Delete Order",
    "Are you sure you want to delete this order?",
    [
      { text: "Cancel", style: "cancel" },
      { 
        text: "OK", 
        onPress: () => {
          console.log('Deleting order:', orderNumber);
          setPurchaseHistory(prevHistory => {
            console.log('Previous history:', prevHistory);
            const updatedHistory = prevHistory.filter(order => order.orderNumber !== orderNumber);
            console.log('Updated history:', updatedHistory);
            return updatedHistory;
          });
        }
      }
    ]
  );
}, [setPurchaseHistory]);

const handleAddDrink = useCallback((item, size) => {
  if (!prices[item.category] || !prices[item.category][size]) {
    console.error(`Price not found for ${item.name} (${size})`);
    Alert.alert('Error', `Price not available for ${item.name} (${size})`);
    return;
  }

  setSelectedDrink(item);
  setSelectedDrinkSize(size);
}, [prices]);
// In the render function
<TouchableOpacity
  style={styles.deleteButton}
  onPress={() => handleDeleteOrder(purchase.orderNumber)}
>
  <Text style={styles.deleteButtonText}>Delete</Text>
</TouchableOpacity>

<TouchableOpacity
  key={size}
  style={[
    styles.sizeButton,
    selectedDrink === item && selectedDrinkSize === size && styles.selectedSizeButton
  ]}
  onPress={() => handleAddDrink(item, size)}
>
  <Text style={styles.sizeButtonText}>{size}</Text>
</TouchableOpacity>

I’ve verified that the handleDeleteOrder function in _layout.js is being called using console.log statements, but the state isn’t updating as expected For the Add Drink functionality, I’ve checked that the handleAddDrink function is being called, but it’s not updating the UI or preparing the drink for addition. I’ve made sure that the setPurchaseHistory function is being passed down to the PriceComponent correctly.

Translate rotated element relative to document

I’m trying to translate a rotated element but when I do so, the element translates considering the rotated axis. I’m trying to translate the element considering the axis pre rotation. How do I do that?

I’ve created a jsfiddle to illustrate the issue : https://jsfiddle.net/c03wpyuz/6/

$(document).ready(() => {

  var tx = 0;
  var ty = 0;
  var ag = 0;
  var el = $('#test');

  setTimeout(() => {
       ag = 45;
       el.css('transform', 'rotate('+ag+'deg)');
  }, 1000);

  setTimeout(() => {
       tx = 100;
       ty = 0;
       el.css('transform', 'rotate('+ag+'deg) translate3d('+tx+'px, '+ty+'px, 0)');
  }, 2000);


});

The element will rotate after 1 second then after 2 seconds it will translate. The issue is that I’m only translating it over the X axis but the axis is then rotated.

Issue with changing feature colors in 3D using UniqueValueRenderer in SceneView

I’m facing an issue while trying to apply a UniqueValueRenderer on a 3D FeatureLayer in a SceneView. My goal is to change the color of the features based on an alert field coming from a CSV file.

The interesting part is that, as the date on the timeslider changes, the color filling the polygons changes based on the alert value.

I have managed to get it working perfectly in 2D (MapView), but when switching to 3D, the layer is not displayed, and I get the following error in the developer tab:

Graphic in layer 19227fb6798-layer-0 has no symbol and will not render.

In some combinations I’ve tried by changing parameters in the code below, I managed to display the layer at some point, but all the entities had the same color.

What I’m doing:

  1. Loading a CSV file containing alert data (values like “A5”, “A4”, etc.) linked to an ID (comarca_sg) field in the layer.

  2. Using a UniqueValueRenderer to change the color of the features based on the comarca_sg field and the alert value from the CSV.

  3. The function getColorBasedOnAlert assigns a color depending on the alert value (“A5” = dark red, “A4” = light red, etc.).

The problem:

• In 2D, the colors change correctly for each feature.
• In 3D (SceneView), **the layer is not displayed ** or all the features render with the same color, even though the same UniqueValueRenderer is applied.

Here’s the code:

require([
  "esri/Map",
  "esri/views/MapView",
  "esri/views/SceneView",
  "esri/layers/FeatureLayer",
  "esri/widgets/TimeSlider",
  "esri/geometry/Extent",
  "esri/core/watchUtils",
  "esri/request"
], function(Map, MapView,SceneView, FeatureLayer, TimeSlider, Extent, watchUtils, esriRequest) {

  // Crear el mapa y la vista de escena
  var map = new Map({
    basemap: "gray-vector", // Basemap actualizado
    ground: "world-elevation"
  });

// Create the SceneView and set initial camera
  const view = new SceneView({
    container: "viewDiv",
    map: map,
    camera: {
      position: {
        latitude: 40.5,
        longitude: -3.7,
        z: 3500000
      },
      tilt: 0,
      heading: 1
    },


    highlightOptions: {
      color: "cyan"
    }
  });


// VISOR EN 2D
// const view = new MapView({
//   container: "viewDiv",
//   map: map,
//   zoom: 5, // Ajusta el zoom para un nivel adecuado de detalle
//   center: [-3.7038, 40.4168] // Coordenadas de Madrid, España (longitud, latitud)
// });

layer.elevationInfo = {
  mode: "relative-to-ground",
  offset: 50,
  unit: "meters"
}

  // Cargar la capa COMARCAS
  var featureLayer = new FeatureLayer({
      url: "url_to_layer", // Sorry but it is private
      outFields: ["*"]
  });




  featureLayer.when(function() {
    console.log("Capa cargada correctamente:");
}, function(error) {
    console.error("Error al cargar la capa.", error);
});

  map.add(featureLayer);

  // Cargar el CSV con los datos de simbología y fecha
  esriRequest("path_to_file", {  // Sorry again but it is private
      responseType: "text"
  }).then(function(response) {


        console.log("CSV cargado con éxito."); // Verifica si el CSV fue cargado
        const csvData = parseCSV(response.data); // Parsear el CSV

        // Crear y configurar el TimeSlider
        var timeSlider = new TimeSlider({
            container: "timeSliderDiv",
            view: view,
            mode: "instant", // Selecciona una fecha a la vez
            fullTimeExtent: {
                start: new Date(2020, 11, 28), //OJO QUE LOS MESES VAN DE 0 A 11
                end: new Date(2023, 11, 31)
            },
            stops: {
                interval: {
                    value: 7,
                    unit: "days"
                }
            }
        });

        view.ui.add(timeSlider, "bottom-left");

        // Vincular el cambio de fecha del TimeSlider con la capa
        timeSlider.watch("timeExtent", function(timeExtent) {
            const selectedDate = timeSlider.timeExtent.end;


            // Filtrar el CSV para obtener los elementos correspondientes a la fecha seleccionada
            const filteredData = csvData.filter(row => {
                return new Date(row.fecha).toDateString() === selectedDate.toDateString();
            });



            // Si hay datos correspondientes a esa fecha, actualizar simbología
            if (filteredData.length > 0) {

                updateLayerSymbology(filteredData);
            } else {
                console.log("No se encontraron datos para la fecha seleccionada.");
            }
        });

// Función para actualizar la simbología en la capa
function updateLayerSymbology(data) {
  const uniqueValues = data.map(function(element) {

      return {
          value: element.comarca_sg,  // Asumimos que "id" es el campo que relaciona los elementos del CSV con los polígonos en la capa
          symbol: {
              type: "polygon-3d",  // Tipo de símbolo para polígonos 3D
              symbolLayers: [{
                  type: "extrude",
                  size: 5,
                  material: {color: getColorBasedOnAlert(element.alerta)},  // Asignar el color según la alerta
                  outline: { color: "black" }
              }]
          }
      };
  });


console.log("Valores únicos aplicados a los polígonos:", uniqueValues);



  const renderer = {

    type: "uniqueValue",
    field: "comarca_sg",
    uniqueValueInfos: uniqueValues,

};

  // Asignar el renderer a la capa
  featureLayer.renderer = renderer;
}


        // Función para obtener el color basado en el valor de alerta
        function getColorBasedOnAlert(alerta) {
          alerta = alerta.trim();
             // Verificar el valor de alerta
          if (alerta === "A5") {
              return "#d73027"; // Rojo oscuro
          } else if (alerta === "A4") {
              return "#fc8d59"; // Rojo claro
          } else if (alerta === "A3") {
              return "#fee08b"; // Amarillo
          } else if (alerta === "A2") {
              return "#d9ef8b"; // Amarillo verdoso
          } else if (alerta === "A1") {
              return "#91cf60"; // Verde claro
          } else if (alerta === "A0" || alerta === "NO ALERTA") {
              return "#1a9850"; // Verde intenso
          } else {
              return "#1a9850"; // Verde por defecto para valores desconocidos
          }
        }

        // Función para parsear el CSV
        function parseCSV(csvText) {
          const rows = csvText.split("n").map(row => row.trim()); // Eliminar espacios innecesarios
          const headers = rows[0].split(";").map(header => header.trim()); // Obtener los encabezados y eliminar espacios



          // Mapear los encabezados a los índices que necesitamos
          const indexId = headers.indexOf("comarca_sg");
          const indexFecha = headers.indexOf("date");
          const indexAlerta = headers.indexOf("riesgo");

          return rows.slice(1).map(row => {
              const columns = row.split(";").map(item => item.trim()); // Dividir por punto y coma
              return {
                  comarca_sg: columns[indexId],
                  fecha: new Date(columns[indexFecha]),
                  alerta: columns[indexAlerta]
              };
          });
      }


    }).catch(function(error) {
        console.error("Error al cargar el archivo CSV:", error); // Mostrar error en caso de que el CSV no se cargue
    });


  }); // LLAVES DEL FIN DEL CODIGO

Questions:

  1. Is there anything different I should consider when applying a UniqueValueRenderer in a SceneView compared to a MapView?

  2. Could there be a limitation or difference in how renderers are applied in 3D?

  3. I’m sure there is an error in the code that prevents the layer from displaying, but I can’t locate it.

I would appreciate any advice or suggestions on how to solve this problem. Thanks in advance!

What I’ve tried:

• Verified that the alert values are passed correctly using console.log().
• Tried removing the defaultSymbol to ensure it wasn’t overriding the renderer.
• Ensured that the comarca_sg field is correctly aligned between the CSV and the layer.
• I placed the layer in a scene view in AGOL, and it displays without issues, allowing me to visualize unique colors for unique values.

How to create multiple javascripts have the same notification

Here are two JavaScripts. There is also a notification script.
I want to combine two javascripts in one and have both javascripts show the same notification.

This is the two different javascripts with the same notification.

<script>
function copy(that){
  var text = that.textContent;
  var input = document.getElementById('cb');
  input.value = input.value + text +'n';
  var inp =document.createElement('input');
document.body.appendChild(inp)
inp.value =that.textContent
inp.select();
    document.execCommand('copy',false);

var notification = document.getElementById('symc');
    notification.style.display = 'block';
    setTimeout(() => {
        notification.style.display = 'none';
     }, 1000);
}
</script>

<script>
function co() {
  var input = document.getElementById("cb");
  navigator.clipboard.writeText(input.value);

var notification = document.getElementById('symc');
    notification.style.display = 'block';
    setTimeout(() => {
        notification.style.display = 'none';
     }, 1000);
}
</script>

<span id="symc">Copied</span>

<div id="ca">
<input id="cb">
<button onclick="co()">Copy</button>
</div>

This is the notification script

var notification = document.getElementById('symc');
    notification.style.display = 'block';
    setTimeout(() => {
        notification.style.display = 'none';
     }, 1000);

Please help me how can I mix two script in one js area…

<script>

</script>

Thanks.

ExtendScript Premier Pro Automation

This is the project screenshot,

I am working on Premier Pro Automation Project where I need to make my work simple by using extend script. So I can just replace paths for media and render it automatically.

My Requrements:

I want to replace Video in V3
Add fade in transition in the markers in V3
Change last three text layers
Change subtitle
Then render to specific path

Sequence Name: 60 Johnstone Street, Peakhurst

New Video Path = D:/Satish Kumar K/A4 NISD/PP Template/Johnstone-20240920T055442Z-001/Johnstone/Assests/Friends_On_A_Meadow_original_177140.mov

My code is below:

// Replace Video in V3
var newMediaPath = "D:/Satish Kumar K/A4 NISD/PP Template/Johnstone-20240920T055442Z-001/Johnstone/Assests/Friends_On_A_Meadow_original_177140.mov";

function replaceClipInV3(newMediaPath) {
    var sequence = app.project.activeSequence;
    if (!sequence) {
        $.writeln("No active sequence found.");
        return;
    }

    var videoTrack = sequence.videoTracks[2]; // V3 is index 2
    var clip = videoTrack.clips[0]; // Assume first clip on V3
    if (clip) {
        clip.projectItem.replaceFootage(newMediaPath);
        $.writeln("Replaced clip on V3 with " + newMediaPath);
    }
}

replaceClipInV3(newMediaPath);

// Add Fade-In Transitions
function addFadeInToMarkers(trackIndex) {
    var sequence = app.project.activeSequence;
    var videoTrack = sequence.videoTracks[trackIndex];
    var clip = videoTrack.clips[0]; // Assume first clip on V3

    for (var j = 0; j < sequence.markers.numMarkers; j++) {
        var marker = sequence.markers.getMarkerAt(j);
        if (clip.start.seconds <= marker.start.seconds && clip.end.seconds >= marker.start.seconds) {
            clip.components[1].properties[0].setValueAtTime(0, marker.start.seconds); // Apply fade-in at marker
            $.writeln("Applied fade-in at marker.");
        }
    }
}

addFadeInToMarkers(2); // V3 is index 2

// Change Last Three Text Layers
function updateTextLayers(newTexts) {
    var sequence = app.project.activeSequence;
    var textTrack = sequence.videoTracks[3]; // Assume text layers are on V4

    var clipCount = textTrack.clips.numItems;
    for (var i = clipCount - 3; i < clipCount; i++) {
        var clip = textTrack.clips[i];
        clip.components[1].properties[0].setValue(newTexts[i - (clipCount - 3)]);
        $.writeln("Updated text layer.");
    }
}

var newTexts = ["New Text 1", "New Text 2", "New Text 3"];
updateTextLayers(newTexts);

// Change Subtitle
function updateSubtitle(newSubtitle) {
    var sequence = app.project.activeSequence;
    var subtitleTrack = sequence.videoTracks[4]; // Assume subtitles are on V5
    var subtitleClip = subtitleTrack.clips[0]; // Assume first clip is the subtitle

    subtitleClip.components[1].properties[0].setValue(newSubtitle);
    $.writeln("Updated subtitle.");
}

updateSubtitle("New subtitle text.");


Can anyone help me to fix the error and it should run smoothly. 

My main aim is to Replace video, Add facein effects in the markers, Change Text layer, change subtitles,add music and then render to specific path. 

Thank you and looking forward for your answers on this. 

It showed me
"ReferenceError: clip.projectItem.replaceFootage is not a function"

THen I changed the codes to below: 

// Define the new media path
var newMediaPath = "D:/Satish Kumar K/A4 NISD/PP Template/Johnstone-20240920T055442Z-001/Johnstone/Assests/Friends_On_A_Meadow_original_177140.mov";

function replaceClipInV3(newMediaPath) {
    var sequence = app.project.activeSequence; // Get the active sequence
    if (!sequence) {
        $.writeln("No active sequence found.");
        return;
    }

    // Access V3 track (track index 2)
    var videoTrack = sequence.videoTracks[2];
    if (videoTrack.clips.numItems > 0) {
        var clip = videoTrack.clips[0]; // Access the first clip on V3
        var projectItem = clip.projectItem; // Get the ProjectItem of the clip
        
        // Check if the projectItem is valid and replace footage
        if (projectItem) {
            projectItem.replaceFootage(newMediaPath);
            $.writeln("Replaced clip in V3 with " + newMediaPath);
        } else {
            $.writeln("No ProjectItem found for the clip in V3.");
        }
    } else {
        $.writeln("No clips found in V3.");
    }
}

// Replace the clip in V3
replaceClipInV3(newMediaPath);

But not able to srt this out .

Thank you

Jest configuration for Angular 15 throwing : Missing semicolon error for test case

I’m trying to configure Jest in my Angular 15 application.

Jest config:

const jestPreset = require('jest-preset-angular/jest-preset');
const { globals } = jestPreset;
const tsjest = globals['ts-jest'];

const tsjestOverrides = {
  ...tsjest,
  tsconfig: '<rootDir>/tsconfig.spec.json'
};
const globalOverrides = {
  ...globals,
  'ts-jest': { ...tsjestOverrides }
};

module.exports = {
  ...jestPreset,
  globals: { ...globalOverrides },
  preset: 'jest-preset-angular',
  setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
  globalSetup: 'jest-preset-angular/global-setup',
    reporters: [
    "default",
    ["./node_modules/jest-html-reporter", {
      pageTitle: "Test Report"
    }]
  ]
};

tsconfig.spec.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
      "outDir": "./out-tsc/spec",
      "types": [
          "jest",
          "node",
          "googlemaps",
          "offscreencanvas"
      ],
      "esModuleInterop": true,
      "emitDecoratorMetadata": true,
      "module": "CommonJs",
  },
  // "files": ["./setup.jest.ts"],
  "include": [
      "projects/design/src/app/**/*.spec.ts",
      "projects/design/src/app/**/*.d.ts"
  ]
}

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "paths": {
      "api-management": [
        "dist/api-management/api-management",
        "dist/api-management"
      ],
      "lib-ui-component": [
        "dist/lib-ui-component/lib-ui-component",
        "dist/lib-ui-component"
      ],
      "@api/*": ["./projects/api-management/src/*"],
      "@design/*": ["./projects/design/src/app/design/*"],
      "@lib-ui/*": ["./projects/lib-ui-component/src/*"]
      
    },
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "strict": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,

    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "importHelpers": true,
    "target": "ES2022",
    "module": "es2020",
    "lib": ["es2018", "es2019", "dom"],
    "useDefineForClassFields": false
  },
  "angularCompilerOptions": {
    "extendedDiagnostics": {
      "checks": {
        "optionalChainNotNullable": "suppress"
      }
    },
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true,
    "suppressImplicitAnyIndexErrors": true,
    "strictPropertyInitialization": false,
  }
}

setup-jest.ts

import 'jest-preset-angular/setup-jest';

Test file

describe('BatteryConfigurationComponent', () => {
  let storeMock: Store<DesignState>;
  let matDialogMock: MatDialog;
  let openNotificationServiceMock: openNotificationService;
  let SettingsServiceMock: SettingsService;
  let ViewContainerRefMock: ViewContainerRef;
  let ComponentFactoryResolverMock: ComponentFactoryResolver;
  let TranslateServiceMock: TranslateService;
  let component: BatteryConfigurationComponent;
  
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [component],
      providers: [storeMock, matDialogMock, openNotificationServiceMock, SettingsServiceMock, ViewContainerRefMock, ComponentFactoryResolverMock, TranslateServiceMock],
    });
  })
  afterEach(() => {
    jest.clearAllMocks();
  });
});

Error I am facing is:

enter image description here

I think my config is not able to understand Typescript.

Out of Memory Error in Browser When Loading Large DICOM Dataset with Cornerstone3D

I’m working on an Angular application using Cornerstone3D to process and render DICOM images. The DICOM images I am working with are quite large. For example, one CT image set has 4137 slices with a resolution of 1024×1024, resulting in a total file size of 8.14 GB.

Here’s a general outline of how I handle the data:

I receive the DICOM data from the server.
I parse the data using the dicomParser JavaScript library.
The parsed dataset is then stored in a cache for future use.
Here’s a simplified example of the code I use to manage the datasets:

let loadedDataSets: Record<string, { dataSet: DataSet; cacheCount: number }> = {};

dataset = dicomParser.parseDicom(buffer);
dataSetCacheManager.create(uri, dataset);

function create(uri: string, dataSet: DataSet, multiFrame: boolean) {
  loadedDataSets[uri] = {
    dataSet: dataSet,
    cacheCount: 1
  };
}
The DataSet structure looks like this:

export interface DataSet {
   byteArray: ByteArray;
   byteArrayParser: ByteArrayParser;
   elements: {
     [tag: string]: Element;
   };
   warnings: string[];

   uint16: (tag: string, index?: number) => number | undefined;
   int16: (tag: string, index?: number) => number | undefined;
   uint32: (tag: string, index?: number) => number | undefined;
   int32: (tag: string, index?: number) => number | undefined;
   float: (tag: string, index?: number) => number | undefined;
   double: (tag: string, index?: number) => number | undefined;
   numStringValues: (tag: string) => number | undefined;
   string: (tag: string, index?: number) => string | undefined;
   text: (tag: string, index?: number) => string | undefined;
   floatString: (tag: string) => number | undefined;
   intString: (tag: string) => number | undefined;
   attributeTag: (tag: string) => string | undefined;
}

export type ByteArray = Uint8Array | Buffer;

The Problem:

When the total size of the loaded data hits around 8.5 GB (based on Heap Snapshot), the browser crashes and throws an “Out of Memory” error.

I understand that handling such large data entirely in RAM might not be feasible, but I’m wondering if there are more memory-efficient ways to store or manage the DICOM datasets in the browser. Is there any strategy to offload or segment the data in a more RAM-efficient manner, another approach to mitigate the memory issue?

Any suggestions or alternative approaches would be greatly appreciated.

Using Heap Snapshots: I’ve used Chrome’s developer tools to take heap snapshots, which confirmed that the JSArrayBufferData is consuming about 8.5 GB when the crash occurs. This was unexpected because the system has more RAM available.

Exploring IndexedDB: I considered using IndexedDB as an alternative to store parts of the DICOM data, but due to the structure of the DICOM dataset (especially with its byteArrayParser functions for accessing binary data), it’s not straightforward to offload the data without significant changes to the parsing and rendering flow.

Thymeleaf to Html conversion [closed]

private convertThymeleafToHtml(thymeleafTemplate: string): string {
    const parser = new DOMParser();
    const doc = parser.parseFromString(thymeleafTemplate, 'text/html');

    const walker = document.createTreeWalker(
      doc,
      NodeFilter.SHOW_ELEMENT,
      null,
      false
    );

    const thymeleafAttributes = ['th:text', 'th:href', 'th:each', 'th:if', 'th:unless', 'th:case', 'th:choose', 'th:fragment', 'th:object', 'th:attr'];

    let currentNode: Element | null = walker.nextNode() as Element;
    
    while (currentNode) {
      thymeleafAttributes.forEach(attr => {
        if (currentNode.hasAttribute(attr)) {
          const attrValue = currentNode.getAttribute(attr)!;
          currentNode.setAttribute(`data-${attr}`, attrValue);
          currentNode.removeAttribute(attr);

          // Handle th:text specifically to add placeholder span
          if (attr === 'th:text') {
            const placeholder = `${${attrValue.replace(/${(.*?)}/, '$1')}}`;
            const formattedPlaceholder = this.nonEditablePlaceholderSpan(placeholder);
            currentNode.innerHTML = ''; // Clear existing innerHTML
            currentNode.appendChild(formattedPlaceholder);
          }
        }
      });
      currentNode = walker.nextNode() as Element;
    }

    return doc.body.innerHTML; // Return the inner HTML of the body
  }

I want to convert it back to html, need most efficient traversal code. and alternative method to that can be sued tml to thymleaf and thymleaf to html conversion ..