Use function defined in colab cell using that has javascript elements inside a python file

I am trying to use my laptop’s webcam in Google Colab (code snippet) but I guess that approach has a limitation. It uses Javascript which can be executed inside the cell only. If the function containing the javascript is defined inside a python file and called, below error related to eval_js is returned.

File "/content/slowfast/my_module.py", line 57, in take_photo data = eval_js('takePhoto({})'.format(quality)) File "/usr/local/lib/python3.10/dist-packages/google/colab/output/_js.py", line 36, in eval_js kernel = _ipython.get_kernel() File "/usr/local/lib/python3.10/dist-packages/google/colab/_ipython.py", line 24, in get_kernel return get_ipython().kernel AttributeError: 'NoneType' object has no attribute 'kernel'

Upon asking ChatGPT, it said to me the below information which seems to support the error.

Ensure Execution in Colab Notebook Context: Make sure that the code snippet involving eval_js is executed within a Google Colab notebook cell. eval_js is designed to work in the Colab environment where it can communicate with the browser's JavaScript context. Running this code outside of Colab, or in an environment where the notebook's kernel isn't properly connected to the Colab frontend, will lead to failures.

My requirement/ limitation is that I need to use an open-source library that works on image inputs and my local PC does not have enough GPU memory to run the code. So, I am trying to test it on Colab’s HW. Is there any way to use the functions defined in the cell inside a Python file? That way, I guess I can minimize the code changes in the pipeline that is already written.

Appended child dissapear after appending? [duplicate]

I have a problem where I try to appendChild to an element, but after it is added it is removed directly after.. I’m relatively new to this but I can’t find an answer online or anywhere else (not even the AI:s) now what to do. Here’s my code

const input = document.querySelector('.input');
const add = document.querySelector('.add');
const list = document.querySelector('.list');

function addToList() {
  const newItem = document.createElement('li');
  newItem.innerHTML = input.value;
  list.appendChild(newItem);
}

<!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" />
    <title>Document</title>
    <link rel="stylesheet" href="styles.css" />
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300&display=swap"
      rel="stylesheet"
    />
  </head>
  <body>
    <div class="container">
      <form>
        <input type="text" class="input" />
        <button class="add" onclick="addToList()">Add item</button>
      </form>
      <ul class="list">
        <li>Hey there!</li>
      </ul>
    </div>
    <script src="script.js"></script>
  </body>
</html>

So I only want it to append and not to remove after appending, how can I achieve that?
Cheers!

I’ve tried using regular eventListeners and also used functions to try get around this, It worked for me this morning, but now I get the same issue.

Cant access the router object in Vue under Laravel Nova

I made a Laravel Nova tool, because I have needed some custom functionalities which Laravel nova can’t handle. Now my tool is finished and I want to go to another page from that tool.
I tried almost everything to fix this issue, but I could not find any solution. The nova documentation is lack of this information, and the steps in the Vue docs are not working.
I’ll provide some snippets what I tried so far:

// Tool.vue

<template> ... </template>
<script>
  import Vue from 'vue';
  import { useRouter } from 'vue-router'; // the package is installed

  const router = useRouter();

  export default {
    // ...
    method: {
      someMethod() {
        router.push('/someUrl');
        this.router.push('/someUrl');
        this.$router.push('/someUrl');
      }
    }
  }
</script>

...

Out of these three none of them is working.

I get this error message in console:
Cannot read properties of undefined (reading 'push')

So the router object can’t be reached anyhow.

I also tried tweaking something in the tool.js:

// tool.js

import Tool from './pages/Tool'
import VueRouter from 'vue-router'

Nova.booting((app, store) => {
  Nova.inertia('CustomTool', Tool)
  app.use(VueRouter)
})

Or

// tool.js

import Tool from './pages/Tool'
import MyComponent from '../MyCompnent'

Nova.booting((app, store) => {
  Nova.inertia('CustomTool', Tool)
  app.component('MyComponent', MyComponent)
})
// Tool.vue

<template> ... </template>
<script>
import VueRouter from 'vue-router';

const router = new VueRouter({
  routes: [
    {
      path: '/app/my-component',
      component: MyComponent,
    },
  ],
});
</script>

This way the error says that MyComponent is not defined. If I import it then it says that the VueRouter is not a constructor. If I change it like

const router = VueRouter.createRouter({
  history: VueRouter.createWebHistory(),
  routes: [
    {
      path: '/app/my-component',
      component: MyComponent,
    },
  ],
});

then simply says Cannot read properties of undefined (reading 'createRouter')

So my question is anyone tried to work with Laravel Nova tools like this before? If so, then how can I solve this issue. Note that, I want to pass some information from one page to another so the window.location.href = '/someUrl' isn’t an option.

can’t set a value of select2

I have initialized a select2

<select id="InputProjectName" class="form-control required"></select>

Filled it with a list generated through an AJAX request.
It has a search option, after typing a few characters it shows a list of these records.
I want to set a value after initialization, without

search.$("#InputProjectName").val(95) 

or

$("#InputProjectName").val([95]) 

doesn’t work ;

