How to execute an external html/javascript file

The scenario for my frontend javascript application is as following:

  1. GET via URL an html/javascript file
  2. execute it

Current I am trying the following frontend approach:

const myElement = document.createElement('myElement');
myElement.setAttribute('src', 'https://.../file.html');
document.body.appendChild(myElement);

And file.html looks like:

<html>
  <head>
    <script language="Javascript">
      function doSomething() { }
    </script>
  </head>
  <body onload="doSomething()"></body>
</html>

But nothing is happening.

Am I wrong to expect that on document.body.appendChild() , the file will be downloaded and executed as if the URL was opened from the browser?

I’m very new to coding, why does my JavaScript code say “Unexpected token return”?

I am new to JavaScript but I have been using Snap! and Scratch for a long time, I am trying to make a reporter block in Snap! where you can enter a decimal value and it will return that value in hexadecimal. The code is relatively short, but that’s where it gets me. return(Number(255).toString(16))
Now, you’re probably thinking that I can just do console.log instead of return, but that doesn’t work because this is a JavaScript function and is not running on standalone JS.
Here are a couple of images for proof.
error image and block code
Somebody please help me with this! I would greatly appreciate it.

A delete button in React component cannot get the useState from page

I am making a Google Map API app. But I have a trouble calling the setMarker(useState) from the component.

It said marker and setMarker are not defined.

I want to make a table to show my search location results and store to the useState(markers). It works, however, when I want to delete the location results by click the button, it’s not work. What should I do to make a delete button. Thanks

My Map.js/App.js

import React, { useState, useEffect, useRef } from "react";
import {
  GoogleMap,
  useJsApiLoader,
  Marker,
  StandaloneSearchBox,
} from "@react-google-maps/api";

import Tablerecord from "../components/Tablerecord";

const libraries = ["places"];

const containerStyle = {
  width: "100%",
  height: "400px",
};

const inputStyle = {
  width: "100%",
  height: "500px",
};

const center = {
  lat: 22.7658314,
  lng: -22.4137297,
};

const options = {
  disableDefaultUI: true,
  zoomControl: true,
};

function App() {
  const [markers, setMarkers] = useState([]);
  const searchBox = useRef(null);

  const [searchPlaceCenter, setSearchPlaceCenter] = useState([
    parseFloat(43.7658314),
    parseFloat(-79.4137297),
  ]);

  const { isLoaded } = useJsApiLoader({
    id: "google-map-script",
    googleMapsApiKey: "API-KEY",
    libraries,
  });

  return isLoaded ? (
    <div>
      <StandaloneSearchBox
        onLoad={(ref) => (searchBox.current = ref)}
        onPlacesChanged={async (event) => {
          await // Find the search field value and make it be center value.
          setSearchPlaceCenter([
            parseFloat(
              searchBox.current.getPlaces()[0].geometry.location.lat()
            ),
            parseFloat(
              searchBox.current.getPlaces()[0].geometry.location.lng()
            ),
          ]);
          //  Store Search geolocation value to useState markers for Red markers
          setMarkers((current) => [
            ...current,
            {
              lat: searchBox.current.getPlaces()[0].geometry.location.lat(),
              lng: searchBox.current.getPlaces()[0].geometry.location.lng(),
              name: searchBox.current.getPlaces()[0].formatted_address,
              time: new Date(),
            },
          ]);
        }}
      >
        <input
          type="text"
          name="address"
          placeholder="Search Address"
          autoComplete="off"
          style={{
            boxSizing: `border-box`,
          }}
        ></input>
      </StandaloneSearchBox>

      <GoogleMap
        mapContainerStyle={containerStyle}
        zoom={8}
        //  Set center to searchPlace location to change center
        center={{
          lat: parseFloat(searchPlaceCenter[0]),
          lng: parseFloat(searchPlaceCenter[1]),
        }}
        options={options}
      >
        {markers.map((marker) => (
          <Marker
            key={marker.time.toISOString()}
            position={{
              lat: parseFloat(marker.lat),
              lng: parseFloat(marker.lng),
            }}
          />
        ))}
      </GoogleMap>

      {/* !!!!!!!!Here is my question !!!!!!*/}
      {markers.map((marker) => (
        <div>
          <Tablerecord key={marker.time} marker={marker} />
        </div>
      ))}
    </div>
  ) : (
    <div>Loading...</div>
  );
}

export default React.memo(App);

My Tablerecord.js(component)

import React, { useState } from "react";
import styles from "../styles/tablerecord.module.css";

