JavaScript in External File [closed]

I have added multiple scripts into a single HTML file. First i placed the scripts in the head tag. After that I placed the same scripts in the body tag, but for both cenarios the HTML page did not load with the scripts. Where do I place multiple scripts?

With a single script file name placed within the body tag the HTML page loads . But with multiple scripts placed within the same body tag or head tag the HTML page loads without the scripts file.

Merging 2 arrays, but only the similar values

I have 2 arrays:

const notifications1 = [
  {
    id: "msg001",
    profilePic: "https://randomuser.me/api/portraits/women/29.jpg",
    platform: "instagram",
    platformPic: "Instagram.png",
    name: "Kimberly Connors",
    content: "Great event! Looking forward to the next one!",
    read: false,
    dm: false,
  },
  {
    id: "msg002",
    profilePic: "https://randomuser.me/api/portraits/men/83.jpg",
    platform: "instagram",
    platformPic: "Instagram.png",
    name: "Alex_Gamer92",
    content: "Anyone up for a game night this weekend?",
    read: false,
    dm: true,
  },
];


const notifications2 = [
  {
    id: "msg001",
    profilePic: "https://randomuser.me/api/portraits/women/29.jpg",
    platform: "instagram",
    platformPic: "Instagram.png",
    name: "Kimberly Connors",
    content: "Great event! Looking forward to the next one!",
    read: false,
    dm: false,
  },
  {
    id: "msg004",
    profilePic: "https://randomuser.me/api/portraits/men/41.jpg",
    platform: "instagram",
    platformPic: "Instagram.png",
    name: "John Doe",
    content: "Count me in too!",
    read: false,
    dm: false,
  },
];

How do I merge them to have only the ones with similar values like this:

const notificationsMerge = [
  {
    id: "msg001",
    profilePic: "https://randomuser.me/api/portraits/women/29.jpg",
    platform: "instagram",
    platformPic: "src/assets/Instagram_Glyph_Gradient.png",
    name: "Kimberly Connors",
    content: "Great event! Looking forward to the next one!",
    read: false,
    dm: false,
  },
];

Right now, I’m only focused on the dm and platform similarities, but if I can learn how to do 1, the rest shouldn’t be too hard.

The only way I’ve seen so far is

const notificationsMerge = [...notifications1, ...notifications2]

but this merges everything. Anyways, thanks in advance for any help or directions to any documents.

NestJS how to use Sesion with RedisStore using Fastify?

I have installed NestJS v.10.3.9, Fastify v.4.28.0, @fastify/secure-session v7.5.1 and @fastify/redis v6.2.0 because I need pernament session to save tokens (id tokens/refresh tokens) to protect authentication against abuse and actions related to other users accounts.

I tried using the code below, but I kept getting a type error, which prevented me from compiling the Nest application.

Code:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import secureSession from '@fastify/secure-session';
import fastifyRedis from '@fastify/redis';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );

  const configService: ConfigService = app.get(ConfigService);
  const fastifyInstance = app.getHttpAdapter().getInstance();
  fastifyInstance
    .addHook('onRequest', async (req, res) => {
      req.socket['encrypted'] =
        configService.get<string>('NODE_ENV', '') === 'production';
      res.header('X-Powered-By', 'CyberSecurity');
    })
    .decorateReply('setHeader', (name: string, value: unknown) => {
      this.header(name, value);
    })
    .decorateReply('end', () => {
      this.send('');
    });
  const port = configService.get<string>('PORT', '');

  await app.register(
    fastifyRedis as Parameters<NestFastifyApplication['register']>[0],
    {
      host: configService.get<string>('REDIS_HOST', ''),
      port: configService.get<string>('REDIS_PORT', ''),
      password: configService.get<string>('REDIS_PASSWORD', ''),
    },
  );

  await app.register(
    secureSession as Parameters<NestFastifyApplication['register']>[0],
    {
      sessionName: configService.get<string>('SESSION_NAME', ''),
      cookieName: configService.get<string>('SESSION_COOKIE', ''),
      expiry: configService.get<string>('SESSION_EXPIRATION_TIME', ''),
      cookie: {
        path: '/',
        httpOnly: true,
        secure: configService.get<string>('NODE_ENV') === 'production',
      },
      secret: configService.get<string>('SESSION_SECRET', ''),
      salt: configService.get<string>('SESSION_SALT', ''),
      store: {
        type: 'redis',
        options: {
          client: app.redis,
        },
      },
    },
  );

  await app.listen(port);
}
bootstrap();

