checking for CSP and iframe embedding – Chrome Extension

I’m writing a very simple Chrome Extension that aims to check whether an endpoint could
be embedded as an Iframe
If it is – write “Success” in green in dev console, if not write it in red.

More context –
My goal is here to check whether an iframe could be embedded in my local extension without violating the CSP.

So once the user click on “Check Endpoint” the checking process will go in the background.

Currently i’m using ChatGPT, and my code did append a new iframe with the designated endpoint to the page, but than either it –
Blocked by inline script policy or providing False Positive whether it got embedded or not.

This is the current code the ChatGPT provide me with –

function checkEndpointCommunication(endpoint, button) {
    console.log(`Checking communication for endpoint: ${endpoint}`);

    let communicationEstablished = false;

    // Create an iframe and embed it
    const iframe = document.createElement("iframe");
    iframe.src = endpoint;
    iframe.style.display = "none"; // Hide the iframe from view
    document.body.appendChild(iframe);

    // Timeout to handle embedding failures
    const timeout = setTimeout(() => {
        if (!communicationEstablished) {
            console.warn(`[TIMEOUT] Iframe communication timeout for: ${endpoint}`);
            button.classList.remove("default", "green");
            button.classList.add("red"); // Mark as failure
            cleanup();
        }
    }, 5000); // 5-second timeout

    // Cleanup function
    const cleanup = () => {
        if (iframe.parentNode) iframe.remove();
        clearTimeout(timeout);
    };

    // Iframe onload handler
    iframe.onload = () => {
        clearTimeout(timeout); // Cancel timeout if iframe loads
        try {
            // Try to access the iframe content
            const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
            const iframeBody = iframeDocument.body;

            if (iframeBody) {
                console.log(`[INFO] Iframe content loaded successfully for: ${endpoint}`);
                communicationEstablished = true;
                button.classList.remove("default", "red");
                button.classList.add("green"); // Mark as success
            } else {
                console.warn(`[FAILURE] Iframe content is inaccessible for: ${endpoint}`);
                button.classList.remove("default", "green");
                button.classList.add("red"); // Mark as failure
            }
        } catch (err) {
            console.warn(`[ERROR] Iframe access failed for: ${endpoint}, Error: ${err.message}`);
            button.classList.remove("default", "green");
            button.classList.add("red"); // Mark as failure
        } finally {
            cleanup();
        }
    };

    // Iframe onerror handler
    iframe.onerror = () => {
        console.warn(`[FAILURE] Iframe failed to load for: ${endpoint}`);
        button.classList.remove("default", "green");
        button.classList.add("red"); // Mark as failure
        cleanup();
    };
}

Incorrect format problem when converting a BMP image file from Base-64 to binary

I am trying to convert the Base-64 data contained in the “data” returned by toDataURL of a fabric.Canvas into a file with its corresponding extension (BMP). The result is a “The file is not in the correct format” error.

The steps I follow are the following.

  1. I get the dataURL variable from the fabric.Canvas with the toDataURL method.

    dataURL = canvas.toDataURL({
    format: ‘bmp’,
    quality: 1.0

});

  1. I extract only the string that contains the “data”.

    dataURLto64 = dataURL.substr(dataURL.lastIndexOf(‘,’) + 1, dataURL.length –
    dataURL.lastIndexOf(‘,’) – 1);

  2. The above is done on the client. On the server I needed to save the string in segments in a TXT text file. I have verified that the final content of the text file is identical to the original dataURLto64 (in Base-64).

  3. I extract the content of the text file.

string strtextfile64 = File.ReadAllText([path]);

  1. I convert that string into a byte array with the method

    byte[] fileBinary = null;

    fileBinary = Convert.FromBase64String(strtextfile64);

    File.WriteAllBytes([path], fileBinary);

I have verified that both, dataURLto64 and strtextfile64 have the same characters and the same number.
To verify that the Base-64 string is correct, I have included the following verification on the server.

 int mod4 = strtextfile64.Length % 4;   

 if (mod4 > 0) {
    strtextfile64 += new string('=', 4 - mod4);
 }