const Tablerecord = (marker) => {


  const handleRemoveLocation = (e) => {
    const name = e.target.getAttribute("name");
    setMarkers(markers.filter((item) => item.name !== name));
  };

  return (
    <div className={styles.table}>
      <center>
          {/* This work, can show name,lat and lng */}
        <p name={marker.marker.name}>Name: {marker.marker.name}</p>
        <p>
          lat: {marker.marker.lat}, lng: {marker.marker.lng}, Added Time:{" "}
          {marker.marker.time.toTimeString()}
        </p>

        {/* Delete button I want to ask */}
        <button name={marker.name} onClick={handleRemoveLocation}>
          x
        </button>
      </center>
    </div>
  );
};

export default Tablerecord;

Office schema URI – doc opened in read only mode

I have a word document that sit in a website in my iis,

When I’m opening the document with office uri from js like this :

window.open(“ms-word:ofe|u|http://machinenumber:8090/test/abc3.docx”),

the doc opened in word but in read only mode,

that cause that when i save the document it opened as save as,

I want the document will open in editing mode,

My user, iis_iusrs, and the user running the app pool have full permissions to the website and the folder,

When i open the doc directly from folder it opens in editing mode,

Thank you

How to use import keyword with an old package insted of using rquire in Nodejs

I’m working on a command-line interface package and I’m using some external packages that work fine with Node.js 14+ and ESM modules.
I need to use Node.js 14+ to be able to use top-level await and import(ESM).

Now, one package that I couldn’t use import with is get-video-duration package.

I already wrote the code using this package in another project and it works fine using rquire keyword, but when replacing it with the import keyword it produces an error that is shown below.

import getVideoDuration from 'get-video-duration';
const getVideoDurationInSeconds = require('get-video-duration');

the first line above produces an error, the second one works fine.

also, require is not defined in ES module, so I need to use import

there’s a closed issue on their original GitHub page, nothing useful https://github.com/caffco/get-video-duration/issues/87

is there any way to fix this error or even a way to use require with ESM? and why does this error only appears when using import?

$ node app.js 
C:Users...media-duration-packagenode_modulesnode-ffprobe-installerindex.js:43
        throw new Error('Could not find ffprobe executable, tried "' + npm3Binary + '" and "' + npm2Binary + '"');
              ^

Error: Could not find ffprobe executable, tried "C:Program [email protected]" and "C:Program [email protected]"
    at Object.<anonymous> (C:Users...media-duration-packagenode_modulesnode-ffprobe-installerindex.js:43:8)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (C:Users...media-duration-packagenode_modulesget-video-durationdistcommonjsindex.js:46:32)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)

I already tried to add these packages (@ffprobe-installer, node-ffprobe-installer) but not worked.

Adapt default behavior for dynamicly created elements

While working with JQuery and JQuery UI for the first time I created a code snipped which allows to drag, resize and create new blocks. The code runs fine so far. The problem: New (dynamicly) created blocks don’t adapt the behavior of the predefined ones (its not possible to move or resize them). So how can I assign them the same behavior as the static (predefined blocks)?

The onclick event could maybe solved by using event bubbling – but I’m not really sure about that. But what are “draggable” and “resizeable”? They aren’t functions – are they??

Thanks for your support (and sorry for my bad English). 🙂

Code:

<!DOCTYPE html>

    <head>
        
        <link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
        <script type="text/javascript" src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
        
        <style>
            html, body, #container { min-height:100%; }
            #dropHere { height:400px; background-color:mediumslateblue; }
            .box { background-color:#fff; position:absolute;}
        </style>

    </head>
    
    <body>

        <div id="dropHere">
            <div id="box-1" class="box" style="width:100px; height:100px; left:50px; top:30px;"></div>
            <div id="box-2" class="box" style="width:100px; height:100px; left:120px; top:150px;"></div>
        </div>

        <button type="button" id="new" class="btn btn-outline-primary">Neue Box</button>


        <script type="text/javascript">

            $('.box')
            .click( function() {
                console.log("Klick!");
            })
            .draggable({
                containment: $('body'),
                snap:true,
                snapTolerance:60,
                snapMode:"outer",
                drag: function(){
                    console.log("Dragging");
                },
                stop: function(){
                    console.log("Dragging stopped");
                },
                revert: 'invalid'
            })
            .resizable({ 
                handles: "e, w, n, s",      
                stop: function(event, ui) {
                    console.log("Resizing stopped");
                }
            });
            

            $('#dropHere').droppable({
                accept: '.box'
            });


            $( "#new" ).click(function(e) {
                $("#dropHere").append('<div id="box-a" class="box" style="width:100px; height:100px; left:200px; top:250px; background-color:yellow;"></div>');
                e.preventDefault();
            });

        </script>
    </body>
</html>

Can’t add files to Firebase using Vue.js + Vuetify

this is my first time using both Vuetify and Firebase.

Following a tutorial, I was trying to add some data to my db in firebase (not images).

After installing firebase in my project with npm, I’ve set it up in a separate js file like this:

import { initializeApp } from "firebase/app";
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';
import { getAnalytics } from "firebase/analytics";

const firebaseConfig = {
  apiKey: "AIzaSyBHaHS-mq4TjrBcRdQq1m-h9FueoF7CdoY",
  ...
  ...
};


const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const db = getFirestore(app);

In the vue.js file where I have the form for the new object with data that I want to add, I’m trying to do like this:

Template:

<template>
    <v-dialog max-width="600px">
        <v-btn flat slot="activator" class="success">
            Add new project
        </v-btn>
        <v-card>
            <v-card-title>
                <h1 class="display-1">Add a new project</h1>
            </v-card-title>
                <v-form class="px-3" ref="newProjectForm">
                    <v-card-text>
                        <v-text-field label="Title" v-model="title" prepend-icon="folder" :rules="inputRules"></v-text-field>
                        <v-textarea  :rules="inputRules" label="Information" v-model="content" prepend-icon="edit"></v-textarea>

                    <v-menu>
                        <v-text-field :rules="inputRules" slot="activator" :value="formattedDate" label="Due date" prepend-icon="date_range"></v-text-field>
                        <v-date-picker v-model="due"></v-date-picker>
                    </v-menu>

                    <v-spacer></v-spacer>
                    
                    <v-btn flat class="success mx-0 mt-3" @click="submit">Add project</v-btn>
                    </v-card-text>
                </v-form>
        </v-card>
    </v-dialog>
</template>

Script:

import format from 'date-fns/format'

import parseISO from 'date-fns/parseISO'

import db from '@/fb'

export default {
    data(){
        return{
            title : "",
            content : "",
            due : null,
            inputRules: [
                v => v.length >= 4 || "Minimum length is 3 characters ",
            ]
        }
    },
    methods:{
        submit(){
            if(this.$refs.newProjectForm.validate()){
                // console.log(this.title,this.content,this.due);
                const project = {
                    title: this.title,
                    content: this.content,
                    due: format(parseISO(this.due), 'eee do MMMM y'),
                    person :'myself',
                    status: 'ongoing'
                }

                db.collection('Listify').add(project).then(() => console.log('added to db'))
            }
        }
    },
 computed: {
    formattedDate () {
      console.log(this.due)
      return this.due ? format(parseISO(this.due), 'eee do MMMM y') : ''
    }
  }}
</script>

The error logged is “TypeError: Cannot read properties of undefined (reading ‘collection’)”

I know I am probably importing something the wrong way, but I am very new to this and I didn’t get a good grasp at it yet.

I want to upload the object coming from the form to the Firebase db, can you help me and explain to me why it wasn’t working?

Cant make requests to googlevideo.com

so this might sound dumb, but I was wanting to make requests to googlevideo.com sites (as in https:// rr3—sn-nx57ynsl.googlevideo.com/ for example) but it it never goes through with the request, and stays idle until it eventually returns with no data. It only happens in a Node instance, but in the browser the request works just fine

the download url is just a 1mb mp3 file, less than 1mb in size. the request should return binary data of the audio, but again, it never finishes it.

Here’s my code:

request({url:downloadUrl, encoding:null}, function (error, response, body) {
    //code that is never reached
    console.log(body); //should be binary data
});

How do I pass a variable into regex with Node js?

So basically, I have a regular expression which is

var regex1 = /10661" class="fauxBlockLink-linkRow u-concealed">([sS]*?)</a>/;

var result=text.match(regex1);
user_activity = result[1].replace(/s/g, "")
console.log(user_activity);

What I’m trying to do is this

var number = 1234;
var regex1 = /${number}" class="fauxBlockLink-linkRow u-concealed">([sS]*?)</a>/;

but it is not working, and when I tried with RegExp, I kept getting errors.

Array(or any iterable) unpacking in Java [duplicate]

Recently, faced an issue with unpacking values from array. So in my application some method returns array of integers which I need to unpack.

Like this in Python: a, b, c = triangle.getSides() where getSides() returns a tuple of 3 elements. Or like this in JavaScript: const [a, b, c] = triangle.getSides() where getSides() returns an array of 3 elements.

So my question is, how can I implement something similar in Java?

My App Component will not render with React

I am doing React project with typescript form scratch, and for some reason, I can’t get the App component to render. I know the file path is correct. The Error says: Module not found: Error: Can’t resolve ‘./App’ in ‘/Users/michaelhorvilleur/Desktop/Codecademy/react-porfolio/src’

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(<App />, document.getElementById("#root"));
import React, { useState } from "react";

const App = () => {
   return (
    <div>
      <h1>App</h1>
    </div>
  );
};

export default App;

React Components Rendering Error in Electron-React-Boilerplate(Multiple Errors)

Good Afternoon all,

I am trying to import some React components from another application of mine, into my new Electron-react-boilerplate  app. The app is supposed to function as a downloadable music-player application. I am new to Electron.js, and I am having a couple rendering errors with my application, (most probably due to a simple error).

I wanted ya’ll to see my code, so I tried to push my entire electron-boilerplate file into my own git repository, but it wasn’t working so I decided that I should at least provide a reproudcible example of my code, so that my issue is still understandable. I ended up using theelectron-quick-start template as a temporary subsitiute, and I just imported some of the boilerplate folders as well as some of my own, so that problem is more clear.(link to my repo below)

What I Have So Far:

As previously stated, I am trying to import some React components from another application of mine, into my new Electron-react-boilerplate  app. The app is supposed to function as a downloadable music-player application. It contains 4 playlists Turkish.js , House.js, Rock.js, and Persian.js, and the user can listen to music from any of these 4 genres.

I imported these following folders from my old react.js application:

the public folder (contains images for the playlists)

the src folder which includes:

components folder .

In the components folder are the folllowing:

  • Navbar folder( named as: “NavbarA”, contains some routing as well).
  • Music folder(where the .mp3 files are loaded to my application via drag-drop.
  • firebase.js folder (included firebase web-authentication).
  • As well as my playlist components (Turkish.js , House.js, Rock.js, and Persian.js) , and their child components that are designated for styling purposes like the “..Card.js” and “…Button.js” components.

And I also added the __tests__,main,and renderer folders into my src folder as well.

After I imported all of this, I changed some aspects of App.tsx, so that I can reference the NavbarA component, wrapped in a react-router.

The Problem:

I received two visible errors:

Error 1: (Music/.mp3 module parse fail)

(Same Error for all .mp3 files), for example I am also getting these errors as well:

ERROR in ./src/components/music/turk1.mp3 1:0
ERROR in ./src/components/music/house1.mp3 1:0
ERROR in ./src/components/music/persian1.mp3 1:0

ERROR in ./src/components/music/rock1.mp3 1:0
Module parse failed: Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
 @ ./src/components/Rock.js 34:36-64
 @ ./src/components/NavbarA.js 40:31-48
 @ ./src/renderer/App.tsx 11:34-63
 @ ./src/renderer/index.tsx 10:30-46

To clarify, this error does not only pertain to rock1.mp3, I received this error for all .mp3 music files. Any idea on how to import audio in my application? How did I do it incorrectly? What is the correct import method to process this file?

Error 2: (blank screen logs string “Cannot GET /index.html”

I am currently getting back a blank screen with that error , and am not sure why.It could be possible that I am not rendering my components correctly, (possibly in the wrong folder). It can also be a routing issue, but I am not certain.

this is the error I recieved after doing npm start

(Picture of Screen Attached Below)

enter image description here

My Code Is Here:

You can look at it here:

link to git repository –
https://github.com/ZpoDavay/electronboilerplate-simple

Let me know what you think!

Best,

Zpo.

Javascript function does not execute on page load but executes when called from Console Window

I have a javascript function to append options on a select input field.
Below is code snippet:

function loadZoneDropDown(){
    var datas = placesZoneData.zones, a = document.getElementById("route_start_point");
    for(let t in datas){
        var value_data = datas[t];
            $('#route_start_point').append('<option value="'+t+'">'+value_data.data["name"]+'</option>');
        
    }
    sortSelectList(a);
}

This function is called inside a load() function on the <body> tag as below:

function load(){
   //otherFunctions();
    loadZoneDropDown();
}

HTML code:

<html>
  <head></head>
  <body onload="load()">
  </body>
</html>

The page loads and No new option is appended to the #route_start_point select field. When I run the same function directly on console, the script executes and the options are populated.
Can you help me figure the problem out.
Note that otherFunctions() are running very OK and fine on the webpage.