$("#InputProjectName").select2({
        allowClear: true,
        tags: true,
        placeholder: 'Lütfen seçiniz',
        minimumInputLength: 1,
        tokenSeparators: [','],
        multiple: true,
        maximumSelectionLength: 1,
        createTag: function (tag) {
            let term = $.trim(tag.term);
            if (term.length < 3) {
                return null
            }
        },
        ajax: {
            url: "/Project/GetProject",
            dataType: 'json',
            type: "POST",
            delay: 750,
            data: function (params) {
                return {
                    projectName: params.term,
                    recordId: params.term,
                    page: params.page
                };
            },
            processResults: function (data, params) {
                params.page = params.page || 1;

                var items = [];

                for (var i in data) {
                    var item = data[i];
                    items.push({ id: item.Id, text: 'Id:' + item.Id + ' -Name:' + item.ProjectName });
                }

                return {
                    results: items
                };
            },
            cache: true
        },

    }).on('select2:select', function (e) {

        var selectedValueArray = $("#InputProjectName").val();
        if (selectedValueArray) {
            var selectedValue = selectedValueArray[0];
            GetFillList($("#InputItem"), '/Project/GetQuestion/', selectedValue);

        }

    }).on("select2:unselecting", function (e) {
        //$("#InputItem").val(null).trigger("change");
    });
});

Thanks in advance.

How to disable/enable the row in table with the same button?

In my table I have one buttons . In the table I want to disable/enable the entire row with the help of the same button. the button default is enable.
When I click on ‘enable’ button the entire row color will change to red and the button value change to ‘disable’.
click again to the ‘disable’ button , thenthe entire row color recovery and the button value change to ‘enable’.
How to do it . Help needed.

part of my code :
jsfiddle

<table >
<tr>
    <th>Value1</td>
    <th>Value2</td>
    <th>
        <input type="button" value="enable" />
    </th>
</tr>
<tr>
    <th>Value3</td>
    <th>Value4</td>
    <th>
        <input type="button" value="enable" />
    </th>
</tr>
</table>

How to reverse the output order (javascript, html)

I want to output the results in the order they were entered. For example, if the input is in the order abcd, I want the output to be abcd as well. However, the problem with my code is that it keeps changing the order and outputting it as dcba. How can I reverse the output order? sorry for my bad english..

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>지화 번역기</title>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd"></script>
</head>
<body>
  <h1>지화 번역</h1>
  <video id="webcam" width="640" height="480" autoplay></video>
  <div id="result"></div>

  <script>
    async function setupCamera() {
      const video = document.getElementById('webcam');
      const stream = await navigator.mediaDevices.getUserMedia({ video: true });
      video.srcObject = stream;

      return new Promise((resolve) => {
        video.onloadedmetadata = () => {
          resolve(video);
        };
      });
    }

    async function loadTeachableMachineModel() {
      const model = await tf.loadLayersModel('https://teachablemachine.withgoogle.com/models/o49biL0_D/model.json');
      return model;
    }

    async function predictWithTeachableMachineModel(model, video) {
      setInterval(async () => {
        const webcamImage = tf.browser.fromPixels(video);
        const resizedImage = tf.image.resizeBilinear(webcamImage, [224, 224]);
        const normalizedImage = resizedImage.div(255.0);
        const batchedImage = normalizedImage.expandDims(0);

        const predictions = await model.predict(batchedImage);
        const classId = predictions.argMax(1).dataSync()[0];
        const className = await getClassLabel(classId);

        displayResult(className);

        webcamImage.dispose();
        resizedImage.dispose();
        normalizedImage.dispose();
        batchedImage.dispose();
        predictions.dispose();
      }, 5000);
    }

    async function getClassLabel(classId) {
      const labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; // 클래스 레이블 목록
      return labels[classId];
    }

    function displayResult(result) {
      const resultDiv = document.getElementById('result');

      // 5초에 한 번 결과 추가
      resultDiv.innerHTML = `${result}${resultDiv.innerHTML}`;
    }

    async function init() {
      const video = await setupCamera();
      const model = await loadTeachableMachineModel();
      predictWithTeachableMachineModel(model, video);
    }

    init();
  </script>