It was not necessary to modify strtextfile64 because mod4 = 0.

I am attaching two text files in which the initial (client) and final (server) Base-64 strings are contained.

Inicial cliente
Final servidor

Could someone tell me the reason why that Base-64 data converted to binary data does not comply with the original BMP format from the original BMP file created from the fabric.Canvas?

How to add user’s sprite sheet with phaser framework when he logs in to the websocket connection?

I created a logic to add new users’ sprite sheet and than remove them if they logged out from the page. It works like I want, problem is when they logged in back, their sprite sheet is not appears in the page. How can I make their sprite sheet appear when they logged in back?

I tried to remove their record from the slicer so inactiveUsers array would cleaned after deletion of sprite sheets. I thought that would cause sprite sheet to added if user comes back but it didn’t worked.

Update method where I created this logic,

update(time, delta) {
        const state = store.getState();
        const avatar = state.communities.avatar;
        const inactiveUsers = state.websocket.inactiveUsers;
        this.activeUsers = state.communities.activeUsers;
        
        const currentUser = this.activeUsers.find((user) => user.id === this.userid);
    
        // Ensure we only act on the current user's character
        if(!currentUser) return;
    
        const distance = Phaser.Math.Distance.Between(
            this.character?.x,
            this.character?.y,
            this.targetX,
            this.targetY
        );
    
        if(distance > 5) {
            // Move the character smoothly towards the target
            const angle = Phaser.Math.Angle.Between(
                this.character.x,
                this.character.y,
                this.targetX,
                this.targetY
            );
            this.character.x += Math.cos(angle) * this.speed * (delta / 1000);
            this.character.y += Math.sin(angle) * this.speed * (delta / 1000);
    
            // Adjust character orientation based on movement direction
            if(this.targetX < this.character.x) {
                this.character.setScale(avatar === 'defaultgirl' ? -1.2 : -1.2, 1.2);
            }
            else {
                this.character.setScale(avatar === 'defaultgirl' ? 1.2 : 1.2, 1.2);
            }
        }
        else {
            // Stop movement animation when the character reaches the target
            if(this.character?.anims?.isPlaying) {
                this.character.stop(`walk_${avatar}`);
                this.character.setTexture(`${avatar}idle`, 0);
            }
        }

        // Sync other users' positions from activeUsers
        this.activeUsers.forEach((user) => {
            if(user.id !== this.userid) {
                const { avatar: otherAvatar, character_position_x, character_position_y } = user;

                // Use spriteMap to track the sprite for each user
                let otherCharacters = this.spriteMap[user.id];
                if(!otherCharacters) {
                    otherCharacters = this.add.sprite(this.cameras.main.width / 2, this.cameras.main.height / 2, `${otherAvatar}idle`);
                    this.spriteMap[user.id] = otherCharacters; // Save the reference
                    otherCharacters.setDepth(1);
                    otherCharacters.setScale(1.2);
                    otherCharacters.setOrigin(0.5, 0.9);
                    otherCharacters.play(`walk_${otherAvatar}`);
                }
    
                // Update position if valid
                if(character_position_x && character_position_y) {
                    const distanceToTarget = Phaser.Math.Distance.Between(
                        otherCharacters.x,
                        otherCharacters.y,
                        character_position_x,
                        character_position_y
                    );
    
                    if(distanceToTarget > 5) {
                        const angleToTarget = Phaser.Math.Angle.Between(
                            otherCharacters.x,
                            otherCharacters.y,
                            character_position_x,
                            character_position_y
                        );
                        otherCharacters.x += Math.cos(angleToTarget) * this.speed * (delta / 1000);
                        otherCharacters.y += Math.sin(angleToTarget) * this.speed * (delta / 1000);
                    }
                    else {
                        otherCharacters.setTexture(`${otherAvatar}idle`, 0);
                    }
                }

                if(inactiveUsers.includes(user.id)) {
                    otherCharacters.destroy();
                    delete this.spriteMap[user.id];
                }

                //this.dispatch(removeFromInactiveUsersArray(user.id));
            }
        });
    
        // Update the position of the speech bubble
        if (this.targetX) {
            const bubbleX = this.character?.x - 0; // Adjust for center alignment
            const bubbleY = this.character?.y - 80; // Position above the character
            this.speechBubbleElement.setPosition(bubbleX, bubbleY);
        }
    }

