Subscribe one one Item and read multiple other ones

i try to create a opc-ua-client with the “node-opcua”-npm package (NodeJs) to do the following thing:
I wan`t to subscribe to one item and every time this value changed i want to do a simple read on about 200 other variables to save it in a file or a database.

The Background is that my Subscription-Item is a Counter that counts + 1 when a new dataset is availible. Then i wan`t so save a couple of other sensor values to make some analyses afterwords.

What is the best way to do that?
I donĀ“t really get it run by myself.

Please support

How to Change Button text in React using useState

I have a button with Text Click View Price. I am displaying Amount when button is clicked.

I want to change the button value to priceVar = "Reset Price"; which is not happening in my case. I am able to set value to 0.

How can I set button text to Reset Price again?

 const [price, setPrice] = useState(0);
  let priceVar = "Click View Price";
  const viewPrice = () => {
    if (price === 0) {
      setPrice(Math.floor(Math.random() * 100));
    } else {
      priceVar = "Reset Price"; --------------------> NOT WORKING
      setPrice(0);
    }
  };

  return (
    <article
      className="book"
      onMouseOver={() => {
        console.log(title);
      }}
    >
      <div>
        <button type="button" onClick={viewPrice()}>
          {priceVar}
        </button>
        <h3>${price}</h3>
      </div>
    </article>
  );

Where can i host my Pygame, or how can i rewrite it in javascript?

So i’m trying to host my pygame as a webgame, i have tried itch.io and did a little research, so there are actually 2 solutions to this, either transforming my pygame into javascript code, or finding a website that hosts my pygame. Is there any automatic way of transfroming my game into java? and if not, is there any website that hosts python games? I’m also considering making a website just to host it but unfortunately idk HTML, i’m learning programming on the side so i don’t have that much time on my hands and i’m still a beginner. I’d appreciate some help on this manner<3

Javascript axios get json array with a bigint

I get an array from the API as follows:

[ { "URL": "", "avatar": "", "characterID": 853, "creationDate": "2022-01-22T17:12:42", "description": "description", "foreignSuggestionID": 0, "id": 5, "seriesID": 0, "type": "IMAGE", "userID": 168314031248113660 } ]

However I expect

[ { "URL": "", "avatar": "", "characterID": 853, "creationDate": "2022-01-22T17:12:42", "description": "description", "foreignSuggestionID": 0, "id": 5, "seriesID": 0, "type": "IMAGE", "userID": 168314031248113664} ]

The userID gets transformed in the request by Javascript, since when I use transformResponse: data => data I get the correct ID.
This gets me to the conclusion that it cannot contain the large number in Javascript. My question here would be, is there a way to make sure that a specific value within the json array is seen as a bigint or can I convert the column into a string on receiving the response?

I use axios and my code is as follows:

this.$axios.get(url, {
  withCredentials: 'true'
})
.then(response => {
  this.data = response.data
})

React API with Private keys (Beginner)

Hello im trying to use a “custom hook” to make a API request to CoinMarketCap API.

Im not sure what im doing wrong I tried basing my code on the given sample from their docs (Node.js): https://coinmarketcap.com/api/documentation/v1/#section/Quick-Start-Guide

Thank you for any help!!

import React, { useState, useEffect } from "react";
import logo from "../../images/bitcoin-logo.png";
import ethereum from "../../images/ethereum-48.png";
import cardano from "../../images/cardano-48.png";
import "./BitcoinPrice.css";
import axios from "axios"