</body>
</html>```

Test if text has been entered into search box

I have a table which has a search box. I want to check if the text search box has a text value entered in it before performing the “table.row” line (as this just returns the first line in the table if empty, which i don’t want). I have tried using .value and .count but couldn’t get it working. Is there a better way to test if the user has entered text in the box?

    #locTable_filter input {
        border-radius: 5px;
        width: 300px;
        font-size: x-large;
        text-align: center;
    }


        $('#table_filter input').bind('keyup', function (e) {
            if (e.keyCode == 13) {              
                if (count > 0) {
                    //TODO check that Search has some text in it.
                    $(table.row({ search: 'applied' }).node()).click();
                }
});

Thank you.

“Joi.validate is not a function”, in NODE JS and status code is 500

const Joi = require("joi");

module.exports.saveOrganisationInfo = Joi.object({
  org_id: Joi.number(),
  entity_type: Joi.string(),
  vertical: Joi.string().valid("vertical", "industry"),
  location: Joi.string(),
});

this is my validation
this generates an error message when I run my program. the error message is below

    {
    "code": 500,
    "errors": [
        {
            "type": "UNKNOWN",
            "code": 500,
            "name": "CustomError"
        }
    ],
    "message": "Joi.validate is not a function",
    "result": null,
    "isSuccess": false
}

   

How to wait for a specific amount of time precisely in javascript

I’m measuring time between keystroykes when user types some text, using performance.now() and saving it. Now, I want to replay what user has been typing, potentially giving him the ability to race with himself, typing the same text again.

However, if I use the following construction:

for (let ev of events) {
    await new Promise(resolve => setTimeout(resolve, ev.performanceDelay));

    replayKey();
}

I noticed that the text that is being replayed is being typed slower than it has been typed before. For example, I type the whole text in 40 seconds, but replay is running for 45 seconds, rendering any possibility of racing with myself obsolete.

My question is: how can I make it work? Is there a way?
I want to delay an action for a specific amount of time, preferably with precision down to microseconds (output of performance.now()), obviously without hanging the main thread or preventing any other events from occuring.

I don’t mind delving into a specific API of a specific browser, for example Chrome (as I’m running it mainly). Is there a way to make this work?

How can I capture audio for WebRTC applications in all mobile browsers to enable subtitles using Web Speech API?

I’ve implemented a WebRTC application that incorporates real-time subtitles generated from user audio using the Web Speech API speech recognition feature. While desktop browsers function smoothly, mobile browsers consistently encounter an “audio capture failed” error. Can someone guide achieving consistent audio capture functionality across all mobile browsers within my WebRTC application?

here is my code:-

let recognition;
let audioContext; 

let isRecognitionActive = false;

    // Function to create the AudioContext on user gesture
    function createAudioContext() {

        audioContext = localMediaAudioContext; // from my webrtc local audio context
        console.log('NewAudioContext',audioContext)
      }
// Function to initialize speech recognition
function initSpeechRecognition() {
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia ) {

    recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
  recognition.lang = 'en-US';

  recognition.continuous = true;
  recognition.interimResults = true; // Set to false to improve recognition responsiveness

  recognition.onstart = function() {
    console.log('Speech recognition started');
    isRecognitionActive = true;
  };

  recognition.onresult = function(event) {
    const transcript = event.results[event.results.length - 1][0].transcript; 


    sendSpeechTranscript(transcript);
  };

  recognition.onerror = function(event) {
    console.error('Speech recognition error:', event.error);
    if (event.error === 'no-speech') {
      console.log('No speech detected. Restarting recognition...');
      // Restart speech recognition when no speech is detected
      if (!isRecognitionActive) {
        recognition.start();
      }
    }
  };

  recognition.onend = function() {
    console.log('Speech recognition ended');
    // Set recognition active to false when recognition ends
    isRecognitionActive = false;
    // Continue speech recognition indefinitely
    if (!isRecognitionActive) {
      recognition.start();
    }
  };

}
}


// Function to send speech transcript over WebRTC
function sendSpeechTranscript(transcript) {
  // Implement your logic to send the transcript over WebRTC
  console.log('Sending transcript over WebRTC:', transcript);
 
  var data;
  setTimeout(() => {
    $('#transcript').text('You : ' + transcript);
  }, 2000);
  // $('#recognized-text').text('You : ' + transcript);

    if(transcript){
      setTimeout(function() {
        $('#transcript').text('');
      }, 6000);
    }

}

// Call the initSpeechRecognition function to initialize speech recognition
    initSpeechRecognition();

// Attach click event listener to start speech recognition when #idCaption is clicked
$('#CaptionClickevent').on('click', function(){
    // Start speech recognition if not already active
    if (!isRecognitionActive) {
       $(this).addClass('selected');
       if (!audioContext) {
        createAudioContext();
      }
      recognition.start();
          console.log('start recognition');
    }


});

Trying to import a function from JS file into a TS file, but facing ts-file.ts:2:32 – error TS2306 js-file.d.ts’ is not a module error

// js-file.js
function exportFunction() {
  console.log("exported function");
}

// exportFunction();

export { exportFunction };
// js-file.d.ts
declare module "js-file" {
  export function exportFunction(): void;
}
// ts-file.ts
import { exportFunction } from "./js-file.js";

exportFunction();
{
  "compilerOptions": {
    "module": "ESNext"
  },
  "ts-node": {
    "esm": true
  }
}
{
  "type": "module"
}

I am trying to make it work with ESM (it works with commonjs). If I update declaration file to export declare function exportFunction(): void;, I can compile the code and then a new error occurs.

n/ts-file.js:2
Object.defineProperty(exports, "__esModule", { value: true });
                      ^

ReferenceError: exports is not defined in ES module scope

I am trying to debug the issue for a while now but unable to find a solution.

Node mailer not sending email using c panel of godady

Locally everything is fine and working perfectly.
When we have done the hosting the nodemailer is not working at all.
We used godady for hosing and using node js app on the goDady.

I have tried on locally that works good for node mailer on express app.
But when we host the node js app on go dady with cpanel then that is not working for nodemailer, others configurations are okay.
We are using node js version 10