Can I force a shinyTree to be loaded when the app is started?

Summary: When I put a shinyTree (from the R package of the same name) in a dropdownButton (from the shinyWidgets package), it seems that the tree in question is not accessible from the input variable until the user has interacted with the tree in some way. Is there a way I can force the tree to load when the app is loaded at the start?

Here is a minimal (almost) example:

library(shiny)
library(shinyWidgets)
library(shinyTree)
library(magrittr)

render.as.text <- function(t) {
  if (is.null(t)) {
    'argument is NULL'
  } else {
    q <- get_selected(t)
    if (length(q) == 0) {
      'none selected'
    } else {
      paste(q, sep=', ', collapse=', ') 
    }
  }
}

ui <- fluidPage(
  dropdownButton(shinyTree('tree', checkbox=TRUE), circle=FALSE, inputId='dd')
)

server <- function(input, output, session) {
  output$tree <- renderTree({ list(OptionA = structure(list(OptionAA='', OptionAB=''), stopened=TRUE), OptionB='') })
  updateActionButton(session, 'dd', label='initial label')
  
  observe({
    updateActionButton(session, 'dd', label=render.as.text(input$tree))
  }) %>% bindEvent(input$dd_state)  
}

shinyApp(ui = ui, server = server)

When I run this app, the button begins with the text ‘initial label’ (as expected), then when I click on it the first time the text changes to ‘argument is NULL’ (showing that the variable input$tree has a NULL value), but the tree displays correctly in the dropdown. If I then click the button again to close the dropdown, the text ‘argument is NULL’ remains – it remains until I actually select one or more of the tree’s checkboxes after which (and after clicking the button again) it will display either a comma-separated list of selected options or ‘none selected’ as expected.

I would very much like to be able to refer to input$tree beginning with the first time the user takes any action in the app – ideally I am looking for some command to insert in either the server or ui code (or both) which will mean that the first time the user clicks the button its text will change directly to ‘none selected’ because input$tree is no longer NULL. Is this possible?

issue running scripts on npm ( npm scripts error )

I recently encountered strange problems when using NPM in the system to execute projects, one of which is when executing gulp during the LAUNCH of projects. What could be the reason for this error and how can it be solved?

Apparently this error is related to PowerShell execution policies , how can this problem be solved?

enter image description here

Vue cli serve, how to get a httprequest with success (404 file not found)

I have a vue app. I have a ‘vue cli serve’ command that compiles the app and serves the application
(Using a webpack node server as far as I know)

I want to get a file using XMLHttpRequest

Ok, I want to retrieve a file using:

var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
       debugger
        this.responseText;
      }
    };
    xhttp.open("GET", file, true);
    xhttp.send();

ok i have played with a lot of combinations for:

http://192.168.0.2:8080//
http://localhost:8080//

and different folders and existing files without success.
I have allways the error: ( or similar)

 GET http://192.168.0.2:8080/public/web_icon.txt 404 (Not Found)

Any idea of to fix this ?
Thanks in advance

Form mail sending issue

Please someone should help me I tried posting it as a code but I couldn’t vet through it I was getting an error message someone should tell me why I’m not receiving form responses in my mailrrap after clicking the button html form

I tried what was there and was expecting a form where I receive form fills to maitltrpa but to no avail

Use Tailwind in Content Script of Browser Extension

I’m trying to write a browser extension which injects some buttons and custom components into a website, therefore I wanted to use Tailwind (and DaisyUI) to style them.

I found this discussion and configured my project according to the solution and I got Tailwind and DaisyUI working for the popup of my extension. My App.css looks like

@tailwind base;
@tailwind components;
@tailwind utilities;

This gets imported in my Popup.tsx with import "../App.css";. No problems there.

But when I try to do the same import in my content-script, I don’t get any errors, but the script somehow fails/doesn’t get executed at all anymore. If I put in a console.log without importing App.css, it gets printed. If I import App.css, it’s not shown anymore.

Could this be an error with my webpack/postcss-config or is there something else preventing me from using custom CSS in the content script? I’m confused because it’s working in the popup without any problems.

GET http://localhost:5000/auth/me 404 (Not Found)

I am following a MERN tutorial and made a React site where it receive data like name and email of the logged in user and then theses data are shown.

Here my back code:

routes/user.js:

const express = require('express')

const userController = require('../controllers/user')
const route = express.Router()
const checkAuth = require('../middleware/auth')