I expected that after configuring Redis and Sessions, the application would compile normally and create a session for me.

Error:

src/main.ts:89:23 - error TS2339: Property 'redis' does not exist on type 'NestFastifyApplication<RawServerDefault>'.

89           client: app.redis,

Getting the correct translate to move an element A to where element B is while scaling at the same time

I was trying to achieve an animation effect in the web app I’m working on which moves element A to where element B is while also changing its size. A and B are both circles but with different sizes, by the time A gets to where B is, it will have scaled to excactly the same size as B and they should completely overlap.

My current approach is to calculate the necessary translate by subtracting the coordinates(using left&top in this case) of A from that of B and assign it to the transform for the animation.

As a result A could roughly move to the desired position but failed to match precisely. I suspect it has to do with the scaling potentially changing the coordinates but I’m not sure how to offset this. Any idea would be appreciated.

How to know CSS property webkit-line-clamp is active with JS?

i was wondering if there is any way to know when the webkit-line-clamp is activated to use in an conditional.

For example I want to show the Show more text but only if the clamp is being applied.

<div class="clamped-text" id="text-clamp">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
</div>

<span class="show-more">Show more</span>
.clamped-text {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 2;
    width: 300px;
}

.show-more {
   display: none;
}

.show-more.clamped {
  display: block
}

I am currently using JS to slice the text and show/hide the content, without using the clamp

Vite is trying to read svelte.config.js even thought Svelte settings are inside vite.config.js

Vite (or one of its plugins) is trying to read a svelte.config.js file that I’ve never used, even though my Svelte configuration is inside vite.config.js.

❯ bun dev
$ vite --host
Error reading svelte.config.js

  VITE v5.3.3  ready in 603 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: http://192.168.68.102:5173/
  ➜  press h + enter to show help

vite.config.js

import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import autoImport from 'sveltekit-autoimport'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    autoImport({
      components: [
        {name: './src/components/containers', flat: true},
        {name: './src/components/displays', flat: true},
        {name: './src/components/files', flat: true},
        {name: './src/components/inputs', flat: true},
        {name: './src/views', flat: true},
        './src/components',
      ],
      module: {
        'svelte-apollo': ['mutation'],
        'svelte/transition': ['fly', 'fade'],
        svelte: ['onMount', 'setContext', 'getContext', 'createEventDispatcher']
      },
    }),
    svelte({
      onwarn(warning, defaultHandler) {
        if (warning.code.startsWith('a11y-')) return;
        // handle all other warnings normally
        defaultHandler(warning)
      }
    })
  ],
  resolve: {
    alias: {
      lib: path.resolve('./src/lib'),
      store: path.resolve('./src/store'),
      queries: path.resolve('./src/queries')
    }
  },
  base: './'
})

If I create a svelte.config.js with an empty export default I get rid off the Vite error:

export default {

}

All my packages are updated. However, I don’t know why it still get that error, I don’t need that file but don’t know how to avoid Vite to look for it. Any help will be really appreciated.

Using ajax and js pop up message is coming undefined

Pop up message is showing undefined code is correct but I have changed so many times
See I want in pop up that message texted successful but when I am refreshing then also it is coming undefined plz help me out because due to this I am not able to get the proper values plz help I have made some changes in js and ajax so it may possible that error has come

Unable to load transpiler to transpile @angular/platform-browser

I’ve been trying to update an Angular2 project to a more recent version of Angular. Currently it’s using Angular 15.2.10 and I’ve gone through a number of errors already but this one is proving difficult to resolve. The application builds successfully but the browser console is giving an error where it’s not transpiling @angular/browser-platform and I’m not sure why.

I’ve already looked at adding “plugin-babel” as a transpiler in systemjs.config.js but that then gives a completely different error regarding a nullish coalescing operator in @angular/common/http.

Console error (@angular/platform-browser)

Unable to load transpiler to transpile http://localhost:3000/node_modules/@angular/platform-browser/esm2020/index.mjs

Console error (@angular/common/http)

