Load Script tag into Angular that loads another script

We have a requirement to load a JS widget from a UCaaS provider on our Angular website to provide chat features. The snippet the provided was

<script>
  var webchat;
  ((window, document, node, props, configs) => {
    if (window.ChatSDK) {
      console.error("SDK already included");
      return;
    }
    var divContainer = document.createElement("div");
    divContainer.id = node;
    document.body.appendChild(divContainer);
    var src = <https://chatsdk.ucass.com/chatsdk.js;>
    var script = document.createElement("script");
    var firstScriptTag = document.getElementsByTagName("script")[0];
    script.type = "text/javascript";
    script.charset = "UTF-8";
    script.id = "webchatscript";
    script.src = src;
    script.async = true;
    firstScriptTag.parentNode.insertBefore(script, firstScriptTag);
    script.onload = () => {
      webchat = ChatSDK(node, props);
      webchat.init(configs);
    };
  })(
    window,
    document,
    "Webchat",
    { flowId: "123", accountId: "", region: "td-us-1" },
    { enableEmoji: true, enableUserInput: true }
  );
</script>

so putting this into the src of a script tag obviously doesn’t work because its a function so the was that whole block of code and that would not work so what I have now is trying to recreate it

 let webchat;
let ChatSDK: any;
let script = this.render.createElement('script');
script.src = 'https://chatsdk.ucaas.com/chatsdk.js';
script.type = 'text/javascript';
script.charset = 'UTF-8';
script.id = 'webchatscript';
script.async = true;

script.onload = () => {
  (function blah() {
    webchat = ChatSDK('Webchat', {
      flowId: '123',
      accountId: '',
      region: 'us-1',
    });
    webchat.init({ enableEmoji: true, enableUserInput: true });
  })();

  console.log(ChatSDK); //undefined 
};

this.render.appendChild(this._document.body, script);

I am able to confirm the script tag is in the body, I am seeing the js bundles get downloaded from the providers CDN and everything looks fine just the SDK is not found and thus not initialized – could someone help me understand what I am doing wrong

Merge array of objects with the same values by key

Please help. I am creating an API and this is the data structure that Iam trying to achive:

Groups:[{ groupId, name, members:[{userId, first_name, last_name, joinedDate, leftDate}] }]
The members filed shoud contain all users that have the same groupId
I need to group this input by groupId:

            [{
              groupId: 1,
              name: 'test group',
              userId: 2,
              first_name: 'Ross',
              last_name: 'Geller',
              joinedDate: 2022-01-13T13:25:43.510Z,
              leftDate: 2023-02-24T19:07:11.110Z   
              },
              {
               groupId: 12,
               name: 'test group 2',
               userId: 2,
               first_name: 'Ross',
               last_name: 'Geller',
               joinedDate: 2022-01-13T00:00:00.000Z,
               leftDate: null
            },
              {
              groupId: 12,
              name: 'test group 2',
              userId: 6,
              first_name: 'Joey',
              last_name: 'Tribbiani',
              joinedDate: 2022-01-13T00:00:00.000Z,
              leftDate: null
            }]


Into this output:

    [
    {  groupId: 1,
      name: 'test group',
      members:[
      {  
      userId: 5,
      first_name: 'Monica',
      last_name: 'Gellar',
      joinedDate: 2022-01-13T13:25:43.510Z,
      leftDate: null}
      ]
    },
    {    groupId: 12,
      name: 'test group 2',
      members:[
      {    
      userId: 2,
      first_name: 'Ross',
      last_name: 'Geller',
      joinedDate: 2022-01-13T00:00:00.000Z,
      leftDate: null   
      },
      {    
      userId: 6,
      first_name: 'Joey',
      last_name: 'Tribbiani',
      joinedDate: 2022-01-13T00:00:00.000Z,
      leftDate: null
      }
      ]
    }
    ]

indexOfFirstPost and indexOfLastPost issues in ReactJs pagination

I am fetching some books to paginate, i have set all the elements to get this done but the pagination does not seem to work normally, i think it’s because of the the calculation of the indexOfFirstPost and indexOfLastPost, you can see in this sandbox that when you click on the next or the second page you get 3 more books so in one page you have 6 books instead of 3, and if you go back the books disapears!

What am i missing?

Here s the state :

constructor(props) {
    super(props);
    this.state = {
      books: [],
      totalPosts: 10,
      currentPage: 1,
      postsPerPage: 3,
      indexOfFirstPost: 0,
      indexOfLastPost: 0
    };
}