const CoinMarketCap = () => {
    const [price, setPrice] = useState(null);
    const [loading, setLoading] = useState(true);

const intervalid = setInterval(
    useEffect(() => {
        fetch('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest', {
            method: "GET",
            qs: {
                'start': '1',
                'limit': '5000',
                'convert': 'USD'
            },
            header: {
                'X-CMC_PRO_API_KEY': 'aaaa-asdfadf-adfadf-asdfadsf-asdf'
            },
            json: true,
            qzip: true
        })
            .then((res) => res.json())
            .then((data) => {
                console.log(data);
                // setPrice(data.USD.last);
                // setLoading(false);
            })
            .catch((error) => {
                console.log(error);
            });
    }, []))

clearInterval(intervalid);

return (
    <div className="btc">
        <img className="btc-logo" src={logo} alt="Bitcoin" />
        <span className="btc-price">
            {loading ? "LOADING" : "$" + price}
        </span>
        <img className="btc-logo" src={ethereum} alt="Bitcoin" />
        <span className="btc-price">
            {loading ? "LOADING" : "$" + price}
        </span>
        <img className="btc-logo" src={cardano} alt="Bitcoin" />
        <span className="btc-price">
            {loading ? "LOADING" : "$" + price}
        </span>
    </div>

);
};



export default CoinMarketCap;

Field value is getting pushed to wrong array

In a vue app form, I have two text inputs and a file input.

What I want to happen: The text inputs should go into a fieldHeader array, and the file input should go into the fieldsArray array.

What does happen: Both text fields and the file input go into both the fieldHeader and the fieldsArray. The console.log for both arrays after clicking “add field” is 0: {field: 0, name: ‘text’, desc: ‘text’, imgOne: File}. It should be fieldHeader: 0: {field: 0, name: ‘text’, desc: ‘text’} and fieldsArray: 0: {imgOne: File}

I would think the v-model would push the items into the correct arrays, but that’s not it. The think I am working through now is to restructure the v-for as that’s the only place where I can currently see the code as mixing the two array concepts.

<template>
  <div v-for="(field, i) in fieldsArray"  :key="i" >
   <q-input
      label="Name"
      v-model="fieldHeader[i].name"
      type="text"
      dense
    />
    <q-input
      v-model="fieldHeader[i].desc"
      type="textarea"
   />
    <q-file
      v-model="fieldArray[i].imgOne"
      @update:model-value="onSelected()"
    ></q-file>
 </div>
 <div @click="handleAddField">Add Field</div>
</template>


<script>
const handleAddFields = () => {
  let i = fieldsArray.value.length;

  const item = {
    field: i,
  };
  fieldHeader.value.push(item);
  fieldsArray.value.push(item);
  
};
</script>

How to remove a subdocument from a schema when a button is clicked? – Mongoose

Unable to figure this out. My project is pretty much a website with listings that you can comment on, all the comments show through EJS. Full CRUD works, except when it comes to deleting the single comment. (listings can be deleted fine) There is a delete button for each comment.The comments are embedded into the schema. I’ve been trying various methods but it is erroring out.

My listing & comment schema:

const commentSchema = new Schema({
    content: String,
},{
    timestamps: true
});

const gigSchema = new Schema({
    title: {
        type: String,
        required: true,
    },
    price: {
        type: Number,
        required: true,
    },
    description: {
        type: String,
        required: true,
    },
    comments: [commentSchema]
}, {
    timestamps: true
});

my routes:

router.post('/:id/comments', commentsCtrl.commentsGig.create);

router.delete('/:id/comments', commentsCtrl.commentsGig.destroy);

i’ve tried