route.post('/', userController.register)
route.post('/login', userController.login)
route.get('/isauth', checkAuth, userController.isAuthenticated)
route.post('/logout', checkAuth, userController.logout)
route.post('/me', checkAuth, userController.getMe)


module.exports = route

controllers/user.js:

module.exports = {
getMe: (req, res) => {
        const {sub} = req.user

        User.findOne({_id : sub}, (err, user) => {
            if (err) {
                res.status(500).json({
                    message : 'User not found',
                    data : null
                })
            } else {
                res.status(200).json({
                    message : 'User found',
                    data : user
                })
            }
        })
    },
}

Here my front code:

authenticationAPI.js:

export const AuthenticationService = {
 getMe: () => {
    return axiosInstance
      .get(requests.getme, { credentials: "include" })
      .then((res) => {
        return res;
      })
      .catch((err) => {
        return err;
      });
  },
}

config/requests.js:

export const requests = {
    register : '/auth',
    login : '/auth/login',
    logout : '/auth/logout',
    getme : '/auth/me',
}

authenticationSlice.js:

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { AuthenticationService } from "./authenticationAPI";

const initialState = {
  registerstatus: "",
  errormessage: "",
  userDetails: null,
};

//getme redux action
export const getMe = createAsyncThunk(
  "users/me",
  async () => {
    const response = AuthenticationService.getMe();
    return response;
  }
);