How do I add custom react component to DOM element

import SingleInvite from "./SingleInvite";

imported a component that I created , but I keep getting [Object object] on the place of SingleInvite component

 const newInvite = () => {
    const container = document.querySelector(".container");
    if (container) {
      container.innerHTML += `${(<SingleInvite index={index} />)}`;
    }
  };

<div>

calling newInvite

<div className="container">
    <SingleInvite index={0} />
  </div>

  <button className="add-another" onClick={newInvite}>
    <img src={plus} className="plus" alt="" /> Add another
  </button>

How to check if the user is logged in on any website

I am creating a widget that can be added through a script tag to any website. I am planning to display it conditonally, based on wether or not the user is logged in.

How can I check if a user is logged in – on any website ? I know I need to check the cookies, but I doubt there is a universal cookie name that stores the login information for all websites.

How should I go about this ?

Thanks a lot!

How to interact an entry of an input with an html table?

I have a webService that allows me to display account numbers.
I would like to create an entry in html, so that when I type an account number in the entry, it shows me that account number in the html table.

enter image description here

Honestly, I don’t know how to do this, I can show you my code so that I can complete this functionality…

template

...
<div class="card" *ngIf="currentAgency">
   <div class="card-body">
      <form #formulaire="ngForm" (ngSubmit)="onSubmit()">
      <div class=" row mb-4 align-items-end ">
         <div class="col-12 col-sm-6 col-md-4 ">
            <div class="mb-2 ">
               <!-- Portefeuille -->
               <h5>Portefeuille</h5>
               <input type="text" class="form-control form-max-width" [(ngModel)]="account">
            </div>
         </div>
         <div class="col-12 col-md-4 ">
            <div class="mb-2 ">
               <button type="submit " class="btn btn-success btn_green_arg ">
                  <!-- Search -->
                  Search 
               </button>
            </div>
         </div>
      </div>
      </form>
      <br>
      <table class="table table-bordered table-striped table-hover">
         <thead>
            <tr class="text-center">
               <!-- Portefeuille     -->
               <th>Portefeuille</th>
            </tr>
         </thead>
         <tbody>
            <ng-container *ngFor="let transfer of transferResponse?.PRE">
               <ng-container *ngFor="let preptf of transfer.PREPTF">
                  <tr>
                     <td class="text-center">
                        <a class="link-primary" role="button" (click)="openConfirmModalAccount(transfer.DEPO)">
                        {{ transfer.DEPO }}
                        </a>
                     </td>
                  </tr>
               </ng-container>
            </ng-container>
         </tbody>
      </table>
   </div>
</div>
...

service

OverviewTransfers(account: number): Observable < ApiResponse > {
   return this.http.post < ApiResponse > (this.api + `/AGHRAF`, {
      FILTRE: {
         TYPE: account,
      },
      AGENCE: this.store.selectSnapshot(AgencyState.currentAgency).CODE
   });
}

interface

export interface TransferResponse extends ApiResponse {
    PRE: Transfer[];
}

export interface Transfer {
    DEPO: number;
    CLER: string;
    INTITULE1: string;
    PHONE: string;
    PREPTF: {
        LABEL: string;
        TYPE: string;
        QUANTITE: number;
        STATUT: number; 
        NUM: number;
        ISIN: string;
        STATUT_LIB: string;
        REF_RBC: string;
    }[];
}

composent

export class OverviewTransfersComponent implements OnInit, OnDestroy {
   private unsubscribe$ = new Subject < void > ();
   currentAgency: any;
   transferResponse: TransferResponse;
   account: number;

   constructor(
      private service: OverviewTransfersService,
      private store: Store,
      private modalService: BsModalService,
      private router: Router
   ) {}

   ngOnInit(): void {
      this.currentAgency = this.store.selectSnapshot(AgencyState.currentAgency);
      if (this.currentAgency) {
         this.OverviewTransfers(this.account);
      }
   }

   ngOnDestroy(): void {
      this.unsubscribe$.next();
      this.unsubscribe$.complete();
   }

   OverviewTransfers(account: number): void {
      this.service.OverviewTransfers(account).pipe(
         takeUntil(this.unsubscribe$)
      ).subscribe(res => {
         if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {
            this.transferResponse = res as TransferResponse;
         }
      });
   }