const destroy = (req, res) => {
  db.Gig.findById(req.params.id, (err, gigs)=>{
    if (err) return res.send(err);
    gigs.comments[0].remove();
    gigs.save(function(err){
      res.redirect(`/gigs/${gigs._id}`)
    })
  })

and get errors, i’ve found pull methods… but my code is not working.
I get this error when trying to ‘delete’ the comment ‘Cannot DELETE /gigs/’

this is my delete button just in case

  <form class = 'secondary-content' action="/gigs/<%= gigs.comments._id %>?_method=DELETE" method="POST">
              <input type="submit" value="Delete" /></form>

any help would be appreciated!

Document reloads after clicking “cancel” button on modal

I am building a project using HTML, bootstrap CSS and Jquery.
This is my HTML code:

<!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">

    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="node_modules/bootstrap-social/bootstrap-social.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Exo&display=swap">
    <link rel="stylesheet" href="styles.css">

    <title>TimeGuard</title>
</head>

<body>
    <div id="myModal" class="modal fade" role="dialog">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-body">
                    <form>
                        <div class="form-group row">
                            <label for="name" class="col-form-label">NAME: <input id="targetname" type="text"
                                    placeholder="Enter name of target website" style="width:350px"></label>
                            <label for="url" class="col-form-label">URL: <input id="targeturl" type="text"
                                    placeholder="Enter URL of target website"
                                    style="width:350px;margin-left:15px;"></label>
                            <div class="alert alert-info" role="alert">
                                Both the input fields are mandatory
                            </div>
                            <div>
                                <button type="submit" class="btn btn-light" id="close">Cancel</button>
                                <button type="submit" class="btn btn-dark" id="submit"
                                    disabled="disabled">Submit</button>
                            </div>

                        </div>
                    </form>
                </div>
            </div>

        </div>

    </div>

    <div class="main">
        <div>
            <nav class="navbar">
                <ul class="nav nav-tabs nav-justified" id="firstul">
                    <li class="nav-item active" style="width:200px"><a class="nav-link" href="#dashboard">DASHBOARD</a>
                    </li>
                    <li class="nav-item inactive" style="width:200px;"><a class="nav-link" href="#reports">REPORTS</a>
                    </li>
                    <li class="nav-item inactive" style="width:500px;"><a class="nav-link" href="#addict">ADDICT
                            SETTINGS</a></li>
                </ul>
            </nav>
        </div>

        <div class="tab-content" style="padding:20px;">
            <div class="tab-pane fade active show" role="tab-panel" id="dashboard">
                <div>
                    <h1>OVERVIEW</h1>
                    <div class="container-fluid box">
                        <div class="row justify-content-around">
                            <div class="overview col-3">
                                <div style="font-size:79px;">
                                    00:00:00
                                </div>
                            </div>
                            <div class="overview col-3">
                                <div style="font-size:79px;">
                                    00:00:00
                                </div>
                            </div>
                        </div>
                        <div class="row justify-content-around">
                            <div class="col-3">

                            </div>
                            <div class="col-3">

                            </div>
                        </div>
                    </div>
                </div>
                <div>
                    <h1>TARGET WEBSITES</h1>
                    <div class="box container-fluid">
                        <div class="row justify-content-center">
                            <div id="tarwebs" class="col-6">
                                
                            </div>
                            <div class="row">
                                <i id="addbtn" class="fa fa-plus-circle" type="button"
                                    style="font-size:50px;margin-left:650px;margin-top:20px;"></i>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" role="tab-panel" id="reports">
                    <h1>DAILY</h1>
                    <div class="box container-fluid">
                        <div class="row justify-content-around">

                        </div>
                    </div>
                    <h1>WEEKLY</h1>
                    <div class="box container-fluid">
                        <div class="row justify-content-around">
                            <canvas id="myChart" style="width:100%;max-width:600px"></canvas>
                        </div>
                    </div>
                    <h1>MONTHLY</h1>
                    <div class="box container-fluid">
                        <div class="row justify-content-around">

                        </div>
                    </div>
                </div>

            </div>
        </div>


        <script src="node_modules/jquery/dist/jquery.slim.min.js"></script>
        <script src="node_modules/popper.js/dist/umd/popper.min.js"></script>
        <script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
        <script src="dashboard.js"></script>
</body>

</html>

This is CSS code:

body{
    font-family: 'Exo', sans-serif;
}

.main{
    background-color:rgb(4, 209, 4);
    margin:30px;    
    border-radius:10px;
    padding-top: 0px;
    padding-bottom:20px;
}

.navbar{
    background-color:white;
    padding-left:0px;
    padding-right:0px;
    margin-left:auto;
    margin-right:auto;
    padding:0px;
}

.nav-link{
    color:black;
}

li{
    font-size:25px;
    text-align:center;
}

li.active{
    background-color: rgb(4, 209, 4);
    color:black;
    border:5px double;
    border-bottom:none;
}

li.inactive{
    background-color: green;
    
}

.box{
    border:1px solid rgb(92, 86, 86);
    border-radius:10px;
    padding:20px;
}

.overview{
    background-color: white;
    padding:5px;
    justify-content:center;
    border-radius:50px;
    text-align:center;
}

#tarwebs{
    background-color: rgb(128, 183, 231);
    padding:10px;
    justify-content:center;
    border-radius:50px;
}