(index):72 
 (SystemJS) http://localhost:3000/node_modules/@angular/common/esm2020/http/src/interceptor.mjs: Unexpected token (52:80)
      50 |     return (req, handler) => {
      51 |         if (chain === null) {
    > 52 |             const interceptors = inject(HTTP_INTERCEPTORS, { optional: true }) ?? [];
         |                                                                                 ^
      53 |             // Note: interceptors are wrapped right-to-left so that final execution order is
      54 |             // left-to-right. That is, if `interceptors` is the array `[a, b, c]`, we want to
      55 |             // produce a chain that is conceptually `c(b(a(end)))`, which we build from the inside
    SyntaxError: Unexpected token (52:80)

systemjs.config.js

(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    '@angular/common/http':       'node_modules/@angular/common/esm2020/http',
    '@angular/common/esm2020/src/directives/ng_optimized_image':          'node_modules/@angular/common/esm2020/src/directives/ng_optimized_image',
    'node-uuid':                  'node_modules/node-uuid',
    'ngx-bootstrap':              'node_modules/ngx-bootstrap',
    'rxjs':                       'node_modules/rxjs',
    'rxjs/operators':             'node_modules/rxjs',
    'moment':                     'node_modules/moment/moment.js',
    'dragula':                    'node_modules/dragula/dist/dragula.min.js',
    'ng2-dragula':                'node_modules/ng2-dragula',
    'angular2-highcharts':        'node_modules/angular2-highcharts',
    'highcharts':                 'node_modules/highcharts',
    'highcharts/highstock.src':   'node_modules/highcharts/highstock.js',
    'plugin-babel':               'node_modules/systemjs-plugin-babel/plugin-babel.js',
    'systemjs-babel-build':       'node_modules/systemjs-plugin-babel/systemjs-babel-browser.js',
    'tslib':                      'node_modules/tslib/tslib.js',
    'zone.js':                    'node_modules/zone.js/bundles/zone.umd.js'
  };

  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':           { main: 'main.js',  defaultExtension: 'js' },
    '@angular/common/http': { main: 'index.mjs',  defaultExtension: 'mjs' },
    '@angular/common/esm2020/src/directives/ng_optimized_image': { main: 'index.mjs',  defaultExtension: 'mjs' },
    'rxjs':          { main: 'dist/cjs/index.js', defaultExtension: 'js' },
    'rxjs/operators': { main: 'dist/cjs/index.js', defaultExtension: 'js' },
    'ngx-bootstrap': { main: 'esm2020/index.mjs', defaultExtension: 'mjs' },
    'ngx-bootstrap/modal': { main: 'esm2020/index.mjs', defaultExtension: 'mjs' },
    'dragula':       { defaultExtension: 'js' },
    'ng2-dragula':   { defaultExtension: 'mjs', main: 'esm2020/ng2-dragula.mjs' },
    'node-uuid':     { main: 'uuid.js', defaultExtension: 'js'},
    'angular2-highcharts': { main: 'index.js', defaultExtension: 'js'},
    'highcharts':    { main: 'highcharts.js', defaultExtension: 'js'},
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'forms',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'upgrade',
  ];
  
  // Individual files (~300 requests):
  function packIndex(pkgName) {
    packages['@angular/'+pkgName] = { main: 'esm2020/index.mjs', defaultExtension: 'mjs' };
  }
  
  // Add package entries for angular packages
  ngPackageNames.forEach(packIndex);
  
  var bsPackageNames = [
    'modal',
    'utils',
    'component-loader',
    'positioning',
    'focus-trap'
  ];
  
  function bsIndex(pkgName) {
    packages['ngx-bootstrap/'+pkgName] = { main: 'esm2020/index.mjs', defaultExtension: 'mjs' };
  }

  // Add package entries for angular packages
  bsPackageNames.forEach(bsIndex);

  var config = {
    map: map,
    packages: packages,
    paths: {
      'ng2-dragula/*': 'node_modules/ng2-dragula/',
    },
    //transpiler: 'plugin-babel',

  };
  System.config(config);
})(this);

ts.config.json

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "System",
    "moduleResolution": "node",
    "lib": [
      "dom",
      "ES2020"
    ],
    "sourceMap": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "typeRoots": [
      "node_modules/@types"
    ],
    "types": [
      "node",
      "jasmine",
      "jQuery",
      "core-js"
    ],
    "useDefineForClassFields": false
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
    ]
}

package.json