   // filtre 
   onSubmit() {
         console.log('Account number entered :', this.account);
         this.service.OverviewTransfers(this.account).pipe(
            takeUntil(this.unsubscribe$)
         ).subscribe(res => {
            console.log('Service Response :', res);
            if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {
               console.log('Transfer Data Recovered :', res);
               this.transferResponse = res as TransferResponse;
            }
         });
      }

      ...

}

I added consoles.log in “onSubmit()” method

// filtre 
onSubmit() {
   console.log('Account number entered :', this.account);
   this.service.OverviewTransfers(this.account).pipe(
      takeUntil(this.unsubscribe$)
   ).subscribe(res => {
      console.log('Service Response :', res);
      if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {
         console.log('Transfer Data Recovered :', res);
         this.transferResponse = res as TransferResponse;
      }
   });
}

I have a message undefined.

Account number entered : undefined

enter image description here

Could you help me solve my problem so that I can enter an account number in the input and display that account number in the html table, please?

Karate: variables set in karate-config.js – can be set in another js file f.e. headers.js?

karate-config.js provides handy way to create global variables, like in this Karate doc example

config.someUrlBase = 'https://e2e-host/v1/auth';

But for our test, we’d rather don’t modify karate-config.js, so can we do the same (that is create global variables) for instance in our headers.js file?

We tried, in headers.js: (a) config.myvariabe= (b) karate.set in headers.js and then karate.get in .feature

Converting text into unordered, ordered or tables using HTML

I have a website that is like chat website.

I want to automaticly detect lists and tables and format it into HTML code.

For example the given input

let text = 1. Pizza2. Burgers3. Tacos4. Sushi5. Pasta6. Fried chicken7. Ramen8. Curry9. Steak10. Ice cream; to convert this into Ordered list

let output = <ol><li>Pizza</li><li>Burgers</li>...</ol>;

and tables from this input

let text = | Rank | Game | |------|------------------------------| | 1 | The Witcher 3: Wild Hunt | | 2 | Grand Theft Auto V | | 3 | Portal 2 | | 4 | Half-Life 2 | | 5 | Overwatch | | 6 | Counter-Strike: Global Offensive | | 7 | Doom (2016) | | 8 | Dark Souls III | | 9 | Divinity: Original Sin II | | 10 | Stardew Valley |;

into HTML code.

Note this should not remove any text before and after the list or tables, example

let input = “Hey look at the most popular video games for PC. 1.Minecraft 2.PUBG….” should not remove Hey look at the most popular video games for PC!!

I tried this code but sadly did not work

function convertTextToHTML(text) {
  const lines = text.split("n");
  let result = "";
  let isTable = false;
  let isList = false;
  let tableHeaders = [];

  for (let line of lines) {
    if (line.startsWith("|") && line.endsWith("|")) {
      isTable = true;
      const cells = line.split("|").slice(1, -1);
      if (tableHeaders.length === 0) {
        tableHeaders = cells.map((cell) => `<th>${cell.trim()}</th>`);
        result += "<table><thead><tr>" + tableHeaders.join("") + "</tr></thead><tbody>";
      } else {
        const tableCells = cells.map((cell) => `<td>${cell.trim()}</td>`);
        result += "<tr>" + tableCells.join("") + "</tr>";
      }
    } else if (line.startsWith("*")) {
      isList = true;
      if (result.indexOf("<ul>") === -1) {
        result += "<ul>";
      }
      result += "<li>" + line.slice(1).trim() + "</li>";
    } else {
      if (isTable) {
        result += "</tbody></table>";
        isTable = false;
        tableHeaders = [];
      }
      if (isList) {
        result += "</ul>";
        isList = false;
      }
      result += line + "<br>";
    }
  }
  if (isTable) {
    result += "</tbody></table>";
  }
  if (isList) {
    result += "</ul>";
  }
  return result;
}

How to use optional parameter path for routing

Using React Router Dom V6
Have MainView that has two optional parameter like,

  1. id, this time, “key” is not exist
  2. key, this time, “id” is not exists

Both paths points to same view, just need key or id distinguish params

Trying to achieve using below way but, it does not fall under ‘key’ path.
So, while using, const {id, key} = useParams(); key remains undefined.

<Routes>
  <Route path="/mainview">
    <Route path="/id" element={<MainView />} />
    <Route path="/key" element={<MainView />} />
  </Route>
</Routes>

Could you please guide how can it be achieve so, either of path can be supported.

How to embed a looker studio dashboard in a private website?

I have a website where I have to show clients different Looker Studio dashboards, this website has its own authentication and the dashboards would be displayed on an embedded basis.