.targets{
    background-color: white;
    height: 40px;
    border-radius:25px;
    padding:8px 30px 8px 15px;

}

.target-input{
    background-color: antiquewhite;
    border-radius:2px;
}

.fa-star:hover{
    color:rgb(241, 241, 214);
}

.select{
    color:yellow;
}

.deselect{
    color:black;
}

This is the Javascript(Jquery) code:

$(document).ready(function () {
    $("#firstul li").on("click", function () {
        $("#firstul li").removeClass("active").addClass("inactive");
        $(this).removeClass("inactive").addClass("active");
        $(".tab-pane").removeClass("active show").addClass("d-none");
        let value = this.children[0].getAttribute("href");
        $(value).addClass("active show").removeClass("d-none");
    });
    $("#addbtn").on("click", function () {
        $("#myModal").modal("show");
    });
    $("#close").on("click", function () {
        $("#myModal").modal("hide");
    });

    $("#targeturl").on("input change", function () {
        if ($("this").val() == "")
            $("#submit").prop("disabled", true);
        else
            $("#submit").prop("disabled", false);
    });


    $(".fa-star").on("click", function () {
        $(this).toggleClass("select deselect");
    });

    $("#submit").on("click", function (e) {
        e.preventDefault();
        $("#myModal").modal("hide");
        let url = $("#targeturl").val();
        let name = $("#targetname").val();
        let domain = new URL(url);
        domain = domain.hostname;
        if (name == "") {
            name = domain;
        }
        let text = `<div class="targets" style="margin-down:10px;"><img src="https://s2.googleusercontent.com/s2/favicons?domain_url=${domain}"><b style="margin-left:10px;">${name}</b><i class="fa fa-trash" style="font-size:25px;float:right;" type="button"></i><i class="fa fa-star select" style="font-size:25px;float:right;margin-right: 10px;" type="button"></i></div>`;

        document.getElementById("tarwebs").innerHTML+=text;

    })

});

My issues are:

  1. After entering the form specified in the modal and submitting it, the document is changed as expected (A div element appears as expected) . But after opening the modal again (By clicking the plus icon below), if I click “cancel” button without entering any detail , the page reloads and all the previous div elements in the document disappear. I want that the user should retain the previous div element as well as add another div element by filling the modal again.

  2. After re-opening the modal second time, the previous inputs are retained. I have to first delete those inputs before filling another.

I would be glad if someone could solve these issues.

Next.js ISR pass additional data to getStaticProps from getStaticPaths

In SingleBlogPost.jsx i have:

export async function getStaticPaths() {
  const res = await fetch("http://localhost:1337/api/posts");
  let { data } = await res.json();

  const paths = data.map((data) => ({
    params: { slug: data.attributes.slug },
  }));

  return {
    paths,
    fallback: "blocking",
  };
}

where I generate blog pages by their slug.
But then in getStaticProps I need to fetch single post by slug but I want to do it by id.

export async function getStaticProps(context) {
  console.log("context", context);

  const { slug } = context.params;

  console.log("slug is:", slug);
  const res = await fetch("http://localhost:1337/api/posts");
  const { data } = await res.json();

  return {
    props: {
      data,
    },

    revalidate: 10, // In seconds
  };
}

And I want to keep url like /blog/:slug , I dont want to include id. in url .When I already fetch all posts in getStaticPaths how I can access post id in getStaticProps to avoid fetching by slug?

Why is my useEffect not running on first render?