Google apps script to limit access on edit so that only the owner and the one who edited the cell have access

Hello I am looking for a specific functionality in google sheets. I tried to make a script that on every edit, if the cell is empty everyone has access to edit it. If someone edits it, only that person and the owner can edit it. I have to mention that every user is anonymous, and I can’t get the emails. This script’s scope is to limit the access of an edited cell so that users can’t modify each other’s cells, the first who types in that cells has control over it.

I tried to use a workaround with the protections, but that worked partially, nobody could edit the owner’s cells but everyone could write on top of each other’s cells. Got errors on the trigger for every person except the owner: you can’t remove yourself as an editor and Cannot read properties of undefined (reading ‘columnStart’) and the parameters (String,number) doesn’t correspond with the signature of the method SpreadsheetApp.Spreadsheet.getRange. at onEdit

This is the code I tried to edit it to make it work. The code was taken from this stackoverflow post and was written by Wim den Herder: Get the user that changed specific cell

// Test it with colors
// var edittedBackgroundColor = "RED"; // makes the change visible, for test purposes
// var availableBackgroundColor = "LIGHTGREEN"; //  makes the change visible, for test purposes

function onEdit(e) {
  Logger.log(JSON.stringify(e));
  var alphabet = "abcdefghijklmnopqrstuvwxyz".toUpperCase().split("");
  var columnStart = e.range.columnStart;
  var rowStart = e.range.rowStart;
  var columnEnd = e.range.columnEnd;
  var rowEnd = e.range.rowEnd;
  var startA1Notation = alphabet[columnStart-1] + rowStart;
  var endA1Notation = alphabet[columnEnd-1] + rowEnd;
  var range = SpreadsheetApp.getActive().getRange(startA1Notation + ":" + endA1Notation);

  if(range.getValue() === "") {
    Logger.log("Cases in which the entry is empty.");
    if(typeof availableBackgroundColor !== 'undefined' && availableBackgroundColor) 
      range.setBackground(availableBackgroundColor)
    removeEmptyProtections();
    return;
  }

  // Session.getActiveUser() is not accesible in the onEdit trigger
  // The user's email address is not available in any context that allows a script to run without that user's authorization, like a simple onOpen(e) or onEdit(e) trigger
  // Source: https://developers.google.com/apps-script/reference/base/session#getActiveUser()

  var protection = range.protect().setDescription('Cell ' + startA1Notation + ' is protected');
  if(typeof edittedBackgroundColor !== 'undefined' && edittedBackgroundColor)
    range.setBackground(edittedBackgroundColor);

  // Though neither the owner of the spreadsheet nor the current user can be removed
  // The next line results in only the owner and current user being able to edit

  protection.removeEditors(protection.getEditors());
  Logger.log("These people can edit now: " + protection.getEditors());

  // Doublecheck for empty protections (if for any reason this was missed before)

  removeEmptyProtections();
}

function removeEmptyProtections() {
  var ss = SpreadsheetApp.getActive();
  var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
  for (var i = 0; i < protections.length; i++) {
    var protection = protections[i];
    if(! protection.getRange().getValue()) {
      Logger.log("Removes protection from empty field " + protection.getRange().getA1Notation());
      protection.remove();
    }
  }
  return;
}

function isEmptyObject(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }
    return JSON.stringify(obj) === JSON.stringify({});
}

Why am I not receiving transcription results from Google Speech API in my React Native app?

I am building a React Native app that records audio on an Android device, streams it to my native module, and then sends the recorded audio to the Google Speech API for transcription. However, despite getting a response from the Google Speech API, I am not able to retrieve any transcription text. The API response includes a status: 429, but no transcription data is returned.

Here’s the code I’m using in my React Native app:
React Native Component (SpeechMode.js):