{
  "name": "", // Name removed for privacy
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && sass assets/scss/main.scss:assets/css/main.min.css --style compressed && concurrently "npm run tsc:w" "npm run lite" ",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "dev": "node ./development.js",
    "lite": "lite-server"
  },
  "license": "ISC",
  "dependencies": {
    "@angular/animations": "^15.2.10",
    "@angular/cli": "^15.2.11",
    "@angular/common": "^15.2.10",
    "@angular/compiler": "^15.2.10",
    "@angular/compiler-cli": "^15.2.10",
    "@angular/core": "^15.2.10",
    "@angular/forms": "^15.2.10",
    "@angular/localize": "^18.1.1",
    "@angular/platform-browser": "^15.2.10",
    "@angular/platform-browser-dynamic": "^15.2.10",
    "@angular/platform-server": "^15.2.10",
    "@angular/router": "^15.2.10",
    "@angular/upgrade": "^15.2.10",
    "@types/core-js": "^2.5.8",
    "@types/jasmine": "^2.8.8",
    "@types/jquery": "^2.0.42",
    "@types/node": "^20.14.11",
    "angular2-highcharts": "0.2.1",
    "bootstrap": "^3.3.6",
    "bootstrap-datepicker": "^1.6.1",
    "core-js": "^2.4.0",
    "dragula": "^3.7.1",
    "hammerjs": "^2.0.8",
    "jquery": "^2.2.4",
    "moment": "2.0.0",
    "ng2-dragula": "^3.2.0",
    "ng2-select": "^1.0.3",
    "ngx-bootstrap": "^9.0.0",
    "node-uuid": "^1.4.7",
    "reflect-metadata": "^0.1.3",
    "rxjs": "^7.4.0",
    "systemjs": "^0.19.42",
    "systemjs-plugin-babel": "^0.0.25",
    "tinymce": "4.3.12",
    "tslib": "^2.0.0",
    "typescript": "^4.9.5",
    "zone.js": "^0.14.0"
  },
  "devDependencies": {
    "babel-core": "^6.10.4",
    "codelyzer": "0.0.23",
    "colors": "1.4.0",
    "concurrently": "^2.0.0",
    "connect": "^3.4.1",
    "gulp": "^3.9.1",
    "gulp-clean-css": "^2.0.11",
    "gulp-concat": "^2.6.0",
    "gulp-exec": "^2.1.2",
    "gulp-minify": "^0.0.12",
    "gulp-nodemon": "^2.1.0",
    "gulp-rename": "^1.2.2",
    "gulp-rev": "^7.1.0",
    "gulp-sourcemaps": "^1.6.0",
    "gulp-usemin": "^0.3.23",
    "lite-server": "^2.2.0",
    "serve-static": "^1.11.1",
    "systemjs-builder": "^0.15.23",
    "tslint": "^6.0.0"
  }
}

Any help would be appreciated 🙂

How to ignore blur from being triggered after clicking on a certain element

I searched but didn’t find a valid answer for this case, I need the blur event to be ignored for a specific click id element. I could simply trigger after the click:

$('#answer-input').focus();

But this is not 100% efficient because it is calling a timer and the delay causes it to increment.

What would be the best way? Thanks in advance!

This is my event:

$('#answer-input').blur(function(e){    
  if (e.target.id != '#click-button') { 

  }
});

this is what i tried

Strange HTML render order in a trivial tutorial function [duplicate]

    let randomNumber = Math.floor(Math.random() * 100) + 1;
    const guesses = document.querySelector(".guesses");
    const lowOrHi = document.querySelector(".lowOrHi");
    const guessSubmit = document.querySelector(".guessSubmit");
    const guessField = document.querySelector(".guessField");

    let guessCount = 0;

    function checkGuess() {
        console.log(`start of the f: ${guessCount}`);    
        if (guessCount <= 10) {        
            if (Number(guessField.value) == randomNumber) {
                lowOrHi.textContent = 'YES, you got it!!!';
            }            
            if (guessField.value < randomNumber) {            
                guesses.textContent = `${guesses.textContent} ${guessField.value}`;            
                lowOrHi.textContent = 'Your guess is smaller than the random number!';
            }
            if (guessField.value > randomNumber) {
                guesses.textContent = `${guesses.textContent} ${guessField.value}`;
                lowOrHi.textContent = 'Your guess is bigger than the random number';
            }        
        }
        guessCount += 1;    
        if (guessCount == 10) {        
            alert("Out of attempts!");       
        }
    }

    guessSubmit.addEventListener('click', checkGuess);
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">

    <title>Number guessing game</title>
    

    <style>
      html {
        font-family: sans-serif;
      }

      body {
        width: 50%;
        max-width: 800px;
        min-width: 480px;
        margin: 0 auto;
      }
      
      .form input[type="number"] {
        width: 200px;
      }

      .lastResult {
        color: white;
        padding: 3px;
      }
    </style>
    <script src="assets/scripts/app.js" defer></script> 
  </head>

  <body>
    <h1>Number guessing game</h1>        

    <div class="form">
      <label for="guessField">Enter a guess: </label>
      <input type="number" min="1" max="100" required id="guessField" class="guessField">
      <input type="submit" value="Submit guess" class="guessSubmit">
    </div>

    <div class="resultParas">
      <p class="guesses"></p>      
      <p class="lowOrHi"></p>
    </div>   
   
  </body>
