cannot execute javascript code in a jupyter notebook

I’m working on a custom jupyter notebook ui using the jupyterlab APIs. However, I am running into an issue where I am not able to execute javascript code on my custom frontend. I am not sure why that is. I am able to run this magic command on the default jupyter lab ui and on the classic jupyter notebook ui (on the same server image that is running all 3 of these interfaces)

I’ve tried to “trust” this notebook, but it still doesn’t allow me to execute js through the magic functions.

How can I enable inline javascript to be executable in a jupyter notebook? Surely it must be possible, but the jupyter documentation doesn’t mention anything about enabling/disabling magic javascript

jupyter magic documentations

enter image description here

How to filter through cards in HTML

I’m trying to create a site which allows you to search through different profiles by their first name. I’m trying to use bootstraps “data-title” to search through, but it isn’t working. Right now it just displays the entire row.

This is my main code

<!--create search bar-->
<div class="search-bar">
 <!--<a href="#about">Search Profies</a> -->
  <input type="text" placeholder="Search.." id="search-box">
  <button type="searchButton">Search</button>
  <button type="recButton">Recommend</button>
  <button type="filterButton">Filter</button>
  

  <!--create line break before profiles-->

  <div class="line-break">
      <hr>

  </div>

  <!---create row 1 of profiles-->

  <div class ="container-fluid">
    <div class="row">
      <div class ="col-2" >
        <div class="card" data-title="terry">
          <img src="https://api.time.com/wp-content/uploads/2017/12/terry-crews-person-of-year-2017-time-magazine-2.jpg" class="img-fluid" alt="Avatar" style="height: 150px; width: 188px;">
            <h6><b>Terry Crews</b></h6>
        </div> 
      </div>
      <div class ="col-2">
          <div class="image" data-title="cute">
            <img src="https://api.time.com/wp-content/uploads/2017/12/terry-crews-person-of-year-2017-time-magazine-2.jpg" style = "width: 150px;height: 150px;"alt="">
            <h3>cute animal</h3>
         </div>
     </div>
     <div class ="col-2">
      <div class="card">
        <img src="https://api.time.com/wp-content/uploads/2017/12/terry-crews-person-of-year-2017-time-magazine-2.jpg" class="img-fluid"alt="Avatar" style="height: 150px; width: 188px;">
        <h6><b>Terry Crews</b></h6>
    </div>
 </div>
 <div class ="col-2">
  <div class="card">
    <img src="https://api.time.com/wp-content/uploads/2017/12/terry-crews-person-of-year-2017-time-magazine-2.jpg"class="img-fluid" alt="Avatar" style="height: 150px; width: 188px;">
    <h6><b>Terry Crews</b></h6>
</div>
</div>

This is my script


  <script>

let searchBox = document.querySelector('#search-box');
   let images = document.querySelectorAll('.container .row .col-2 .card');
   
   searchBox.oninput = () =>{
      images.forEach(hide => hide.style.display = 'none');
      let value = searchBox.value;
      images.forEach(filter =>{
         let title = filter.getAttribute('data-title');
         if(value == title){
            filter.style.display = 'block';
         }
         if(searchBox.value == ''){
            filter.style.display = 'block';
         }
      });
   };


  </script>

I have tried to use data-title in col-2, and the cards but neither work.

increment loop based on iframe load

i need to get the increment loop based on max, so if the increment inside the iframe load is reach the max, the increment is back to 1 2 3 … here’s the code i’ve try

<script type="text/javascript">
var n = 1;    //based on page access ex:1
var max = 8;    //based on the array data ex:8
$('#iframe').on('load', function() {
    var i = n++;
    var l = ( (i-1) != max) ? 1 : i;
    var el = $('div[id^="detail_'+l+'"]')
    var k = el.attr('key')
});
</script>

the problem is when i’ve reach the max 8 and successfull back to 1, the next load is going to 10 not going to loop 1 to 8 again.
it would be nice if you guys have a suggestion. thank

Chrome extension to listen for when a “subscriber form” popup is rendered on a site and automatically inject name, email into the popup’s form

I am learning to code and starting with browser plugins for practice.
I have a plugin project where I have to do the following:

  1. Listen for what tab (and url) the user is currently on
  2. Listen for if a JS popup is rendered (specifically any of the popular popups that help sites grab new subscribers)
  3. Automatically inject the popup’s subscriber form the name and email I have pre-approved the plugin to share