import React, { useEffect, useState } from 'react';
import { NativeEventEmitter, NativeModules, View, Text, StyleSheet, Button } from 'react-native';
import axios from 'axios';

const { AudioInputModule } = NativeModules;
const audioEventEmitter = new NativeEventEmitter(AudioInputModule);

const SpeechMode = () => {
  const [isRecording, setIsRecording] = useState(false);
  const [transcription, setTranscription] = useState('');

  useEffect(() => {
    const subscription = audioEventEmitter.addListener('AudioData', (data) => {
      processAudioChunk(data);
    });

    return () => {
      AudioInputModule.stopAudioStream();
      subscription.remove();
    };
  }, []);

  const startRecording = () => {
    setIsRecording(true);
    setTranscription(''); // Clear previous transcription
    AudioInputModule.startAudioStream();
  };

  const stopRecording = () => {
    setIsRecording(false);
    AudioInputModule.stopAudioStream();
  };

  const processAudioChunk = async (base64Data) => {
    try {
      const transcriptionResult = await transcribeAudio(base64Data);
      if (transcriptionResult) {
        setTranscription((prev) => prev + ' ' + transcriptionResult);
      }
    } catch (error) {
      console.error('Error in transcription:', error);
    }
  };

  const transcribeAudio = async (base64Data) => {
    const GOOGLE_API_KEY = 'api key';
    const url = `https://speech.googleapis.com/v1/speech:recognize?key=${GOOGLE_API_KEY}`;

    const requestBody = {
      config: {
        encoding: 'LINEAR16',
        sampleRateHertz: 16000,
        languageCode: 'en-US',
      },
      audio: {
        content: base64Data,
      },
    };

    try {
      const response = await axios.post(url, requestBody);
      if (response.data && response.data.results) {
        return response.data.results
          .map((result) => result.alternatives[0].transcript)
          .join(' ');
      }
    } catch (error) {
      console.error('Google API Error:', error.response || error.message);
    }
    return '';
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Real-Time Speech-to-Text</Text>
      <Button
        title={isRecording ? 'Stop Recording' : 'Start Recording'}
        onPress={isRecording ? stopRecording : startRecording}
      />
      <Text style={styles.subtitle}>
        {isRecording ? 'Listening...' : 'Ready to Record'}
      </Text>
      <View style={styles.outputContainer}>
        <Text style={styles.outputLabel}>Transcription:</Text>
        <Text style={styles.output}>{transcription}</Text>
      </View>
    </View>
  );
};

export default SpeechMode;

Native Module Code:
AudioInputModule.java (Java Code):

package com.webrtcexample;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Base64;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.modules.core.DeviceEventManagerModule;

public class AudioInputModule extends ReactContextBaseJavaModule {
    private static final int SAMPLE_RATE = 16000;
    private boolean isRecording = false;
    private Thread recordingThread;

    public AudioInputModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "AudioInputModule";
    }

    @ReactMethod
    public void startAudioStream() {
        if (isRecording) return;

        isRecording = true;
        recordingThread = new Thread(() -> {
            AudioRecord audioRecord = new AudioRecord(
                MediaRecorder.AudioSource.MIC,
                SAMPLE_RATE,
                AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT,
                AudioRecord.getMinBufferSize(
                    SAMPLE_RATE,
                    AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT
                )
            );

            if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
                sendEvent("onError", "AudioRecord initialization failed");
                return;
            }

            audioRecord.startRecording();
            byte[] buffer = new byte[2048];
            while (isRecording) {
                int read = audioRecord.read(buffer, 0, buffer.length);
                if (read > 0) {
                    // Convert PCM data to Base64 and send to React Native
                    String base64Audio = Base64.encodeToString(buffer, 0, read, Base64.NO_WRAP);
                    sendEvent("AudioData", base64Audio);
                }
            }

            audioRecord.stop();
            audioRecord.release();
        });
        recordingThread.start();
    }

    @ReactMethod
    public void stopAudioStream() {
        isRecording = false;
        if (recordingThread != null) {
            try {
                recordingThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            recordingThread = null;
        }
    }

    private void sendEvent(String eventName, Object data) {
        getReactApplicationContext()
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit(eventName, data);
    }
}