</html>

We have to guess a number, by clicking a button checkGuess() gets executed, and when guessCount hits 10 it’s over, all this is OK. As this the function is not complete, but that’s not the point here.
The question is: When guessCount hits 10, I first see “alert” popup, and after close it, HTML gets updated with “guesses.textContent” and “lowOrHi.textContent” despite that code is before alert part.

But if I replace “alert” with “console.log()” message, everything renders as it should (or at least as I think it should).

Electron, node.js, next.js – bluetooth serial get device name – serial web api

I have a small electron + next.js + typescript + ES application running and I’d like it to list all connected bluetooth devices on my pc.

Currently, I’m able to list those but only their information is shown without the device name like “myIphone” or “earbuds brandname pro+”. What is a good way to do so?

I’ve tried multiple other bluetooth node modules but they are almost all deprecated and will not work with the latest versions of the tools electron, next.js, typescript and ES.

Setup:

  • Node.js 18.16.1,
  • Chromium 116.0.5845.228,
  • Electron 26.6.10.
  • npm -v: 10.5.0

  • node -v: 20.12.2 (why is this different from node.js? )

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.

    <button id="clickme">Test Serial</button>
    
    <!-- You can also require other files to run in this process -->
    <script src="./renderer.js"></script>
  </body>
</html>

main.js:

// Modules to control application life and create native browser window
const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')

app.commandLine.appendSwitch('enable-features', 'ElectronSerialChooser')

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      enableBlinkFeatures: 'Serial'
    }
  })

  mainWindow.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
    console.log('SELECT-SERIAL-PORT FIRED WITH', portList);
    
    //Display some type of dialog so that the user can pick a port
    /*dialog.showMessageBoxSync({
      ....
      ...
      ...
    });*/
    event.preventDefault();
    
    let selectedPort = portList.find((device) => {      
      // Automatically pick a specific device instead of prompting user
      //return device.vendorId == 0x2341 && device.productId == 0x0043;

      // Automatically return the first device
      return true;
    });
    if (!selectedPort) {
      callback('')
    } else {
      callback(selectedPort.portId)
    }
  })

  mainWindow.webContents.session.on('serial-port-added', (event, port) => {
    console.log('serial-port-added FIRED WITH', port);
    for(var i = 0; i < port.length; i++) {
      const info = port[i].getInfo();
      console.log(info);
    }
    event.preventDefault();
  })

  mainWindow.webContents.session.on('serial-port-removed', (event, port) => {
    console.log('serial-port-removed FIRED WITH', port);
    event.preventDefault();
  })
  
  mainWindow.webContents.session.on('select-serial-port-cancelled', () => {
    console.log('select-serial-port-cancelled FIRED.');
  })

  mainWindow.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
    // This permission check handler is not needed by default but available if you want to limit serial requests
    console.log(`In PermissionCheckHandler`);
    console.log(`Webcontents url: ${webContents.getURL()}`);
    console.log(`Permission: ${permission}`);
    console.log(`Requesting Origin: ${requestingOrigin}`, details);  
    return true;
  });  

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()

  ipcMain.on('log', (event, msg) => {
    console.log(msg);
  });
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()
  
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

package.json:

{
  "name": "test_bt3",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "devDependencies": {
    "electron": "^26.0.1"
  },
  "author": "",
  "license": "ISC"
}

