I want to be able to change a variable to true with the click of a button

So i want to make my button so it changes to true in the Script part. This is so a random number will appear in the p element


<!doctype html>
<html>
<button>
random number
</button>
<p id="randomnumber">

</p>



</html>
<script>
if (document.getElementById('button').clicked == true)
{
document.getElementById("randomnumber").innerHTML = (Math.floor(Math.random()*21)+2);

}


</script>

Combine react-easy-crop with react-uploady

I am trying to combine react-easy-crop.js with react-uploady.js but do not succeed. There is an example in which react-uploady is combined with react-image-crop which I am trying to adapt using react-easy-cropper. After selecting a picture to be shown in the cropper I run into an error:

TypeError
Cannot read properties of null (reading 'x')
Cropper.render
https://93p5u.csb.app/node_modules/react-easy-crop/index.js:737:16

and do not know how to proceed.

The codesandbox showing this behavior is here.

How can I avoid this error? How should react-easy-crop be implemented with react-uploady?

Alternatives to Javascript’s with() Statement?

The with() statement is more or less eliminated from modern Javascript. It is not available in strict mode and ES6 modules, TS all that is loaded in strict mode. So what use instead to put unknown variables into a scope?

For example:


function renderTemplateString(template, data) {
    let func
    with(data) {
       func = () => eval('`' + template + '`')
    }
    try {
        return func()
    } catch (error) {
      return `Error in Template ${template}: ${error} in ${JSON.stringify(data)}`
    }
}

console.log(renderTemplateString("foo: ${foo}", {foo: 'bar'}))

Can the same effect (putting all of data into the scope of eval()) archived without with?

comparing different values of two arrays and returning one filtered array in JavaScript

I am trying to compare the values of two different arrays, if the user.id of the volunteer iteration matches the id of the userVolunteer iteration, I want that entry to be filtered out of the volunteers array

current attempt:

  const newBirds = volunteers.filter((volunteer) => {
    return volunteer.user_id !== userVolunteers.some((vol) => vol.id)
  });

newBirds currents returns the volunteers array without filtering any of the entries? Any advice?

Props not getting value from another component

I am new to React and have just been learning about functional components. I am trying to build a Login page that redirects to a Comment section which when submitted, displays the comment text to the Result page. I am trying to pass the comment from Comment component to Result through props but I can’t seem to get it to work. Any thoughts on my code below? Thanks!

Comment.js

import React, { useState, useEffect } from "react";
import auth from "../../auth/auth";
import "./Comment.css";
import { Button, Form, ToggleButtonGroup, ToggleButton } from "react-bootstrap";
import Header from "../Header/Header";

import "bootstrap/dist/css/bootstrap.css";

export default function Comment(props) {
  const [comment, setComment] = useState();
  const [email, setEmail] = useState();

  useEffect(() => {
    // get email address input using getToken()
    const loggedInUser = auth.getToken();

    if (loggedInUser !== "") {
      setEmail(loggedInUser);
    }
  }, []);

  const handleSubmit = (e) => {
    e.preventDefault();
    props.history.push("/result");
  };

  return (
    <div className="comment-wrapper">
      <Header />
      <Form onSubmit={handleSubmit}>
        <div class="row">
          <h3>Course Evaluation</h3>
          <div class="col col-xs-2 col-md-4">
            <Form.Label>Was this a required course or an elective?</Form.Label>
          </div>
          <div class="col col-xs-2 col-md-1">
            <ToggleButtonGroup type="checkbox">
              <ToggleButton value={"required"}>Required</ToggleButton>
              <ToggleButton value={"elective"}>Elective</ToggleButton>
            </ToggleButtonGroup>
          </div>
        </div>

        <div class="row">
          <div class="col col-xs-2 col-md-4">
            <Form.Label>Course Code:</Form.Label>
          </div>
          <div class="col col-xs-2 col-md-4">
            <Form.Control type="text" />
          </div>
        </div>

        <div class="row">
          <div class="col col-xs-2 col-md-4">
            <Form.Label>Course Name:</Form.Label>
          </div>
          <div class="col col-xs-2 col-md-4">
            <Form.Control type="text" />
          </div>
        </div>

        <div class="row">
          <div class="col col-xs-2 col-md-4">
            <Form.Label>Professor Name:</Form.Label>
          </div>
          <div class="col col-xs-2 col-md-4">
            <Form.Control type="text" />
          </div>
        </div>

        <div class="row">
          <div class="col col-xs-2 col-md-4">
            <Form.Label>Email:</Form.Label>
          </div>
          <div class="col col-xs-2 col-md-4">
            <Form.Control type="text" defaultValue={email} disabled={true} />
          </div>
        </div>

        <div class="row">
          <div class="col col-xs-2 col-md-4">
            <Form.Label>Your comments:</Form.Label>
          </div>
          <div class="col col-xs-2 col-md-4">
            <Form.Control
              as="textarea"
              onChange={(e) => setComment(e.target.value)}
              rows={4}
            />
          </div>
        </div>
        <br></br>
        <Button variant="success" type="submit">
          Submit
        </Button>
      </Form>
      <br></br>
    </div>
  );
}