I guess the problem is with the audio input I am taking what should , and I know of limit but ever before the limit it was not giving the text

Draggable window lagging on movement

So I’m trying to create draggable-resizable iframe which will work on any site.
I created one. On some websites works perfectly, but on others – very laggy. When i move this window around, it just very slow and not following mouse speed.

I don’t know why this happens… What should i do?

My code (which could be completely wrong):

import React, { useState, useEffect } from 'react';
import { Rnd } from 'react-rnd';

const style = {
  display: "flex",
  flexDirection: "column",
  alignItems: "center",
  justifyContent: "center",
  border: "solid 1px #402791",
  background: "#000000bf",
  zIndex: 9999998,
  overflow: "hidden",
  pointerEvents: "auto",
  position: "absolute",
} as const;

const dragHandleStyle = {
  width: "100%",
  height: "30px",
  background: "#402791",
  cursor: "move",
  zIndex: 9999999,
};

const DraggableResizableWindow = () => {
  const [dragging, setDragging] = useState(false);

  useEffect(() => {
    if (dragging) {
      const overlay = document.createElement('div');
      overlay.id = 'drag-overlay';
      overlay.style.position = 'fixed';
      overlay.style.top = '0';
      overlay.style.left = '0';
      overlay.style.width = '100%';
      overlay.style.height = '100%';
      overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
      overlay.style.zIndex = '9999997';
      overlay.style.pointerEvents = 'none';
      document.body.appendChild(overlay);

      document.body.style.pointerEvents = 'none';
    } else {
      const overlay = document.getElementById('drag-overlay');
      if (overlay) {
        document.body.removeChild(overlay);
      }

      document.body.style.pointerEvents = 'auto';
    }

    return () => {
      const overlay = document.getElementById('drag-overlay');
      if (overlay) {
        document.body.removeChild(overlay);
      }
    };
  }, [dragging]);

  const handleDragStart = () => {
    setDragging(true);
  };

  const handleDragStop = () => {
    setDragging(false);
  };

  return (
    <Rnd
      style={style}
      default={{
        x: 400,
        y: 400,
        width: 400,
        height: 300,
      }}
      dragHandleClassName="drag-handle"
      bounds="window"
      onDragStart={handleDragStart}
      onDragStop={handleDragStop}
    >
      <div className="drag-handle" style={dragHandleStyle}></div>
      <iframe
        src="https://example.com/"
        width="100%"
        height="100%"
        style={{ border: "none" }}
        title="Example iframe"
      />
    </Rnd>
  );
};

export default DraggableResizableWindow;

React To do app not updating after delete [duplicate]

Thanks for the help in advance. I have a to-do app the items get deleted on clicking the delete. But on submitting the new item along with the new item the deleted item is also listed. Provided the code with this. Please help to sort this issue. On the console, the data is listed correctly but not updating the state

App.js

import { useState } from "react";
import Input from "./Inputs/Input";
import Items from "./Items/Items";

import "./styles/App.scss";

export default function App() {
  const [formData, setInitFormData] = useState([]);
  const inputHandler = (data) => {
    setInitFormData(data);
  };
  const dataAftrDelInPar = (delData) => {
    console.log("After Deleted:", delData);
    setInitFormData(delData);
    console.log("Form Data:", formData);
  };

  return (
    <div className="container w-[70%] mt-5">
      <h1>To Do App</h1>
      <Input FrmData={inputHandler} />
      <Items listData={formData} deletedDataToPr={dataAftrDelInPar} />
    </div>
  );
}

Item.js

import { useState, useEffect, useRef } from "react";
import { CheckIcon, PencilIcon } from '@heroicons/react/24/solid';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faTrashAlt  } from '@fortawesome/free-solid-svg-icons';