//creation du slice
const authenticationSlice = createSlice({
  name: "authentication",
  initialState,

extraReducers: {

//getMe http request 3 cases
    [getMe.pending]: (state, action) => {

    },
    [getMe.fulfilled]: (state, action) => {
        console.log(action.payload);
        state.userDetails = action.payload.data.data
    },
    [getMe.rejected]: (state, action) => {

    },

export const { } = authenticationSlice.actions;
export const selectUserDetails = (state) => state.authentication.userDetails
export default authenticationSlice.reducer;

views/posts/post.jsx:

import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getMe, selectUserDetails } from '../../features/authentication/authenticationSlice'
export default () => {

    const dispatch = useDispatch()

    useEffect(() => {
      dispatch(getMe())
    }, [])

    const userDetails = useSelector(selectUserDetails)
    

    return (
        <h5>{userDetails && userDetails.name}</h5>
        <hr />
        <h6>{userDetails && userDetails.email}</h6>
    )
}

The email and the name still do not render.

I tried runnig this code on browser, but i got theses two errors in devtools Console when i’m logged in (i can see the access_token in Application):

Error: Request failed with status code 404
GET http://localhost:5000/auth/me 404 (Not Found)

I really appreciate your help. Thank you all.

Sending message from Main to Renderer

Could someone help me out here. I’m completely confused on how to solve this. I’ve now spent about a week trying to find a solution for this but have come up short and there appears to be a lack of a solid solution online. I’ve made a github repository trying to demonstrate the issue.

In short I’ve implemented a status bar in my application which i want to populate with various string messages. These messages would be sent from functions that are contained inside a js file that imports electron, which mean’s it doesn’t have direct access to the Renderer. So how would I send these messages to the Renderer. I’m assuming this needs to be done using the ContextBridge, but i have no clue how to successfully do this, so if your response is just linking me to the context bridge docs, don’t bother, lol I’ve exhausted myself looking at that. The other alternative i was considering is using a custom event but but i’m not sure that would solve the problem either.

Here is a sample of what im trying to do along with repo on github. If you do a pull-request to fix the repo, ill gladly merge and keep the repo public for others to benefit from and share with the community. https://github.com/JokerMartini/statusbar

As a minor problem, im not sure why i can no longer call getPath from ‘app’ from within a js file that’s not loaded into the render thread.

I trigger a method from Renderer

index.vue

const doWork = () => {
    window.messenger.doWork();
}

electron-preload.js

import { contextBridge } from "electron";

const messenger = require("../src/helpers/messenger");
contextBridge.exposeInMainWorld("messenger", messenger);

messenger.js

const { app } = require("electron");
const path = require("path");

// using electron module to demonstrate this file can't be imported into renderer
export function showMessage(msg) {
  const dir = path.join(app.getPath("documents"), "presets");
  console.log(dir);
  // TODO: send message to renderer...
}

export function doWork() {
  console.log("Doing working...");

  // step 1: long process
  showMessage("Processing step 1...");

  // step 2: long process
  showMessage("Processing step 2...");

  // step 3: long process
  showMessage("Processing step 3...");
}

I’d like to display the messages sent from the main to renderer to be displayed in the status bar of

main.vue

<q-footer>
     <q-bar>
        <span class="text-caption">Show message here...</span>
    </q-bar>
</q-footer>

DOM of new page inaccessible after window.location.href value changes

I’ve a rating submission form. In form.onSubmit(), I capture the rating data, redirect to a “thank you page” with window.location.replace(url).

I’m trying to append the rating data in the new page. However, once the page is replaced, I can access the formData variable, but, DOM of the new page seems inaccessible.

Code:

function handleSubmit(e) {
  e.preventDefault();

  const formData = new FormData(form);

  window.location.replace('thankyou.html');

  console.log(formData.get('rating'));
  
  // dom not accessible after replace
  console.log(document.body);
}

Any leads?

Show random picture with Javascript in HTML

I have a code which shows randomly a url to a picture.
I want to add the random shown url to the part where the picture is created.

How can I extract the url from javascript and use it in html? Test.jpg should be replaced with the random generated url.

<!DOCTYPE html>
<html>
  <head>
    <title>Der Titel des Dokuments</title>
  </head>
  <body>
      
      <h2>HTML Image</h2>
<img src="test.jpg" width="460" height="345">


      
      <div id="textbox"></div>
      
<script language="JavaScript">
var myimages = [{
  image: "https://cdn.prod.www.manager-magazin.de/images/ca3dd5d1-0001-0004-0000-000000088705_w920_r1.778_fpx42.51_fpy49.99.jpg",
  probability: 0.1
}, {
  image: "https://p6.focus.de/img/fotos/id_40323993/porsche-cayman-heck.jpg?im=Crop%3D%280%2C20%2C1600%2C800%29%3BResize%3D%28800%2C400%29&impolicy=perceptual&quality=medium&hash=69314e722c29162f49edafd9b16362ceb1a704219e2a128272824e5d8d585019",
  probability: 0.1
}, {
  image: "https://i.auto-bild.de/ir_img/1/7/6/3/5/7/9/Alle-Auto-Neuheiten-2019-1200x800-bbcf8a2e46bd3f1f.jpg",
  probability: 0.25
}, {
  image: "https://cache.pressmailing.net/thumbnail/story_hires/64940fdd-8ec9-4854-98f9-e7f7467414b7/image.jpg",
  probability: 0.55
}];

function getImage() {
  var rand = Math.random();
  var probabilitiy_sum = 0;
  for (var i = 0; i < myimages.length; i++) {
    probabilitiy_sum += myimages[i].probability;
    if (rand <= probabilitiy_sum) {
      return myimages[i].image;
    }
  }
  return myimages[myimages.length].image;
}

// Just for testing:
for (var i = 0; i < 1; i++) {
  document.getElementById("textbox").innerHTML += getImage() + "<br />";
}
</script>
        
  </body>
</html>

Comparing 2 arrays and fetch values to see if array 1 is greater than array 2

I am still in the midst of learning React and Javascript and have came to a roadblock with my current project.

Project goal
I am trying to map through two array of objects, and check if a certain property matches.
if recommendedSkillTree.skills.skill === currentSkills.skill, I would then like to check if recommendedSkillTree.skills.level > currentSkills.level.
if the above condition matches, or if currentSkills.skill do not have the skills in the recommendedSkillTree Data, the skill will then show up in a red text. Else, green text.

What I have done
I have tried mapping between the 2 arrays to check if currentSkills.skill === recommendedSkillTree.skills.skill.

  const skillMatch = recommendedSkillTree.filter((skillRecommended) =>
    currentSkills.some((skillCurrent) => skillRecommended.skill === skillCurrent.skill)
  );
.
.
.
  return (
   <div>
     {recommendedSkillTree.map((item, i) => (
            <div key={item.id}>
              <div
                style={{
                  color: !skillMatch[i] ? "red" : "green", 
                }}
              >
                {item.skill}
              </div>
            </div>
          ))}
   </div>


By doing so, I am able to churn out an output where skills that are present in currentSkills are shown in green, and those that are not in it are shown in red.

Next I would like to go one step deeper, and tried to compare the skill level of the present skills, and if they fall short of the recommended level, the text would then show in red.

  const levelGap = recommendedSkillTree.map((recommendedLevel) =>
    currentSkills.some((levelCurrent) => recommendedLevel.level > levelCurrent.level)
  );

By doing so, I would be expecting an output of

[true, false, true, true, true, true, true, true, true]

instead I’ve got:

[true, true, true, true, false, true, true, false, false]

I am unable to see which part have went wrong. Would greatly appreciate if any seniors in this field would guide me along.

Data 1

const recommendedSkillTree = [
  {
    id: "1",
    role: "Paladin",
    skills: [
      {
        id: "1",
        skill: "Attack",
        level: "3",
      },
      {
        id: "2",
        skill: "Block",
        level: "3",
      },
      {
        id: "3",
        skill: "Taunt",
        level: "3",
      },
      {
        id: "4",
        skill: "Heal",
        level: "4",
      },
      {
        id: "5",
        skill: "Group Heal",
        level: "2",
      },
      {
        id: "6",
        skill: "Double Attack",
        level: "4",
      },
      {
        id: "7",
        skill: "Ultimate",
        level: "3",
      },
      {
        id: "8",
        skill: "Defense Up",
        level: "2",
      },
      {
        id: "9",
        skill: "Attack Up",
        level: "2",
      },
    ],
  },
];
export default recommendedSkillTree;

Data 2

const currentSkills = [
  {
    id: "1",
    skill: "Attack",
    level: "2",
  },
  {
    id: "2",
    skill: "Block",
    level: "3",
  },
  {
    id: "3",
    skill: "Taunt",
    level: "2",
  },
  {
    id: "4",
    skill: "Heal",
    level: "3",
  },
  {
    id: "5",
    skill: "Final Slash",
    level: "3",
  },
];
export default currentSkills;

Thank you in advance for your time, and I do apologize if my way of asking questions are not up to community standard as this is my first time posting on here.
I do not really have anyone around me to ask questions on since I am fully self-taught and no one around me is in the tech field. Thank you so much.

Loop with delay in Postman test script

My API has two endpoints, one for starting a process and a second to check if that process has finished.

There can only be three states returned by the second endpoint: running, success or failure. Running is a temporary state, and once the process finishes, it will be marked as success or failure permanently.

How can I write a test script that keeps sending a request to the second endpoint (1 second delay) until it stops responding with running?

I’ve tried using pm.sendRequest but with no success. Since it is an async/callback function, it doesn’t work well when calling it recursively. I’ve also tried some setTimeout / setInterval hacks but with no success. And also, unfortunately, postman doesn’t support async / await syntax.

How to remove multiple classes from different div with jQuery

I’ve three dropdowns.. When i click on the div with the data-column=”1″ ( Momentum Jeans Shorts ), I want the current dropdown to remove the “active” & “disable” class for the data-column=”1″ (Momentum Shorts) and also add the “disable” & “active” class on the selected div which is the data-column=”1″ ( Momentum Jeans Shorts )..

On my second dropdown, I would want the data-column=”1″ (Momentum Shorts) to not have the “disable” & “active” class. data-column=”2″ ( Momentum Jeans Shorts ) would have the “disable” class.

I’ve tried to work on this many hours but I cant seems to get the algorithm right.. I’ve attached a screenshot of the dropdowns, and hopefully you get what I’m trying to achieve

$(function() {
            $(".compare-filter-item").on("click",function() {
                const column_value = $(this).attr("data-column");
                const selected_data_product = $(this).attr("data-product");

                $('.compare-filter-item[data-product="' + selected_data_product + '"][data-column="' + column_value + '"]').parent().parent().find(".active.disable").removeClass("active disable");


                $("[data-product='" + selected_data_product + "']").addClass("disable");
                $(this).addClass("active");

                const myarray = $(`.compare-all .compare-products [data-product="${selected_data_product}"]`).map(function() {
                return $(this).html();
                });

                $(`.compare-main .compare-products [data-column="${column_value}"]`)
                .each(function(i) { $(this).html(myarray[i]) });
            });
        });

enter image description here
enter image description here

NextJS 12 and webpack 5 unknown property ‘fs’

I have upgraded from Next10 to Next12 (webpack5), also from React16 to React17. This is how our next.config.js looks like

next config here

When running a dev server this error comes up and I’m not sure how to work around it:

error on dev server

If I remove the fs: 'empty' from the config next12 does not seem to find other files in their respective location:

error when remove fs

Part of the package.json I believe its relevant to this looks as follow:

package json