preload.js:

// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const type of ['chrome', 'node', 'electron']) {
    replaceText(`${type}-version`, process.versions[type])
  }
})

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

contextBridge.exposeInMainWorld("electronAPI", {
    on: (channel, callback) => {
        ipcRenderer.on(channel, callback);
    },
    send: (channel, args) => {
        ipcRenderer.send(channel, args);
    },
    
    
    log : (msg) => ipcRenderer.send('log', msg),
      
});

renderer.js:

// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// No Node.js APIs are available in this process because
// `nodeIntegration` is turned off. Use `preload.js` to
// selectively enable features needed in the rendering
// process.

async function testIt() {  

  
  const filters = [
    // Optional filters to limit what serial ports are returned
    // { usbVendorId: 0x2341, usbProductId: 0x0043 },
    // { usbVendorId: 0x2341, usbProductId: 0x0001 }
  ];

  const port = await navigator.serial.requestPort({filters});
  window.electronAPI.log('Selected port');
  window.electronAPI.log(port);

}

document.getElementById('clickme').addEventListener('click',testIt);

Maximize quality in a YouTube video using the API in Javascript

I’m doing a small project for a multicam website and I would like to know if using the YouTube API I can make the video appear in a predefined way with the highest possible quality. The program is very simple, I added the javascript code to see if someone who has worked with it or understands the subject can help me.

This is the code:

    "https://www.youtube.com/embed/FTw5xuq2swo?si=FEoxfsIQhmr4cu",
    "https://www.youtube.com/embed/Rg7kw-KLDL8?si=pABas8BsqLuQnP",
    "https://www.youtube.com/embed/uH1W01t_lGc?si=chERPVJdUGf-Q",
    "https://www.youtube.com/embed/Mu-dvOOnaOw?si=nckTPbwRLvVVqF",
    "https://www.youtube.com/embed/c212qMUTnEs?si=_bkJR78x2cX9FX",
    "https://www.youtube.com/embed/uH1W01t_lGc?si=4UxhxVaVJpspE1_",
    "https://www.youtube.com/embed/RsIG9WF-B4s?si=ETIOowVKEUaDBX",
    "https://www.youtube.com/embed/qw3uaLRrYNY?si=0epReb6olWaEP9",
    "https://www.youtube.com/embed/OWCh3wmKtak?si=t3fjj5cE90Gv",
];

function createIframes(videoUrls) {
    const videoGrid = document.getElementById('videoGrid');
    videoUrls.forEach((url, index) => {
        const iframeContainer = document.createElement('div');
        iframeContainer.id = 'player' + index;
        iframeContainer.className = 'grid-item';
        videoGrid.appendChild(iframeContainer);
    });
}

createIframes(videoUrls);

function onYouTubeIframeAPIReady() {
    videoUrls.forEach((url, index) => {
        new YT.Player('player' + index, {
            height: '100%',
            width: '100%',
            videoId: extractVideoID(url),
            playerVars: {
                'autoplay': 1,
                'mute': 1
            }
        });
    });
}

function extractVideoID(url) {
    const urlObj = new URL(url);
    return urlObj.searchParams.get('v') || urlObj.pathname.split('/').pop();
}