export default function Items({ listData,deletedDataToPr }) {
  const [frmValue, setFrmVal] = useState(listData);
  const [selected, setSelected] = useState(null);
  const [updateInp, setUpdateInp] = useState(null);
  const [editVal, setEditVal] = useState(null);
  const updatedFrmRef = useRef(null);

  useEffect(() => {
    setFrmVal(listData);
  }, [listData]);

  const deleteHandler = (val) => {
    const BefrdeleteData = [...frmValue];
    const AftrdeleteData = BefrdeleteData.filter((currFl, ind) => ind !== val);
    setFrmVal(AftrdeleteData);
    deletedDataToPr(AftrdeleteData)
    setSelected(null);
  }

  const doneHandler = (doneVal) => {
    setSelected(doneVal);
  }

  const updateHandler = (updateVal) => {
    console.log(`currently clicked is ${updateVal}`);
    setUpdateInp(updateVal);
    setEditVal(frmValue[updateVal]);
  }

  const editFrmSave = (saveFrmVal) => {
    const updatedData = [...frmValue];
    updatedData[saveFrmVal] = updatedFrmRef.current.value;
    setFrmVal(updatedData);
    setUpdateInp(null);
  }

  return (
    <>
      {frmValue.map((currEl, index) => (
        <div className="justify-between flex items-center rounded-md bg-blue-50 my-3 px-2 py-2 ring-1 ring-inset ring-blue-700/10" key={index}>
          {updateInp === index ?
            (
              <div className="grid grid-cols-12 gap-4 items-center">
                <div className="col-span-9">
                  <input type="text" className="border border-gray-300 p-1" defaultValue={editVal} ref={updatedFrmRef} />
                </div>
                <div className="col-span-3 px-2">
                  <button type="submit" className="w-full px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600" onClick={() => { editFrmSave(index) }}>
                    Submit
                  </button>
                </div>
              </div>
            )
            :
            (<>
              <h2 className={`text-lg font-medium text-blue-700 ${selected === index ? 'line-through text-red-500' : ''}`}>{currEl}</h2>
              <div className="justify-between flex items-center">
                <button className="p-1.5 flex items-center space-x-2 text-red-500 rounded" onClick={() => { deleteHandler(index) }}>
                  <FontAwesomeIcon icon={faTrashAlt} />
                </button>
                <button onClick={() => { doneHandler(index) }} className="p-1.5">
                  <CheckIcon className="w-6 h-6 text-green-500" />
                </button>
                <button onClick={() => { updateHandler(index) }} className="p-1.5">
                  <PencilIcon className="h-4 w-4 text-blue-500" />
                </button>
              </div>
            </>)
          }

        </div>
      ))}
    </>
  );
}

How to check if a cell contains an integer value in onlyoffice macros?

I’m trying to check if a cell in an only office spread sheet contains an integer in an only office macro.

I already checked the API-Documentation but couldn’t find anything. However since I keep finding seemingly undocumented functions in blog posts (and similar), I hope that someone knows the answer. Perhaps I’m also missing something basic regarding calculation functions in oo-macros. (I’m relatively new to js)

Alternatively I could implement this as a custom function, however I would find it strange, that I’d have to resort to this for a seemingly easy task. If this is required, how would I go about that?

(function()
{   
    var sheet = Api.GetActiveSheet();  // Get the active sheet
    var cellValue = sheet.GetRangeByNumber(row, 6).GetValue(); // get the value 
      
     if (MOD(cellValue) === 0) { //<-- WHAT needs to go here?
          alert("value is integer");
         }  
})();

How to get configuration value from pom.xml to ReactJS when springboot and Reactjs project build together

We have a backend springboot application along with reactjs frontend build together. Currently, the reactjs application is building successfully with the spring boot application.
However,we need to get the configuration value from the pom.xml(OR from application.yml) to the ReactJS project.
Is there anyone who has done these type of configuration reading from the frontend?

Following is part of the pox.xml file which has plugins section

