How to Track User Progress in SCORM Content Embedded via an iFrame from AWS S3?

I have embedded a SCORM package hosted in an AWS S3 bucket into my website using an iFrame. The SCORM content displays correctly, but I would like to track the user’s progress—specifically which slides the user has completed and how far they’ve progressed through the content.

<iframe id="scormPlayer" src="https://scorm-package.s3.eu-west-2.amazonaws.com/scorm/hurak-learning/fire-marshal-fire-warden-online/Introduction/index.html" width="100%" height="600" frameborder="0"></iframe>

How can I track which slides the user has completed and their overall progress within the SCORM content? I’m using SCORM 2004 and would prefer to manage the data within my own system without relying on third-party services.

Any help or suggestions would be greatly appreciated!

Matching a post with a memberId WIX

I’m trying to input the logged member ID into a CMS in Wix. I can’t find a way to do this without using code, and when I try to use code, it works but creates an additional item in the database just for the member ID insert.

I believe this happens because the other data I send im using the no-code method connecting the inputs to the specific table from the database for every input on the screen. The only way I found to insert the current logged member ID into the CMS is through JavaScript, but it’s sending twice: once via the no-code method sending all the data and once via code sending only the memberId. I can’t find a way to ensure everything is sent only once without creating 2 items in the database.

here is my code to send the memberId:

export function buttonSubmit_click(event) {
    currentMember.getMember()
    .then(member => {
        if (member) {
            const userId = member._id;

                const toInsert = { "userId": userId };

                wixData.insert("Empresas1", toInsert)
                .then(result => {
                    console.log("Item inserido com sucesso:", result);
                })
                .catch(err => {
                    console.error("Erro ao inserir o item:", err);
                });
        } else {
            console.log("Nenhum membro logado.");
        }
    })
    .catch(err => {
        console.error("Erro ao obter o membro:", err);
    });
}

Importing highlight.js as a CDN resource in a typescript project?

The highlight.js project provides CDN assets that provide ES6 modules.

And I’m trying to import the hljs module like this in a typescript project (In order to get around this issue).

import hljs from 'https://unpkg.com/@highlightjs/[email protected]/es/highlight.min.js';

However doing the import like this produces the linting error:

Cannot find module ‘https://unpkg.com/@highlightjs/[email protected]/es/highlight.min.js’ or its corresponding type declarations.ts(2307)
Follow link (cmd + click)

Any ideas on how to get around this?

Creating a thumbnail from existing base64 encoded image and put it as data URI

In my React project, I first pull the full image from database as Base64 encoded string, and then display it in a webpage, like the following:

...react code...
return {
    <img src='data:image/jpeg;base64, /9j/4A.../>
}

I want to create a simply function that can take base64 encoded image as input, and output a new base64 encoded image with smaller size as the thumbnail, something like:

...react code...
return {
    <img src={createThumbnail('data:image/jpeg;base64, /9j/4A...)}/>
}

I found examples such as Creating thumbnail from existing base64 image, and base on which I tried something like below but the image will not get a src at all because the reason stated in the 1st post.

const createThumbnail = (base64Image, callback = x => {return x;}) => {
    console.log(base64Image)
    const img = new Image();
    img.src = base64Image;
    img.onload = () => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, 100, 100);
      const thumbnail = canvas.toDataURL('image/jpeg');
      console.log(thumbnail)
      callback(thumbnail);
      
    }
  }

I do not understand why I need to use canvas or img.onload(...), since I have the base64 string already, how can I just open it as an image, shrink its size, and return the new image as base64?

DevExtream Show popup on datagird row click

I want to show display the pop up (app-process-enrollment) on row click rather than the button click (process column):

I’ve tried using (onRowClick) on the grid, but cannot get the data to properly load in the popup.

conn-item.component.html

<dx-data-grid *ngIf="sessions && sessions.length > 0" id="sessions" [dataSource]="sessions" keyExpr="Id"
    [columnAutoWidth]="true" [allowColumnResizing]="true" [hoverStateEnabled]="true" [showBorders]="false"
    [showColumnLines]="false" [showRowLines]="true">

    <dxi-column dataField="S.CD" caption="Created" dataType="date" sortOrder="desc"></dxi-column>
    <dxi-column *ngIf="c.t== 0" dataField="Summary.pc" caption="PCCost"></dxi-column>
    <dxi-column *ngIf="c.t == 0" caption="View" cellTemplate="process"></dxi-column>

    <div *dxTemplate="let data of 'process'">
        <app-en [s]="decaudates"></app-en>
    </div>
</dx-data-grid>

app-en.component.html

<ng-container *ngIf="mode == 'button'">
    <span class="" (click)="showImportUtility()"></span>    
</ng-container>

<!-- full screen enrollment process tool -->
<app-dialog #dialog [toolbarTitle]="screenTitle" [fullScreenOnLoad]="true" [showCloseButton]="true"
    [dragEnabled]="false" [visible]="showTool" (dialogClosed)="onDialogClosed()">
    ...
    ...
</app-dialog>

app-en.component.ts:

showImportUtility(): void {
    this.sId = this.s.ISId;
    this.PSC = this.s.PSC;
    this.showTool = true;
}

AWS DynamoDB doesn’t log or call an API

I am working on something dynamo needs to trigger an API once the records are successfully inserted. It is inserting the records but doesn’t log the success message or call the API. Once I remove the API call from the condition, everything works fine as in success message is logged and api is also triggered. Code below –

const sendTrigger = async (apikey) => {
  try {
  logger.info('Initiating trigger')   
  const res = await axios.post(`/abc/xyz`,{}, {
      headers: {
          'apikey': apikey
      }
  })
  console.log('Response', res)
  return res
  } catch (err) {
      logger.error('Error in sending ', err)
      throw err
  }
}

dynamo.put(params, async (err, data) => {
  if (err) {
    logger.error('Unable to add item. Error JSON:', JSON.stringify(err, null, 2));
  } else {
    console.log('Insert dynamoDB successful');
    try {
      const response = await sendTrigger(apiKey);
      logger.info('Response', response);
    } catch (error) {
      logger.error('Error occurred while sending trigger:', error);
    }
  }
});

If I do this it works fine –

dynamo.put(params, (err, data) => {
  if (err) {
    logger.error('Unable to add item. Error JSON:', JSON.stringify(err, null, 2));
  } else {
    console.log('Insert dynamoDB successful');
  }
});

const response = await sendTrigger(apiKey);
      logger.info('Response', response);

But my condition is like the trigger should be called only when the records are inserted. I am assuming it has something to do with async/await but not able to figure out. Any suggestions?

How to use cloud functions to create a document in Firebase Cloud Storage

I have created a Python cloud function to create a new document in Cloud Storage. It works well with firebase emulators:start, but I get an error when trying to call it from my application:

cloud-function.ts:20 Error executing cloud function upload_html_page FirebaseError: unauthenticated

I have set my scurity rules to allow read, write: true in Firebase Cloud Storage.

My cloud function is:

@https_fn.on_request()
def upload_html_page(req: https_fn.Request) -> https_fn.Response:
    """Store an entire recorded HTML page."""
    try:
        # Expecting the HTML content to be provided in the request body
        data = req.get_json().get('data', {})
        print(f"Received data: {data}")  # Log received data

        html_content = data.get("htmlAsString")
        documentId = data.get('documentId')
        actionId = data.get('actionId')
        eventId = data.get('eventId')

        storage_client = gcs_storage.Client()

        # Reference to your bucket
        bucket = storage_client.bucket('***SECRET FOR STACK OVERFLOW***')

        # Create a new blob and upload the file's content.
        blob = bucket.blob(documentId + "/" + eventId + "_" + actionId)

        # Upload the file to Firebase Storage
        blob.upload_from_string(html_content)

        return https_fn.Response(status=200)
    except Exception as e:
        return https_fn.Response(f"Error processing HTML content: {str(e)}", status=500)

And I call it in typescript with:

import { getApp } from './get-app';
import { getFunctions, httpsCallable } from 'firebase/functions';

const functions = getFunctions(getApp());
const payload: { [key: string]: any } = {};
            payload["htmlAsString"] = response.htmlAsString;
            payload["documentId"] = documentId;
            payload["actionId"] = actionId;
            payload["eventId"] = eventId;
const cloudFunction = httpsCallable(functions, "upload_html_page");
    try {
        const result = await cloudFunction(payload);
        return result.data;
    } catch (ex) {
        console.error("Error executing cloud function", name, ex);
        return null;
    }

I am connected to a FireBase account in my application when I do the call.

Is there anything I must configure in the Firebase console ?

Webresource form in power apps api show 401 error

I created web-resource form using html,JavaScript and jQuery when i deployed in power application the API show error 401 (unauthorized) and not working. When deployed we used below script also for access data from data verse. please suggest any solution for this.

$.ajax({
      type: "GET",
      contentType: "application/json; charset=utf-8",
datatype: "json",
url: "[Org_Name]/api/data/v9.2/[Table and requested fiels]",
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("Prefer", "odata.include-annotations="*"");
},
async: false,
success: function (data, textStatus, xhr) {
var results = data;
for (var i = 0; i < results.value.length; i++) {}
},
error: function (xhr, textStatus, errorThrown) {
console.log(textStatus + " " + errorThrown);
}});

below script are also used for data transaction

Error: Cannot read properties of undefined (reading ‘fromDate’)

I am getting this error: Cannot read properties of undefined (reading ‘fromDate’), when I try to get the expiry time for the otp I getting from Twilio. So I am using firebase function for my backend and I am successfully getting an OTP but I am getting that error for reasons unknown to me.

This is my code below in “functions/src/index.ts” file.

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import twilio from "twilio";
import * as dotenv from "dotenv";
// import {getFirestore, Timestamp} from "firebase-admin/firestore";

dotenv.config();
admin.initializeApp();

// const firestore = getFirestore();

const twilioClient = twilio(
  process.env.TWILIO_ACCOUNT_SID,
  process.env.TWILIO_AUTH_TOKEN
);