Result.js

import React, { useState, useEffect } from "react";
import auth from "../../auth/auth";
import Comment from "../Comment/Comment";
import { Form } from "react-bootstrap";
import Header from "../Header/Header";

import "bootstrap/dist/css/bootstrap.css";

export default function Result(props) {
  const [comment, setComment] = useState();
  const [email, setEmail] = useState();

  useEffect(() => {
    // get email address input using getToken()
    const loggedInUser = auth.getToken();

    if (loggedInUser !== "") {
      setEmail(loggedInUser);
    }
  }, []);

  return (
    <div className="result-wrapper">
      <Header />
      <Form>
        <div class="row">
          <div class="col col-xs-2 col-md-12">
            <h3>Thank You {email}</h3>
          </div>
        </div>
        <div class="row">
          <div class="col col-xs-2 col-md-12">
            <p>We appreciate your comments: {props.Comment}</p>
          </div>
        </div>
      </Form>
    </div>
  );
}

App.js

import React from "react";
import "./App.css";
import Login from "./components/Login/Login";
import Comment from "./components/Comment/Comment";
import Result from "./components/Result/Result";
import auth from "./auth/auth";
import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <Switch>
          <Route
            path="/comment"
            render={(data) =>
              auth.getLogInStatus() ? (
                <Comment {...data}></Comment>
              ) : (
                <Redirect to={{ pathname: "/" }}></Redirect>
              )
            }
          ></Route>

          <Route
            path="/result"
            render={(data) =>
              auth.getLogInStatus() ? (
                <Result {...data}></Result>
              ) : (
                <Redirect to={{ pathname: "/" }}></Redirect>
              )
            }
          ></Route>

          <Route exact path="/" component={Login}></Route>
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;

Calling variables of a class to run another class

Null pointer exception error in kotlin, calling the parameters of one class to run under another class , Forexample , Class A , it has two variable of EditText, edt1 and edt2 , in Class B , it has two TextViews, txt1 and txt2 ,
declare ” var test = Class A()” and I called them as ” txt1 = test.edt1.text.toString( ) and
txt2 = test.edt2.text.toString( ) ” But null pointer exception , please guide me to avoid this

How to change image every second in map react

Im trying to change my image every second in react inside of a map. However this doesnt seem to be working. Here is my code:

function ImageGrid() {
const {shell, gridImage} = styles
const squishAnimals = [
    '/SquishAnimalDemo(1).png',
    '/SquishAnimalDemo(2).png',
    '/SquishAnimalDemo(3).png',
    '/SquishAnimalDemo(4).png',
    '/SquishAnimalDemo(5).png',
    '/SquishAnimalDemo(6).png',
    '/SquishAnimalDemo(7).png',
    '/SquishAnimalDemo(8).png',
    '/SquishAnimalDemo(9).png'
];
const [images, setImages] = useState(squishAnimals);
const [currentImage, setCurrentImage] = useState(0);

function changeBackgroundImage() {
    let newCurrentImg = 0;
    const noOfImages = images.length;

    if (currentImage !== noOfImages - 1) {
        newCurrentImg += currentImage;
    }

    setCurrentImage(newCurrentImg);
}

useEffect(() => {
    const interval = setInterval(() => changeBackgroundImage(), 1000);

    if (interval) {
        clearInterval(interval);
    }

});

return (
    <div className={shell}>
        {squishAnimals.map((image, index) => {
            return (
                index === 4 ?
                    <img className={gridImage} src={images[currentImage]} alt={`${index}-${image}`}/> :
                    <img className={gridImage} src={image} alt={`${index}-${image}`}/>
            )
        })}
    </div>
);

}