Due to G Suite administrator settings, I am unable to share dashboard to people outside of the organization. Is there a way to share it either through a service account or some other way?

I have tried to share the dashboard to a service account that I have created but I get an unknown error.

Thank you very much in advance.

Display next 5 items of an array with scroll block Alpinejs/vue.js

How can I display each next 5 items of an array with scroll block Alpinejs/vue.js ? By clicking the Search button I need to render only first 5 items of an array, and then on scroll inside the block I need to render next 5 items untill the end of the array. I’m handling the scroll event and passing the increased index and step inside the new fetching function, but the code doesn’t work.

https://codesandbox.io/s/html-template-forked-ywqs9r?file=/index.html

<!-- <!DOCTYPE html> -->
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="normalize.css" />
    <link rel="stylesheet" href="styles.css" />
    <script
      defer
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"
    ></script>
    <!-- <script type="”module”" src="./script.js"></script> -->
    <title>Spring</title>
  </head>

  <body>
    <section class="content">
      <div class="container">
        <div
          class="content__top"
          x-data="{
          search: ''
        }"
        >
          <input
            type="text"
            class="input font--m1"
            placeholder="Search for the item"
            x-model="search"
            @keyup.enter="$store.products.getAllProducts(search)"
          />
          <button
            class="input__btn font--m1"
            @click="$store.products.getAllProducts(search)"
          >
            Search
          </button>
        </div>
        <div
          class="content__mid-wrapper font--m2"
          @scroll="$store.products.displayNextItems(people)"
          x-ref="topScroll"
        >
          <template x-if="showTableHeader">
            <div class="content__mid">
              <p class="content__mid-item content__mid-item--header">Med</p>
              <p class="content__mid-item content__mid-item--header">Country</p>
              <p class="content__mid-item content__mid-item--header">
                Manufacturer
              </p>
              <p class="content__mid-item content__mid-item--header">
                Price
              </p>
              <p class="content__mid-item content__mid-item--header">Till</p>
            </div>
          </template>
          <div x-data>
            <template x-for="item in $store.products.people" :key="item.id">
              <div class="content__mid">
                <p class="content__mid-item" x-text="item.name"></p>
                <p class="content__mid-item" x-text="item.email"></p>
                <p class="content__mid-item" x-text="item.username"></p>
                <p class="content__mid-item" x-text="item.username"></p>
                <p class="content__mid-item" x-text="item.username"></p>
              </div>
            </template>
          </div>
        </div>
        <div class="content__bottom">
          <div class="content__bottom-left">
            <div
              class="btn--content"
              x-data
              @click="$refs.topScroll.scrollTo({top: 0, behavior: 'smooth'})"
            >
              <img
                src="./assets/top-icon.png"
                alt="to top"
                class="content--bottom-img"
              />
              <span class="font--m1 text-underline">To top</span>
            </div>
            <div class="btn--content">
              <img
                src="./assets/print-icon.png"
                alt="print"
                class="content--bottom-img"
              />
              <span class="font--m1 text--underline">Print</span>
            </div>
          </div>
          <div class="btn--content">
            <img
              src="./assets/loader-icon.png"
              alt="downloding"
              class="content--bottom-img"
            />
            <span class="font--m1 text--underline">Downloading</span>
          </div>
        </div>
      </div>
    </section>
    <script>
      document.addEventListener("alpine:init", () => {
        Alpine.store("products", {
          people: [],
          showTableHeader: false,
          index: 0,
          step: 5,

          getAllProducts(searchInput) {
            fetch("https://jsonplaceholder.typicode.com/users")
              .then((response) => response.json())
              .then((res) => {
                this.people = res.slice(0, 5);
                this.showTableHeader = true;
                console.log(this.showTableHeader);
              });
          },
          displayNextItems(people) {
            // Return slice of the array
            fetch("https://jsonplaceholder.typicode.com/users")
              .then((response) => response.json())
              .then((res) => {
                return (this.people.slice(this.index + 5, this.step + 5) = res);
              });
            console.log("scrollRuns");
          }
        });
      });
    </script>
  </body>
</html>

TypeError: Do not know how to serialize a BigInt

I’m working on a discord bot project in Javascript. To deploy my commands I have to register them in my index.js file. Here is the structure of my project :

  • index.js
  • node_modules
  • other config files…
  • commands
    ∟ command_folder1
    ∟ command1.js
    ∟ command2.js
    ∟ command-folder2
    ∟ command3.js
    ∟ command4.js
    ∟ command-folder…