So I am trying to scramble a sentence or string and push the words into an array to later join them and output this scrambled sentence but for some reason the useEffect is not running on the first render even with an empty array but when I change one line and run it again it runs as intended. I was just wondering if I was doing anything wrong and how I can change it so that it does run on the first render.

const ScrambleSentence = ({sentence}) => {
    const [words, setWords] = useState([]);
    const [scrambledSentence, setScrambledSentence] = useState('');
    let scrambledWord = [];


    function scrambleWord(n){
        var text = n.split('');
        for(var i = text.length - 1; i > 0; i--){
            var j = Math.floor(Math.random() * (i + 1));
            var temp = text[i];
            text[i] = text[j];
            text [j] = temp;
        }
        return text.join('');
    }

    useEffect(() => {
        setWords(sentence.split(' '));


        words.map(word =>{
          if(word.length <= 2){
            scrambledWord.push(word);

          }
          else{
            scrambledWord.push(scrambleWord(word));
          }
        })
        setScrambledSentence(scrambledWord.join(' '));
      }, [])


      console.log(scrambledSentence);
    return (
        <div>
            <p id='scrambled-word'>{scrambledSentence}</p>
        </div>
    )
};

export default ScrambleSentence;

Possible CORS error when looping between Twilio Functions and an external php endpoint

We’re working on a looping alert system that sends an alert to our agent, then sends a request to our external PHP endpoint to sleep for an interval, then the endpoint calls our Twilio Function/Twilio Runtime Domain Endpoint again with an AJAX request to issue an alert, and loops.

Function A –> External Sleep Function (/Sleep) –> Function A

That’s the flow that we need, and we can’t get it to work. We can receive the request from Function A at /Sleep, but then can’t get it back to Function A. We can also send request from the browser to /Sleep, then receive the request back at Function A, then receive at /Sleep but still can’t get it back to Function A.

Basically, we can’t get the loop to complete. Does anyone have experience making a system like this work?

Thank you so much.

DocumentNotFoundError: No document found for query”{id:xxx}”

hello I have a discord bot and I started to do a marriage and divorce command the case is that when I try to delete the user from the db I get the error

DocumentNotFoundError: No document found for query "{ _id: new ObjectId("61ec3c66cb5991d616c6032d") }" on model "casados"

this is my model

const casados = mongoose.Schema({
    pareja1: String,
    pareja2: String
})
module.exports = mongoose.model("casados", casados)```
my code in the marry command is 

look for the model

let modelo = await casados.findOne({ $or: [{pareja1: interaction.user.id}, {pareja2: interaction.user.id}]})

If it doesn’t find it, create a new one.

        pareja1: interaction.user.id,
        pareja2: pareja.id
      })
      await modelo.save()```


then on my command divorce

look for the model again

```let modelo = await casados.findOne({ $or: [{pareja1: interaction.user.id}, {pareja2: interaction.user.id}]})```

and delete it

`await casados.findOneAndDelete({
       $or: [{
       pareja1: interaction.user.id
       },
       {
       pareja2: interaction.user.id
       }
       }).catch(e=> { console.log(e)})`

Changing position relative the other tags in css

I have 3 boxes on my page. The second (red) has to be fixed position. If the height of the green box increases, it has to increase to the top side, not to the bottom. So red one’s position has to be fixed. Also if the red one’s height increases, yellow has to move forward to the bottom. How can i do that?

enter image description here

Here is my css and html code:

#div1 {position:relative;top:0;bottom:0;right:0;background:green;width:100px;height:100px;}
#div2 {width:100px;height:140px;position:absolu;bottom:0;left:0;background:red;}
#div3 {width:100px;height:100px;position:relative;top:0;right:0;background:yellow;}
<!DOCTYPE html>
<html>
<head>
<title>HTML, CSS and JavaScript demo</title>
  
</head>
<body>
<!-- Start your code here -->
  
   <div class="parent">
       <div id="div1"></div>
       <div id="div2"></div>
       <div id="div3"></div>