Any help as to why it may not be working would be great. Thanks 🙂

Error while importing file using import command in oclif cli node js

I have created a custom cli by oclif package.

in my run.ts file when I am importing file by import command

import actionCommand from "../package/action/src/commands/config/set/system.js";

when I hover mouse over “../package/action/src/commands/config/set/system.js” it showing me this error.

Cannot find module '../package/action/src/commands/config/set/system.js' or its corresponding type declarations.ts(2307)

but when same file I am importing by using require it working perfectly fine

const actionCommand = require("../package/action/src/commands/config/set/system.js");

here is my code can someone help me how can I access same file by using import

run.ts

import { Command } from "@oclif/command";

//import actionCommand from "../package/action/src/commands/config/set/system.js";
const actionCommand = require("../package/action/src/commands/config/set/system.js");

export default class Run extends Command {
  async run() {
    await actionCommand.run();
  }
}

Run.description = "run the file to test region action";

Pass variable into function to be defined

How do I pass a variable into a function in Javascript to be assigned a value. E.g.:

Why does the variable not get assigned the value 5? And what’s the way around this?

let a
function defineVariable(var2beDefined) {
   var2beDefined = 5
}
defineVariable(a)

console.log(a === 5)

What’s the scope of a closure callback function? [duplicate]

I’ve searched with javascript, scope and closure as keywords, but couldn’t find an answer.

The following node.js javascript should explain the problem:

const fs = require('fs');

function parseFile( source )
{
    let html;
    
    fs.readFile(source, (err, data) => {
        if( err ) throw err;
        
        html=data;
    })
    
    console.log(html); // undefined
    
    return html;
}

parseFile( '<path_to_file>' );

How to assign data to html?

Thank you very much!

Return Rhino host object as primitive value

I’m using an old Mozilla Rhino library (version 1.7.7.1) in my project and I’m struggling to understand how to implement the host object hierarchy properly.

What I’m trying to do is to have a root host object containing a field which is another Scriptable. This field contains an inner map with String keys and another Scriptable object (Map<String, ListObject>). The ListObject contains an inner String collection and custom functions.

I’ve created an example code which contains the example of the host object and the fields. The repository is here.
The included test can be run with mvn test command.

When I try to run the following code everything works as expected:

var objectMap_foo_0 = root.objectMap['foo'][0];
var objectMap_foo_0_split = objectMap_foo_0.split('|');

The root.objectMap['foo'][0] returns string and I can call javascript split function on it.

But I need to be able to run the following as well:

// should return first value in the inner collection as a default and do split on it
var objectMap_foo = root.objectMap['foo'];
// call custom method (length() in this case)
print(objectMap_foo.length());
var objectMap_foo_split = objectMap_foo.split('|');

The root.objectMap['foo'] should return the first value in the inner collection (which is a string) but right now it returns the ListObject object. The current solution lets me call the custom function length() on the object but I’m not able to use the split function as the returned value is not of type string. The error message I get when running the code above is:

org.mozilla.javascript.EcmaError: TypeError: Cannot find function split in object bar|baz. (script.js#14)

Can someone please help me to achieve the desired functionality so both the custom function length() and the javascript split() function can be used?

Grouping elements with parentId, child relationship into groups

I’d like to generate this logic of grouping.

The image is what I’m trying to draw out of the result, it describes the relationship between the children, parent, and grouping
enter image description here

Using this data set

const nodes = [{
        "id": "9",
        "root":true,
        "parentIds": []
    },
    {
        "id": "3",
        "parentIds": [
            "9"
        ]
    },
    {
        "id": "2",
        "parentIds": [
            "3"
        ]
    },
    {
        "id": "4",
        "parentIds": [
            "9"
        ]
    },
    {
        "id": "1",
        "parentIds": [
            "4",
            "5",
            "6"
        ]
    },
    {
        "id": "8",
        "parentIds": [
            "9"
        ]
    },
    {
        "id": "5",
        "parentIds": [
            "8"
        ]
    },
    {
        "id": "7",
        "parentIds": [
            "9"
        ]
    },
    {
        "id": "6",
        "parentIds": [
            "7"
        ]
    }
]

Each node has a parentIds property indicating where it belongs to and grouping them, if there is a 1-1 relationship it adds a new group under the previous one and so on, eventually creating a tree of groups (and nodes if remaining).

My main question is how can apply that logic to what I currently have with the dataset flat array?

After grouping it would return a tree like array structure such as this (color property is irrelevant, its just there for visual aid)

  const tree = [
    {
      groupNumber: 1,
      color: "purple",
      children: [
        {
          groupNumber: 2,
          color: "blue",
          children: [
            {
              groupNumber: 4,
              color: "green",
              children: [{ nodeId: "6" }, { nodeId: "7" }],
            },
            {
              groupNumber: 5,
              color: "yellow",
              children: [{ nodeId: "5" }, { nodeId: "8" }],
            },
            { nodeId: "1" },
            { nodeId: "4" },
          ],
        },
        {
          groupNumber: 3,
          color: "red",
          children: [{ nodeId: "2" }, { nodeId: "3" }],
        },
        { nodeId: "9" },
      ],
    },
  ];

Building Json Object from Vue input fields

Im trying to generate a JSON object with a vue method and using vue input data fields to build part of the JSON object. My input files accept a key and a value and i have two default values ‘zone’ and ‘capping’. My goal is for the JSON object to be like:

{
"zone":{
  "capping":{
    "duration": 300
  }
 }
}

But instead i get a JSON object like this:

{
   "zone":{
      "capping":{
         "values":[
            {
               "key":"duration",
               "value":"300"
            }
         ]
      }
   }
}

This is my vue method:

generateJson() {
      const values = this.inputs
      const loopedObj = values.forEach((item) => {
        const val = {
          ...item
        }
        return val
      })
      console.log(values)
      const jsonValues = {
        zone: {
          capping: {
            values
          }
        }
      }
      console.log(JSON.stringify(jsonValues))
    }

This is the Vue code for the input fields:

<div>
          <p>3- Add Data</p>
          <button @click="showInput">+</button>
          <div v-for="(input, k) in inputs" :key="k">
            <input v-model="input.key" type="text" @change="getKey($event)" />
            <input
              v-model="input.value"
              type="text"
              @change="getValue($event)"
            />
          </div>

Any advice? Many thanks.

Cypres – mochawesome reports – reportDir

I am trying to implement dynamic path to mochawesome reports for different browsers
e.g for example, for chrome it is supposed to be cypress/reports/chrome/mocha

This is my cypress.json configuration for reporter

 "reporter": "cypress-multi-reporters",
"reporterOptions": {
    "reporterEnabled": "mochawesome",
    "mochawesomeReporterOptions": {
        "quiet": true,
        "overwrite": false,
        "html": false,
        "json": true

    }
},

And this is how I’m trying to run tests with custom reporterDir

"cypress run --spec cypress\integration\filter\*.js --browser chrome --headless --config-file config.json --config videosFolder=cypress\videos\chrome downloadsFolder=cypress\downloads\chrome --reporter mochawesome --reporter-options reportDir=cypress/reports/chrome/mocha"

but it doesnt work. Reports are saved under path from cypress.json. I tried different syntax many times but I just can’t make it work. I need it because my tests will be launched on many browsers and I want to make reports directory well organised.

Website that pulls data from a text file on every reload, not pulling data

I am trying to build a to-do list that I can display on my office TV that reloads every minute, I will be emailing a service account and creating code for it to add/remove tasks at a later date. I’m currently just trying to get the site to pull the tasks from a text file and update the site, but it is not pulling the data. I feel like I may have something wrong here, if anyone can help it would be much appreciated.

Both the index.html and todo.txt files are in the same directory.

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf8" />
  <script type="text/javascript">
    function refresh() {
      var req = new XMLHttpRequest();
      console.log("Grabbing Value");
      req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
          document.getElementById('ToDo').innerText = req.responseText;
        }
      }
      req.open("GET", 'ToDo.txt', true);
      req.send(null);
    }

    function init() {
      refresh()
      var int = self.setInterval(function () {
        refresh()
      }, 10000);
    }
  </script>
</head>

<body onload="init()">
  <div id="main">
    <div id="updateMe">
      <h2>To-Do List</h2>
      <h1 id="ToDo"></h1>
    </div>
  </div>
</body>
</html>

ToDo.txt contents

Purchase Things