const generateOtp = (): string => {
  return Math.floor(100000 + Math.random() * 900000).toString();
};

// Send OTP via SMS
export const sendOtpSms = functions.https.onRequest(async (req, res) => {
  const {phoneNumber} = req.body;

  if (!phoneNumber) {
    res.status(400).json({error: "Phone number is required"});
    return;
  }

  const otp = generateOtp();

  try {
    await twilioClient.messages.create({
      body: `Your OTP is ${otp}`,
      from: process.env.TWILIO_PHONE,
      to: phoneNumber,
    });

    if (typeof admin.firestore.Timestamp.fromDate === "function") {
      const expiresAt = admin.firestore.Timestamp.fromDate(
        new Date(Date.now() + 5 * 60000)
      );
      await admin.firestore().collection("otps").doc(phoneNumber).set({
        otp,
        expiresAt,
      });
      console.log(`Generated OTP: ${otp}, Expires At: ${expiresAt.toDate()}`);
    } else {
      console.log(`Generated OTP: ${otp}`);
      res.status(500).json({error: "fromDate is not available"});
      return;
    }

    res.status(200).json({message: "OTP sent successfully"});
  } catch (error) {
    console.error("Error sending OTP:", error);
    res.status(500).json({error: "Failed to send OTP"});
  }
});

// Verify Otp
export const verifyOtp = functions.https.onRequest(async (req, res) => {
  const {phoneNumber, otp} = req.body;

  if (!phoneNumber || !otp) {
    res.status(400).json({error: "Phone number and OTP are required"});
    return;
  }

  try {
    const otpDoc = await admin
      .firestore()
      .collection("otps")
      .doc(phoneNumber)
      .get();
    if (!otpDoc.exists) {
      res.status(404).json({error: "OTP not found"});
      return;
    }

    const otpData = otpDoc.data();

    if (!otpData || !otpData.expiresAt) {
      res.status(400).json({error: "OTP data is incomplete"});
      return;
    }

    const isExpired = otpData?.expiresAt.toDate() < new Date();

    if (isExpired) {
      res.status(400).json({error: "OTP has expired"});
      return;
    }

    if (otp !== otpData?.otp) {
      res.status(400).json({error: "Invalid OTP"});
      return;
    }

    res.status(200).json({message: "OTP verified successfully"});
  } catch (error) {
    console.error("Error verifying OTP:", error);
    res.status(500).json({error: "Failed to verify OTP"});
  }
});

I have checked if it is undefined, I have done all I can but I am not getting any solution.
I will be glad to get a reply on how to sort this out because it is getting frustrating at this point. I have tried all I can, search online and also used chatGPT and Google Gemini but I could not get a solution.

How to use Speckle Viewer in a Flutter WebView?

Thanks in advance for your help!

I’m working on integrating the Speckle Viewer into a mobile Flutter app. The Speckle Viewer is written in JavaScript and utilizes the @speckle/viewer library. Is there a way to use JavaScript libraries in a Flutter app? I came across some articles about using the flutter_js package, but I’m having trouble understanding it. I have managed to run JavaScript code in a Flutter WebView by linking libraries through a CDN, but it doesn’t seem to work with the Speckle Viewer. Any suggestions?

As mentioned, using a CDN didn’t work; the page stays blank and I receive the following errors:

  • Uncaught SyntaxError: Cannot use import statement outside a module
  • Uncaught TypeError: Failed to resolve module specifier “three”. Relative references must start with either “/”, “./”, or “../”.

I also tried downloading the package via npm and referencing it locally, but I encountered the same SyntaxError, though not the TypeError.

When I include <script type="module" src="script.js"></script>, I get: Access to script at … from origin ‘null’ has been blocked by CORS policy.

On the other hand, using a URL like https://app.speckle.systems/projects/08ec61c09a/models/549ff948ec works fine, which makes me think it should be possible to get this working.

This is my first question here, and I would greatly appreciate any assistance to help me complete this project.

I’m relatively new to Flutter and have 0 JS knowledge, thank you very much for your patience.

https://github.com/Matheus-Rossetti/Amvali3D/tree/StackOverflowQuestion

Javascript – how to simple detect type of coersion?

For example

 console.log({} >= null)
 console.log([] >= null)

give as

 false
 true

Why exactly? MDN define 6 coersion type:

 primitive
 object
 numeric
 number
 boolean
 string
 other

there are a lot of very strange result, for example

 console.log(Boolean("false") > Boolean());
 console.log(Boolean("false") > Boolean(undefined));
 console.log(Boolean([]).valueOf(), Boolean({}).valueOf());
 console.log(Symbol().valueOf >= Function())
 console.log(Symbol().valueOf >= [])
 console.log(Symbol>= function(){})
 console.log(Symbol() >= function(){})

give us

 true
 true
 true true
 true
 true
 false
 TypeError: Cannot convert a Symbol value to a number

or sometimes we receive even more strange result.
Is there simple direct logic, something simple rules for Javascript developer that we can understand and quickly predict result of similar operations?