Something like that.

But I have this error : TypeError: Do not know how to serialize a BigInt

Here is my index.js file :

const {
  Client,
  Collection,
  Intents,
  GatewayIntentBits,
} = require("discord.js");
const fs = require("fs");
const { token } = require("./config.json");

// Create a new Discord client
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
  ],
});

// Set up a collection to hold your command files
client.commands = new Collection(); // define commands collection here
const commandFolders = fs.readdirSync("./commands");

for (const folder of commandFolders) {
  const commandFiles = fs
    .readdirSync(`./commands/${folder}`)
    .filter((file) => file.endsWith(".js"));

  for (const file of commandFiles) {
    const command = require(`./commands/${folder}/${file}`);
    client.commands.set(command.name, command); // use client.commands instead of commands
  }
}

// Set up event listeners for when the client is ready and when it receives a command interaction
client.once("ready", async () => {
  console.log(`Logged in as ${client.user.tag}!`);

  // Register slash commands
  try {
    const commandData = Array.from(client.commands.values()).map((command) => {
      const data = { ...command };
      if (typeof data.defaultPermission === "boolean") {
        data.defaultPermission = String(data.defaultPermission);
      }
      return data;
    });
    await client.application.commands.set(commandData);
    console.log("Successfully registered application commands.");
  } catch (error) {
    console.error("Failed to register application commands:", error);
  }
});

client.on("interactionCreate", async (interaction) => {
  if (!interaction.isCommand()) return;

  const command = client.commands.get(interaction.commandName); // use client.commands instead of commands

  if (!command) return;

  try {
    await command.execute(interaction);
  } catch (error) {
    console.error(error);
    await interaction.reply({
      content: "There was an error while executing this command!",
      ephemeral: true,
    });
  }
});

// Log in to Discord with your bot token
client.login(token);

And here is the precise output :

Logged in as botname#0000 !
Failed to register application commands: TypeError: Do not know how to serialize a BigInt
    at JSON.stringify (<anonymous>)
    at RequestManager.resolveRequest ([email protected]:1146:26)
    at RequestManager.queueRequest ([email protected]:1056:46)
    at REST.raw ([email protected]:1330:32)
    at REST.request ([email protected]:1321:33)
    at REST.put ([email protected]:1296:17)
    at ApplicationCommandManager.set (pathtofilenode_modulesdiscord.jssrcmanagersApplicationCommandManager.js:173:41)
    at Client.<anonymous> (pathtofileindex.js:48:39)
    at Object.onceWrapper (node:events:628:26)
    at Client.emit (node:events:513:28)

AngularJS dynamically called image for ng-src not displaying

I have a need to pass some custom headers for images so for certain images I am calling a function that will then retrieve the image. It looks like my function call is properly retrieving the image, but its not getting displayed in the rendered page.

$scope.imageSources = {} ;
$scope.imageCount = 0 ;
$scope.getImage = function(imageURL,id) {
var req = {
  method: 'GET',
  url: imageURL,
  headers: headers
}  

$http(req)
.then(function(response){
     $scope.imageSources[id] = response.data
     $scope.imageCount++ ;
}) ;

}

And in my page:

  <img ng-src="data:image/png;base64,{{imageSources[imageCount]}}" ng-init="getImage(imageInfo.imageURL,imageCount)" >

After the image is called, which I can see being called in the Developer Console Network tab, this is what the rendered page looks like, there is no ng-src – other images called using a ng-src=https://example.com/thisImage.png shows the ng-src in the rendered image tag:

  <img ng-init="getImage(club.clubInfo.siteMap,imageCount)">  // missing the ng-src

How can i get values from JSON using prompt?

I want to use json to change the background for the current user.
There are different users with different backgrounds.

I’m currently using prompt() to get the user.
The btn is the button, and the slider is the image.
Is there an easy way to get the current users background?

Sorry if its a stupid question, i am new to this.

let images = '{ "characters" : [' +
  '{ "name":"T" , "image":"WallP.jpg" },' +
  '{ "name":"A" , "image":"WallP2.jpg" },' +
  '{ "name":"G" , "image":"WallP3.jpg" } ]}';
  
  const query = JSON.parse(images);
  
  let element = document.getElementById("btn");
  let slider = document.getElementById('slider');
  
  element.addEventListener("click", function() {
    let box = prompt("Enter your name:", "T");
    // slider.src = query.characters["name":"T"].image;
  });