<plugins> 
  <plugin>
        <groupId>com.github.eirslett</groupId>
        <artifactId>frontend-maven-plugin</artifactId>
        <version>${frontend-maven-plugin.version}</version>
        <configuration>
            <workingDirectory>src/main/resources/ui-resources</workingDirectory>
            <!--<nodeDownloadRoot>https://npm.taobao.org/mirrors/node/</nodeDownloadRoot>-->
            <nodeVersion>${node.version}</nodeVersion>
            <npmVersion>${npm.version}</npmVersion>
            <yarnVersion>${yarn.version}</yarnVersion>
            <installDirectory>target</installDirectory>
        </configuration>
        <executions>
            <execution>
                <id>install node and yarn</id>
                <goals>
                    <goal>install-node-and-yarn</goal>
                </goals>
                <phase>generate-resources</phase>
            </execution>
            <execution>
                <id>yarn install</id>
                <goals>
                    <goal>yarn</goal>
                </goals>
                <configuration>
                    <arguments>install --check-cache</arguments>
                </configuration>
            </execution>
            <execution>
                <id>yarn build</id>
                <goals>
                  <goal>yarn</goal>
                </goals>
                <configuration>
                    <arguments>build</arguments>
                </configuration>
            </execution>
        </executions>
    </plugin>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.6</version>
    <executions>
      <execution>
        <id>copy-ui-resources</id>
        <phase>prepare-package</phase>
        <goals>
          <goal>copy-resources</goal>
        </goals>
        <configuration>
          <!--
          <outputDirectory>src/main/resources/static</outputDirectory>
          -->
          <outputDirectory>target/classes/static</outputDirectory>
          <resources>          
            <resource>
              <directory>${basedir}/src/main/resources/ui-resources/build</directory>
            </resource>
          </resources>              
        </configuration>            
      </execution>
    </executions>
  </plugin>
  <plugin> 
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-maven-plugin</artifactId>  
    <configuration> 
      <excludes> 
        <exclude> 
          <groupId>org.projectlombok</groupId>  
          <artifactId>lombok</artifactId> 
        </exclude> 
      </excludes> 
    </configuration> 
  </plugin>  

</plugins> 

Using OpenAI from broswer client

I’m following freecode camp tutorial on building a chatbot – https://www.freecodecamp.org/news/build-gpt-4-api-chatbot-turorial/

I tried to use their code as is, however is getting the error – Uncaught TypeError: Failed to resolve module specifier "openai". Relative references must start with either "/", "./", or "../".. I looked up some resources at https://platform.openai.com/docs/libraries#node-js-library it seems the usage in the code is similar as in freecode camp code – snippet below.

import { process } from '/env.js'
import { Configuration, OpenAIApi } from 'openai'

const configuration = new Configuration({
    apiKey: process.env.OPENAI_API_KEY
})

const openai = new OpenAIApi(configuration)

I need help on how I can modify freecode camp code if required to make it work. Unfortunately they haven’t given steps on how to launch the app.

How catch and mute “Cross-Origin-Opener-Policy policy would block the window.closed call” error

I’m opening a pop-up from a page (main page). I’m then checking constantly if the pop-up is still open or has been closed. I’m doing that with the code below

const checkForPopUp = async function() {
    try {
        while(!extFrame?.closed) {
            await new Promise(resolve => setTimeout(resolve, 250));
        }
        return true;
    }
    catch (error) {
        console.log(error);
    }
}

However, at some point the pop-up redirects to another domain so the browser throws the error Cross-Origin-Opener-Policy policy would block the window.closed call directly when checking if the pop-up is still open or not. The error is not caught by try/catch nor by window.onerror, nor by window.onunhandledrejection.

How can I catch this specific error and handle it differently so that it doesn’t print as an error?

ipcmain.handle parameter has metadata(?) instead of value

I am a beginner to electron and my app does nothing more than unpack a zip and start a .bat file (it’s an installer) i need the user to give a url to a database but when it returns i get in ipcMain: {"sender":{"_windowOpenHandler":null,"ipc":{"_events":{},"_eventsCount":1,"_invokeHandlers":{}},"_events":{"render-process-gone":[null,null]},"_eventsCount":13},"frameId":1,"processId":4}