document.addEventListener("DOMContentLoaded", function() {
    const videoGrid = document.getElementById('videoGrid');

    const numVideos = videoUrls.length;
    const numCols = Math.ceil(Math.sqrt(numVideos));
    const numRows = Math.ceil(numVideos / numCols);

    videoGrid.style.gridTemplateColumns = `repeat(${numCols}, 1fr)`;
    videoGrid.style.gridTemplateRows = `repeat(${numRows}, 1fr)`;
});```

Extract level data from unknown octet-stream format

Overview:

I wanted to attempt to extract the level data from Happy Wheels, their APIs are all open to pull data. I can pull the data shown in the level lists as well as each individual level ID (it returns all of that in XML) but when I attempt to pull the level data itself (obstacles, guns, etc) it responds with an octet-stream. All of the threads I have pulled told me to read it as hex which I have done but I have no idea where to go from here.

Issue:

POST https://totaljerkface.com/get_level.hw?level_id=1786343&action=get_record&ip_tracking=53445

That API is what the Happy Wheels game hits when it wants to load a new level but it returns it in an unknown format.
My end-goal is to have the level structure data in json or xml format so I can then read it via code.

Other findings:

The way I have been debugging this is, looking at the “Network” tab in my browser as I navigate around the app, for anything level related it always uses /get_level.hw with various parameters to determine the action.

Also when you create a level you can grab the raw levelXml via the UI but after some tinkering I still havent found a way to apply this to other user created levels, only my own and not via API because it still uses the same get_level.hw API with the same response to gather information. But that is good news cause that means all data required is in fact in that response, just have no idea how to decode it or even if thats possible.

Question:

Is it possible to convert the response from get_level.hw to something more readable?
I believe the end format should be what is described here.

It seems it’s being decoded in the javascript somewhere but sadly the source map files arent included and I cant find anywhere on github someone posting the decoded source code.

Thanks in advance!

When using a hex viewer, this is what the response of the API looks like.

hex output of api response

TypeError: Cannot read properties of undefined (reading ‘map’) react.js [closed]

import React, { Component } from 'react';
import Like from '../common/like';
import TableHeader from '../common/tableHeader';
import TableBody from '../common/tableBody';

class MoviesTable extends Component {
    columns = [
        {path: 'title', label: 'Title'},
        {path: 'genre.name', label: 'Genre'},
        {path: 'numberInStock', label: 'Stock'},
        {path: 'dailyRentalRate', label: 'Rate'},
        {key: 'Like' ,
         content: movie => (<Like liked={movie.liked} onClick={() => this.props.onLike(movie)}/>)
        },        
        {key: 'Delete',
         content: movie => (<button onClick={() =>this.props.onDelete(movie)} className="btn btn-danger btn-sm">Delete</button>)
        }
    ];
   
    render() { 
        const {movies} = this.props;
        return (
            <table className="table">
                <TableHeader columns = {this.columns} 
                sortColumn = {this.props.sortColumn} 
                onSort = {this.props.onSort} />

                <TableBody 
                data = {movies}
                {...console.log(this.props.data)} />
                
                {/* <tbody>
                   {movies.map(movie =>  <tr key={movie._id}>
                        <td>{movie.title}</td>
                        <td>{movie.genre.name}</td>
                        <td>{movie.numberInStock}</td>
                        <td>{movie.dailyRentalRate}</td>
                        <td>
                           
                        </td>
                        <td></td>
                    </tr>)}
                </tbody> */}
            </table>
        );
    }
}
 
export default MoviesTable;

This is the moviestable.jsx I am using it to render the movies table but then I decided to seperate the table rendering from this component and make a common component

import React, { Component } from 'react';
import _ from 'lodash';
import PropTypes from 'prop-types';

class TableBody extends Component {
    renderCell = (item, column) => {
        if(column.content) return column.content(item);
        return _.get(item, column.path);
    };
    state = {  } 
    render() { 
        const {data, columns} = this.props;
        return (
           <tbody>
            {data && data.map((item) =>  (<tr>
               {columns.map((column) => <td>{this.renderCell(item, column)}</td>)} 
            </tr>))}
           
           </tbody>
        );
    }
    
}
TableBody.propTypes = {
    data: PropTypes.array.isRequired,
    columns: PropTypes.array.isRequired
};
 
export default TableBody;

So I made another component tableBody.jsx just to render the table and imported it into the moviesTable. The movies in moviesTable is being fetched from movies component and is of array type .

The error I am facing:-

Uncaught TypeError: Cannot read properties of undefined (reading 'map')
at tableBody.jsx:15:1
at Array.map (<anonymous>)
at TableBody.render (tableBody.jsx:14:1)
at finishClassComponent (react-dom.development.js:19781:1)
at updateClassComponent (react-dom.development.js:19727:1)
at beginWork (react-dom.development.js:21650:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27490:1)

  

Cannot open a gtlf file on html using three js

I am looking to open a 3D image I downloaded from Sketchfab and make it interactive and clicakble using three js. I have followed the instructions by ChatGPT, so I have all the scrypts I need in the folder (GLTFLoader.js, main.js, OrbitControls.js, three.module.js, index.html, and the image itself (gltf format) . I am using a local server from Visual studio code and there is no error message appearing in the developers tool, however the website is blank and I cannot see the image.

I have tried python -m https.server -> same blank screen
I have tried different images in gltf and glb format
Also, ChatGPT suggested I use simple geometric structures like a cube, but it still doesn’t work