</div>


<!-- End your code here -->
</body>
</html>

How would I apply a fade out animation to each of the icons in my menu within a for loop

im currently working on an animation where there’s a delay between each of the icons when fading out. The fade out animation works fine, but only on the first icon and im unsure on why this is. Could some one maybe point out the mistake im making?

Javascript code:

function closeHorizontalWindow()
{
const delay = 150;

const reasons = ['btnReady', 'btnNotReady', 'btnBreak', 'btnEmail', 'btnLunch', 
'btnComfortBreak', 'btnMeeting', 'btnChat']

for (let i = 0; i < reasons.length; i++) {   
    document.getElementById(reasons[i]).style.animation = `reasonsfadeout 0.45s ease-out 
forwards ${delay}ms` 
    delay+=150       
}

CSS code:

@keyframes reasonsfadeout
{
  from{opacity: 1; }
  to {opacity: 0; } 
}

}

Thankyou

How to use multiple Full Calendar sources with different coloring based on description?

I have been building a Google Apps Script web app to display my Google Calendar events. The calendar service won’t allow an editable calendar to be used so I have been using Full Calendar to complete this task. When I use the google calendar api to import events, they all come in but they all have the same color. The coloring is essential and depends on the event description (e.g. if “specified string” is in the event description the color is yellow, otherwise grey). I then tried to import them as JSON and limited to title & start times in an array. Using some test cases I know this works, but when I try to import the events, the calendar remains blank. What am I doing wrong?

// This Does NOT Work.
var yellowEvents = [];
var greyEvents = [];
function loadEvents(importedData) {
  // importedData is coming in as 
  //     importedData = [
  //       {title: "someTitle", start: ISODateTime, end: ISODateTime, color: "someColor"}, 
  //       {title: "someTitle", start: ISODateTime, end: ISODateTime, color: "someColor"}, 
  //      ...]
  for (var k in importedData) {
    var event = importedData[k];
    if (event.color == 'yellow') {
      yellowEvents.push({ title: event.title, start: event.start, end: event.end });
    } else {
      greyEvents.push({ title: event.title, start: event.start, end: event.end });
    }
  }
}
google.script.run.withSuccessHandler(loadEvents).getCalenderEventsAsJson();
var calendar = new FullCalendar.Calendar(calendarEl, {
  eventSources: [{
    events: yellowEvents,
    color: "yellow"
  }, {
    events: greyEvents,
    color: "blue"
  },
  ]
});



// This Works.
document.addEventListener('DOMContentLoaded', function() {
  var calendar = new FullCalendar.Calendar(calendarEl, {
    eventSources: [{
        events: [
          {title: "TEST", start: new Date().toISOString()},
        ],
        color: "red"
      }, {
        events: [
          {title: "TEST", start: new Date(2022, 0, 23, 12, 30).toISOString(), end: new Date(new Date().setHours(18)).toISOString()},
        ],
        color: "blue"
     },
     ]
   });
   calendar.render();
}

From checking the options object before calendar creation through the console, I am certain the events are making it into the calendar options. The final options look like this:

{...,
  eventSources: {
    0: {color: "yellow",
        events: [
          0: {title: 'Some Person', start: '2022-01-23T16:00:00.000Z', end: '2022-01-23T18:00:00.000Z'}, 
          1: {title: 'Some OtherPerson', start: '2022-01-24T16:00:00.000Z', end: '2022-01-24T18:00:00.000Z'},
          ...
        ]
    },
    1: {color: "grey",
        events: [
          0: {title: 'Some Person', start: '2022-01-23T12:00:00.000Z', end: '2022-01-23T14:00:00.000Z'}, 
          1: {title: 'Some OtherPerson', start: '2022-01-24T12:00:00.000Z', end: '2022-01-24T14:00:00.000Z'},
          ...
        ]
    }
  },
...}

I also see them pre & post rendering in Calendar.currentData.eventSources.{SOME_NUMBER}.meta.