I think I have step 1 working right with the code below (I tested it with console.log statements.

chrome.tabs.onActivated.addListener(tab => {
chrome.tabs.get(tab.tabId, current_tab_info => {

});
});

If this is correct, what code should I add inside the chrome.tabs.get function to make steps 2 and 3 above work as intended?

Thank you for your support.

Best,
N

The code above works fine, I am not sure how to proceed with steps 2 and 3 above.

Get X, Y position in canvas

In JS, we could use Element.getBoundingClientRect() to get element’s X and Y coordinates.
But what if we want to know the X,Y coordinates of an element in canvas

The closet thing I could think about is CanvasRenderingContext2D.isPointInPath() to check without a point exists in the shape. Is there a built-in function or any way to get X and Y coordinates of a shape in canvas?

For example,

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');

ctx.rect(10, 10, 100, 100);
ctx.fill();
canvas{
width:200px;
height:200px;
background:red;
}
<canvas></canvas>

Is there a way I get the top/left coordiates of the black rect?

Any answers will be appreicated.

Having one text.txt file and the bot chooses a component of it randomly with discord.js

i want to make a joke bot. (just for some friends on my server). I dont want to use an api. But instead make a big text.txt file with the jokes in it. I managed to let the bot respond when I message: test. It responds with a “joke” from the txt file. It only haves one joke in it tough. Now I want to have more jokes in it. And let the bot randomly choose from one of the jokes. The thing is, I dont know how to make the jokes be seperated so the bot can actually choose randomly from it. Here is my code so far:

client.on("message", msg => {
  var textart = fs.readFileSync('./textart.txt', {"encoding": "utf-8"})
  if(msg.content === `test`) {
     msg.channel.send(textart)
  }
  
  
})

I also dont know how to make the bot choose randomly between those jokes too( I’m an beginner so I need some more help with coding) Is there someone thats able to help me out?

How do you use data that was passed into a component in a function?

I have a functional component that has been passed data ({clicked}) from its parent function, but when I try to use it as a variable in my function, it errors out. Here is my current code:

function Songs({clicked}) {

    const songListFiltered = songList.filter(item => item.{clicked} === true) 
    const songDisplayed = songListFiltered[Math.floor(Math.random() * songListFiltered.length)] 
    return (
        <div className="song-box">
            <img src={songDisplayed.artwork} alt="album artwork" />
            <h3>{songDisplayed.songName}</h3>
            <p>{songDisplayed.artistName}</p>
        </div>
    )
}

I need to check if songList has the data in {clicked}, in order to filter those songs from the list, but I’m not sure how to make it work. Would love any help!

Control with the duration of a mouse press instead of the number of a mouse press

I coded this:

$("#scroll-to-left-button").on("mousedown", function() {
  var x = $("#scroll-area").scrollLeft();
  $("#scroll-area").scrollLeft(x - 10);
});


$("#scroll-to-right-button").on("mousedown", function() {
  var x = $("#scroll-area").scrollLeft();
  $("#scroll-area").scrollLeft(x + 10);
});
#container {
  width: 50%;
  height: 100px;
  background-color: grey;
  position: relative;
}

#scroll-area {
  white-space: nowrap;
  overflow-x: auto;
  height: 100%;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<div id="container">
  <div id="scroll-area">
    <div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
  </div>
</div>

<button id="scroll-to-left-button">Scroll to left</button>
<button id="scroll-to-right-button">Scroll to right</button>

You need to click the buttons pretty often to navigate through this container. Is there a way to let it based on the duration of the mouse press? Like if you keep the mouse pressed, it continues constantly scrolling? And if you stop, it stops.

Would be happy if someone could help me.

Trouble with AWS CognitoIdentityServiceProvider

I’m trying to call the adminGetUser function through the AWS CognitoIdentityServiceProvider. The initialising looks fine to me, but i’m getting the following error.

[Nest] 43  - 03/29/2022, 9:18:43 AM   ERROR [ExceptionHandler] Cannot read properties of undefined (reading 'CognitoIdentityServiceProvider')
TypeError: Cannot read properties of undefined (reading 'CognitoIdentityServiceProvider')
at new UsersService (/usr/src/app/src/users/users.service.ts:21:36)
at Injector.instantiateClass (/usr/src/app/node_modules/@nestjs/core/injector/injector.js:301:19)
at callback (/usr/src/app/node_modules/@nestjs/core/injector/injector.js:48:41)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at Injector.resolveConstructorParams (/usr/src/app/node_modules/@nestjs/core/injector/injector.js:124:24)
at Injector.loadInstance (/usr/src/app/node_modules/@nestjs/core/injector/injector.js:52:9)
at Injector.loadProvider (/usr/src/app/node_modules/@nestjs/core/injector/injector.js:74:9)
at async Promise.all (index 3)
at InstanceLoader.createInstancesOfProviders (/usr/src/app/node_modules/@nestjs/core/injector/instance-loader.js:44:9)
at /usr/src/app/node_modules/@nestjs/core/injector/instance-loader.js:29:13

Following this code:

import AWS from 'aws-sdk';
import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { User } from 'models/user.entity';
import { CreateUserDto } from './dto/create-user.dto';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class UsersService {
  config = {
    apiVersion: '2016-04-18',
    region: 'eu-central-1',
  };

  cognitoIdentity: AWS.CognitoIdentityServiceProvider;

  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {
    this.cognitoIdentity = new AWS.CognitoIdentityServiceProvider(this.config);
  }

  async findByCognitoSub(cognitoSub: string): Promise<User | undefined> {
    const result = await this.usersRepository.find({ where: { cognitoSub } });
    if (result.length !== 1) {
      return undefined;
    }
    return result[0];
  }

  getUser(userPoolId: string, userName: string) {
    return this.cognitoIdentity.adminGetUser({
      UserPoolId: userPoolId,
      Username: userName,
    });
  }

Any help would be greatly appreciated!

node js: run program and get stdout

Iam newb in node.js

Is there a working example where the stdout is returned?

Tried many options, none of them returns stdout to me, only an error if there is one

in C# my program returns fine


exec.execSync("test.txt -arg=xxx", function callback(error, stdout, stderr) {
   if (error) console.log(error);
   if (stdout) console.log(stdout);
   if (stderr) console.log(stderr);
 });```

How do I add multiple variables efficiently?

I am trying to add multiple variables efficiently.

<script>
    var var1 = 6
    var var2 = 3
    var var3 = 8
    var var4 = 2
    var var5 = 9

    var varnumtotals = var1 + var2 + var3 + var4 + var5;
</script>

How do I do this more efficiently?
A way that can function for 10000 variables?

text
var varnumtotals = var1 + var2 + var3 + var4 + var5;

Cloudfare images API

I’m trying to use the upload images API in Cloudfare without any success.
I read the docs, but they are very poor and I can’t understand them at all. They also give me a CUrl that returns an error when you run it…

curl -X POST -F file=@./https://www.datocms-assets.com/45562/my-file.png -H "Authorization: Bearer my-key" https://api.cloudflare.com/client/v4/accounts/my-user-id/images/v1

Currently, my code consists in:

export default async (req: NextApiRequest, res: NextApiResponse) => {
  const formData = new FormData();

  formData.append(
    "file",
    request(
      "https://www.datocms-assets.com/45562/my-file.png"
    )
  );

  try {
    await fetch(
      "https://api.cloudflare.com/client/v4/accounts/my-user-id/images/v1",
      {
        method: "POST",
        headers: {
          Authorization: `Bearer my-key`,
          "Content-Type": "multipart/form-data; boundary=abcd",
        },
        body: JSON.stringify(formData),
      }
    ).then((uploadRes) => {
      return res.status(200).send(
        uploadRes.text().then((resolved) => {
          console.log(resolved);
        })
      );
    });
  } catch (err) {
    console.log(err);
  }
};

And this returns an ERROR 5400: Bad request: incomplete multipart stream, and I can’t figure out what that is.

I also tried this:

export default async (req: NextApiRequest, res: NextApiResponse) => {

  try {
    await fetch(
      "https://api.cloudflare.com/client/v4/accounts/c6e775850575d70aad58b5fdb9c1a248/images/v1",
      {
        method: "POST",
        headers: {
          Authorization: `Bearer b-Mpt1qldqNuM5cmcp3WP7_zqHhpxMdlaauj8ady`,
          "Content-Type": "multipart/form-data; boundary=abcd",
        },
        body: JSON.stringify({
          file: "https://www.datocms-assets.com/45562/1648253640-blog_scale_treehacks_cover.png"
        }),
      }
    ).then((uploadRes) => {
      return res.status(200).send(
        uploadRes.text().then((resolved) => {
          console.log(resolved);
        })
      );
    });
  } catch (err) {
    console.log(err);
  }
};

But it doesn’t work neither.

Can someone help me please? thanks

Remove empty array from array of objects

I have an array of object arrays, and one of the dates is empty, I would like to remove that empty date.

const arr = [
  {
    "2022-03-10": [
      { "Age": "31", "Last": "Craig", "Name": "Carlos", "Time": "11:00am - 12:00pm", "Type": "Consulta General", "read": false }
    ],
    "2022-03-26": [
      { "Age": "31", "Last": "Craig", "Name": "Carlos", "Time": "11:00am - 12:00pm", "Type": "Follow Up", "read": false }
    ],
    "2022-03-27": [],
    "2022-03-31": [
      { "Age": "31", "Last": "Craig", "Name": "Carlos", "Time": "11:00am - 12:00pm", "Type": "Valoraciones Funcionales", "read": false }
    ]
  }
];

What I’ve tried

list.push(doc.data());
var filtered = list.filter(function (el) {
  return el != " ";
});

I would like to keep the same array, just without the “2022-03-27” item.

Error when redeploying my react app with nodemon it keeps sayings “Plugin “react” was conflicted between “package.json » eslint-config-react”-app »

I’m starting a new React app and if I start it with npm start I have no problem but if I start it with nodemon I start having Plugin "react" was conflicted between "package.json » eslint-config-react-app » each time I redeploy my application :

Console screenshot

Error’s Screenshot

I have read this topic : Error when deploying react app and it keeps sayings << Plugin “react” was conflicted between “package.json » eslint-config-react-app » >> and each time I save my package.json the error disappears and each time I change my code it comes back.

I tried :

  • removing my node_modules folder and npm install
  • downgrading eslint-config-react-app to the version 6

I am still very new to nodeJS development, I don’t know what I am doing wrong.

Thanks in advance