main.js: (not entire file just handle)

    ipcMain.handle('run-start', async (database) => {
        console.log(`dbUrl in main.js:`, JSON.stringify(database), `Type:`, typeof database);
    const command = path.join(filePath, 'dist', 'setup.bat') + ' ' + database
    try {
        console.log(command)
        // const result = await new Promise((resolve, reject) => {
        //     exec(command, (error, stdout, stderr) => {
        //         if (error) {
        //             reject(`Error: ${stderr}`);
        //         } else {
        //             resolve(stdout);
        //         }
        //     });
        // });
        return result;
    } catch (error) {
        return error;
    }
})

preload.js (entire file):

const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electron', {
    selectFolder: () => ipcRenderer.invoke('select-folder'),
    runInstall: (destDir) => ipcRenderer.invoke('run-install', destDir),
    runStart: (dbUrl) => {ipcRenderer.invoke('run-start', dbUrl); console.log(dbUrl)}
});

index.html (just the handler for the clicked btn):

        document.getElementById('startButton').addEventListener('click', async () => {
        console.log(dbUrl)
        await window.electron.runStart(dbUrl)
        alert('ClassyBooks is gestart!');
    });

everywhere the dbUrl is correct except in main.js

Pull data from trade ogre api with php

https://tradeogre.com/api/v1/markets

I am trying to pull the price of ada to add to my website.

This is what I’ve tried:

<?php
$content = file_get_contents('https://tradeogre.com/api/v1/markets');

preg_match('#"ADA-USDT":{"initialprice":"(.*)","price":"(.*)"#', $content, $match);
echo $match[2];

?>

I tried and thought it was going to be easy as i have used this code many times!

I want to deploy laravel intertia wth react.tsx on namecheep server stuck at this point

I know how to deploy a Laravel project, but I don’t know how to handle the React project with Laravel and Inertia. I am using shared hosting on Namecheap. I have deployed the Laravel backend, and the migrations have run successfully, and the tables are connected. The only issue is that the frontend is not loading. This is not an API-based project; I am using Inertia to communicate between React and Laravel Error message Images on frontend

can you please guide me what to do next and how to solve this problem

Note: i have try to install npm in directory but its not work but i have an option of node in my serve see the image bellow
Node Image in namecheep cpanle

wait a function to finish

The general use case for waiting for a function to finish is to use async-await and Promise. But somehow I can’t get it to work.

I have a directive and in this directive I have a public function like this:

getCellValue(
    rowField: string,
    rowValue: any,
    columnField: string,
    gridData?: any[]
  ): any {
    setTimeout(() => {
      if (gridData) {
        return methods.getCellValuePrivate(
          rowField,
          rowValue,
          columnField,
          gridData
        );
      } else {
        return methods.getCellValuePrivate(
          rowField,
          rowValue,
          columnField,
          this.config.gridData
        );
      }
    });
  }

It gets a value from the provided gridData argument or from the this.config.gridData. I have to use setTimeout, because in the directive I do some data manipulating and with using setTimeout I ensure, that I get the right data.

Now, in a component, where I use this directive, I simply look for it like this:

  @ViewChild(EnhancedGridDirective) enhancedGridDirective!: EnhancedGridDirective;

And in ngAfterViewInit I call the beforementioned function, f. e.:

const val = this.enhancedGridDirective.getCellValue(
      'category',
      'cat 2',
      'feb'
    );
console.log(val);

Of course I get undefined in the console because of the setTimeout in the function.

But if I change the function like this:

async getCellValue(
    rowField: string,
    rowValue: any,
    columnField: string,
    gridData?: any[]
  ): Promise<any> {
    new Promise((resolve) => {
      setTimeout(() => {
        if (gridData) {
          resolve(
            methods.getCellValuePrivate(
              rowField,
              rowValue,
              columnField,
              gridData
            )
          );
        } else {
          resolve(
            methods.getCellValuePrivate(
              rowField,
              rowValue,
              columnField,
              this.config.gridData
            )
          );
        }
      });
    });
  }

And in the ngAfterViewInit then:

this.enhancedGridDirective
      .getCellValue('category', 'cat 2', 'feb')
      .then((v) => console.log(v));

I also get undefined.

So, how to solve this issue?