Javascript function returning undefined instead of value – Squared concatenation of a Number

i am working on exercise: Squared concatenation of a Number in JavaScript (https://www.tutorialspoint.com/squared-concatenation-of-a-number-in-javascript). I am trying to add it to a function so it looks like:

function squareDigits(num){
const squared = num => {
   const numStr = String(num);
   let res = '';
   for(let i = 0; i < numStr.length; i++){
      const square = Math.pow(+numStr[i], 2);
      res += square;
   };
   return res;
};
}
console.log(squareDigits(9191));

But it keeps returning undefined, not sure why. Any help would be appreciated thanks

Any standard way to export structured js/json from jsdoc comments

I want to use jsdoc comments from a javascript file inside an interactive component (like property definitions appearing on hover), but I can’t find a way to do that as jsdoc is primarily intended to export html files.

Is there a straightforward way to parse jsdoc comments from a file as structured data that I can then consume in my UI?

my redirect doesn’t work though I have the correct syntax

I have the following code :

app.get('/decl_param', async (req, res) => {
  var gui = await guiText("declension", lang);
  var msg = await messageText("declension", lang);
  console.log("msg", msg);
  res.render("decl_param", { gui: gui, msg: msg });
})
app.get('/decl_quizz', async (req, res) => {
  var gui = await guiText("index", lang);
  var msg = await messageText("declension", lang)
  console.log(" decl_quizz requested");;
  res.render('decl_quizz',{gui:gui,msg:msg} );
})
app.post('/decl_param', async (req, res) => {
  console.log("post obtained /decl_param");
  //let question = req.body; // JavaScript object containing the parse JSON
  //let answer = await makeDeclAnswer(question, lang);
  //console.log("question", answer);
  //res.json(answer);
  res.redirect(301,'/decl_quizz');
})

Console output :

 post obtained /decl_param  
 decl_quizz requested

When I click in a button in the page ‘decl_param’, a post message is sent, a redirection is requested, the page ‘/decl_quizz’ seems to be generated but the browser still stays at ‘/decl_param’ and ‘/decl_quizz’ is not displayed.

Directly requesting /decl_quizz in the address bar does work correctly. What is wrong in my redirection ?

Is it possible to create plugin without selector in eslint?

I want to create eslint plugin.

export const rule = ESLintUtils.RuleCreator(() => __filename)({
  name: RULE_NAME,
  meta: {
    type: 'problem',
    docs: {
      description: ``,
      recommended: 'error',
    },
    schema: [],
    messages: {},
  },
  defaultOptions: [],
  create(context) {
    return {};
  },
});

I’m not so familiar with eslint plugin.

From what I read in the eslint docs I need to return an object with a selector of what I looking for in the code (for example VariableDeclaration) and then I’ll get the ts node in the callback function.

But is it possible to not return the selector, instead just to return callback and in this callback I’ll get the root ts node and I’ll do my own logic there with ts-morph?

I mean something like this possible to do with eslint?

import { ts } from 'ts-morph';
...

  create(context) {
    const rootNode = context.getRootNode() as ts.Node;
    const nodes = rootNode.getChildren().map(n => ....)

    nodes.forEach(node => {
      context.report({
        node,
        messageId: 'some'
      })
    })

  },

Command is getting the model from the db not the value discord.js

I want to make another command handler for my bot but I can’t.

I’ve tried this code:

module.exports = (client) => {
  let dateNow = Date.now();
  try {
    readdirSync("./commands/").forEach((dir) => {
      const commands = readdirSync(`./commands/${dir}/`).filter((file) =>
        file.endsWith(".js")
      );
      for (let file of commands) {
        try {
          let pull = require(`../commands/${dir}/${file}`);
          if (pull.name) {
            client.commands.set(pull.name, pull);
          } else {
            continue;
          }
        } catch (e) {
          console.log(e);
        }
      }
    });
  } catch (e) {
    console.log(e);
  }
};

But It’s not working. and I am getting an error:

Error: Cannot find module '../config.json'
Require stack:
- C:UsersPooyanDesktopPDM BotcommandsUtilityyoutube.js
- C:UsersPooyanDesktopPDM Bothandlerscommand_handler.js
- C:UsersPooyanDesktopPDM Botmain.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Object.<anonymous> (C:UsersPooyanDesktopPDM BotcommandsUtilityyoutube.js:4:16)
    at C:UsersPooyanDesktopPDM Bothandlerscommand_handler.js:13:22
    at module.exports (C:UsersPooyanDesktopPDM Bothandlerscommand_handler.js:7:32)
    at C:UsersPooyanDesktopPDM Botmain.js:57:37
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'C:\Users\Pooyan\Desktop\PDM Bot\commands\Utility\youtube.js',
    'C:\Users\Pooyan\Desktop\PDM Bot\handlers\command_handler.js',
    'C:\Users\Pooyan\Desktop\PDM Bot\main.js'
  ]
}

and +100 more errors…

Notes: I also tried to read articles and other questions on stack overflow and other websites, bot It did not work out. I am using discord.js v13 and Node.js v16

Extra Notes: My files are like this:

enter image description here

how to locate this syntax error : SyntaxError: Assigning to rvalue at

When trying to build my vu3js SPA I get the following error

vite v2.9.12 building for production… ✓ 75 modules transformed.

[rollup-plugin-dynamic-import-variables] Assigning to rvalue (1907:44)

file:
/ORIGINAL-P1/LARAVEL-BREW/BrewersCompanion/vue/src/components/RecipeEditor.vue:1907:44

error during build:

SyntaxError: Assigning to rvalue (1907:44)

at Parser.pp$4.raise (/ORIGINAL-P1/LARAVEL-BREW/BrewersCompanion/vue/node_modules/rollup/dist/shared/rollup.js:19738:13)
at Parser.pp$7.toAssignable (/ORIGINAL-P1/LARAVEL-BREW/BrewersCompanion/vue/node_modules/rollup/dist/shared/rollup.js:18231:12)
at Parser.pp$5.parseMaybeAssign (/ORIGINAL-P1/LARAVEL-BREW/BrewersCompanion/vue/node_modules/rollup/dist/shared/rollup.js:18754:21)
at Parser.pp$5.parseParenAndDistinguishExpression (/ORIGINAL-P1/LARAVEL-BREW/BrewersCompanion/vue/node_modules/rollup/dist/shared/rollup.js:19209:28)
at Parser.pp$5.parseExprAtom (/ORIGINAL-P1/LARAVEL-BREW/BrewersCompanion/vue/node_modules/rollup/dist/shared/rollup.js:19072:41)
at Parser.pp$5.parseExprSubscripts (/ORIGINAL-P1/LARAVEL-BREW/BrewersCompanion/vue/node_modules/rollup/dist/shared/rollup.js:18905:19)
at Parser.pp$5.parseMaybeUnary (/ORIGINAL-P1/LARAVEL-BREW/BrewersCompanion/vue/node_modules/rollup/dist/shared/rollup.js:18871:17)
at Parser.pp$5.parseExprOps (/ORIGINAL-P1/LARAVEL-BREW/BrewersCompanion/vue/node_modules/rollup/dist/shared/rollup.js:18798:19)
at Parser.pp$5.parseMaybeConditional (/ORIGINAL-P1/LARAVEL-BREW/BrewersCompanion/vue/node_modules/rollup/dist/shared/rollup.js:18781:19)
at Parser.pp$5.parseMaybeAssign (/ORIGINAL-P1/LARAVEL-BREW/BrewersCompanion/vue/node_modules/rollup/dist/shared/rollup.js:18748:19)

I cannot see anything like assigning to right hand value around line 1907

Here is a chunk of code starting at line 1905

//Gravity (line 1905)
let fixed_og = ref();

let showConfirmGravity = ref(false);
function adaptFermentablesToNewGravity() {
    let equipment = store.getters["equipment/getEquipmentById"](
        recipe_model.equipment
    );
    let old_extract_added_to_boil = extract_added_to_boil.value;
    let old_extract_from_mash = extract_from_mash.value;
    let P = SGToPlato(recipe_model.original_gravity);
  
    if (P < 1) {
        P = 1;
    }
    //original gravity is for postboil volume
    let new_extract_mass = extract_mass_from_platos_and_volume(
        P,
        postboil_volume_reverse_cold.value
    );
    //FOR MASH
    let new_extract_from_mash =
        (new_extract_mass * old_extract_from_mash) /
        (old_extract_added_to_boil + old_extract_from_mash);

    recipe_model.fermentables.forEach((element) => {
        if (element.use === "mash") {
            element.quantity =
                1 *
                (element.quantity / old_extract_from_mash) *
                new_extract_from_mash;
        }
    });

    //FOR BOIL
    let new_extract_added_at_boil =
        (new_extract_mass * old_extract_added_to_boil) /
        (old_extract_added_to_boil + old_extract_from_mash);

    recipe_model.fermentables.forEach((element) => {
        if (element.use === "boil" || element.use === "steep") {
            element.quantity =
                1 *
                (element.quantity / old_extract_added_to_boil) *
                new_extract_added_at_boil;
        }
    });
}

Could somebody help me finding where the problem is located ?

How to run rinkeby test ethereum deploy

I build deploy.js for deploy rinbkeby test network. But when I run command node deploy.js didnt work. Here my code:

const HDWalletProvider = require('truffle-hdwallet-provider')
const Web3 = require('web3')
const {interface, bytecode} = require('./compile')

const provider = new HDWalletProvider(
    'xxxxx xxxxx xxxxx xxxxx xx xxxxxx ...',
    'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
)

const web3 = new Web3(provider)

const deploy = async () =>{

    console.log("geldm");
    const accounts = await web3.eth.getAccounts()

    console.log(accounts);

    const result = await new web3.eth.Contract(JSON.parse(interface))
        .deploy({data: bytecode, arguments: ['Hi there!']})
        .send({gas: '1000000', from: accounts[0]})

    console.log('Contract deployed to', result.options.address)
}

deploy()

When I run command I get this:

geldm (node:6184) V8:
C:UsersFeruzDesktopethereuminboxnode_modulessolcsoljson.js:3
Invalid asm.js: Invalid member of stdlib (Use node --trace-warnings ... to show where the warning was created)

“Can’t read properties of ‘undefined'” after excecuting an action with Redux

I’m making a Shopping List App with React/Redux. I’m having truble removing an item from a list. After excecuting the ‘removeItem’ action the page can no longer read the object that is the list (which was previously stored in local state and coul’d be read before excecuting the action).

I’ve tried storing the list object in a const variable and a local state using the useEffect hook but it still breaks.

JSX

  const { id } = useParams();
  const shoppingLists = useSelector((state) => state.shoppingLists);
  const findList = shoppingLists.find((list) => list.listId === id);
  const [selectedList, setSelectedList] = useState({});

  useEffect(() => {
    setSelectedList(findList);
  });

  const removeItemForm = (item) => {
    const { itemName, itemId } = item;
    dispatch(removeItem({ itemName, itemId, listId: id }));
  };

  <div className="listHeading mb-4">
    <h2>{selectedList.listName}</h2> //Line that breaks
  </div>

Reducer

const shoppingListsSlice = createSlice({
  name: "shoppingLists",
  initialState: [],
  reducers: {
    createList(state, action) {
      state.push({
        listId: uuidv4(),
        listName: action.payload,
        items: [],
        color: "",
        createdAt: Date(),
      });
addItem(state, action) {
      state
        .find((list) => list.listId === action.payload.listId)
        .items.push({
          itemId: uuidv4(),
          itemName: action.payload.itemName,
          isBought: false,
        });
    },
    removeItem(state, action) {
      return state
        .find((list) => list.listId === action.payload.listId)
        .items.filter((item) => item.itemId !== action.payload.itemId);
    },

how can i get the value of variable inside function to outside the on jquery

can i take the value from ‘a = entry.username’ out of the function? i want to get value that already looping inside the function

$('#btnlogin').click(function(){
        var usernamelogin = $('#usernamelogin').val()
        var passwordlogin = $('#passwordlogin').val()
        var data_user1 = JSON.parse(localStorage.getItem('data_user'))
        
        for(var i in data_user1){
        var entry = data_user1[i]
        
        if(usernamelogin == entry.username && passwordlogin == entry.password){
            window.location.href = "curhat.jsp"
            a = entry.username
            return
            }   
        }
        if(usernamelogin != entry.username && passwordlogin != entry.password){
            alert("wrong username or password") 
        }
                
        //console.log(data_user1)
        //console.log('username = ' + entry.username)
        
    })

React.js i have Bug in prod but not in dev mode, can you help me

I’ve been having a problem for 3 days now, and I don’t really understand what can cause this bug, can you help me?

Here is the problem,
I have created a small game(react.js) where 5 cards are displayed at each reload, these 5 cards have a score of points each which are cumulated each time, which gives a score of all the cards, then the score of each “hand” which is cumulated.

In development mode, everything works correctly, but if I build and put it on a cdn (netlify), the score logic doesn’t work…

Prod link (bug) : https://are-you-lucky-game.netlify.app/

Github repo link (dev mode work fine) : https://github.com/rodolphe37/random-playing-card-tuto/tree/step-3-final

If you have ever encountered this kind of bug, or if you think you have a solution for me, I’m interested.

If needed, tell me if you want the link to the source code repo to help me solve this problem.

Thanks in advance!

Animation only works on first element when using Var CSS

I have found a lovely button animation and implemented it using a tutorial from this video. The button animation works on the first button, however not properly on the second.

It uses JavaScript and CSS var() to generate an animation, both of which I am not familiar with.

HTML and JavaScript is as follows, Run Snippet to see what I mean:

.btn {
  position: relative;
  display: inline-flex;
  height: 50px;
  width: 100px;
  background: #ffffff;
  /* color: rgb(11, 81, 211); */
  border: 2px solid rgb(11, 81, 211);
  border-radius: 10px;
  text-decoration: none;
  letter-spacing: 1px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn span {
  padding-left: 50%;
  padding-right: 50%;
  padding-top: 10px;
  padding-bottom: 10px;
  position: relative;
  z-index: 1;
  font-size: 20px;
  color: rgb(11, 81, 211);
}

.btn span:hover {
  color: rgb(255, 255, 255);
}

.btn::before {
  content: '';
  position: absolute;
  top: var(--y);
  left: var(--x);
  transform: translate(-50%, -50%);
  width: 0;
  height: 0;
  border-radius: 50%;
  background: rgb(11, 81, 211);
  transition: width 0.5s, height 0.5s;
}

.btn:hover::before {
  width: 1200px;
  height: 1200px;
  color: white;
}
<div>
  <button type="submit" class="btn" id="button1"><span>Plot</span></button>
  <script>
    const btn = document.querySelector('.btn');
    btn.onmousemove = function(e) {
      const x = e.pageX - btn.offsetLeft;
      const y = e.pageY - btn.offsetTop;

      btn.style.setProperty('--x', x + 'px');
      btn.style.setProperty('--y', y + 'px');
    }
  </script>
</div>

<div>
  <button type="submit" class="btn" id="button2"><span>Plot</span></button>
  <script>
    const btn2 = document.querySelector('.btn');
    btn2.onmousemove = function(e) {
      const x = e.pageX - btn2.offsetLeft;
      const y = e.pageY - btn2.offsetTop;

      btn2.style.setProperty('--x', x + 'px');
      btn2.style.setProperty('--y', y + 'px');
    }
  </script>
</div>

I have tried renaming the function, the var() etc. but with no luck.
Perhaps I could use Id’s and pass to the CSS, but I am struggling to find a method that would allow a dynamic number of buttons to be created.

Any help much appreciated.

Got the error code “TypeError: Cannot read properties of null (reading ‘sendTransaction’)” while trying to deploy to the goerli test network

Here is my hardhat.config.js code

// hardhat.config.js

require("@nomiclabs/hardhat-ethers");
require("@nomiclabs/hardhat-waffle");
require("dotenv").config()

// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more

const GOERLI_URL = process.env.GOERLI_URL;
const PRIVATE_KEY = process.env.PRIVATE_KEY;

/**
 * @type import('hardhat/config').HardhatUserConfig
 */
module.exports = {
  solidity: "0.8.4",
  networks: {
    goerli: {
      url: process.env.GOERLI_URL || "https://eth-goerli.alchemyapi.io/v2/PT8BEXCUKwsfvcBz8y3g7A2V7LdhUKQA",
      accounts: process.env.PRIVATE_KEY
    }
  }
};

And my deploy.js script:

// scripts/deploy.js

const hre = require("hardhat");

async function main() {
  // We get the contract to deploy.
  const BuyMeACoffee = await hre.ethers.getContractFactory("BuyMeACoffee");
  const buyMeACoffee = await BuyMeACoffee.deploy();

  await buyMeACoffee.deployed();

  console.log("BuyMeACoffee deployed to:", buyMeACoffee.address);
}

// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

I really do not know how to get it sorted and it pretty much has left me in a loop.
Please help. Thank You
I am pretty much new to using hardhat and npm. My current node v16.13.1 (npm v8.1.2)

How can I log smt to the console on button click?

I m trying something really simple: I have tree buttons and I want to log smt to the console when clicked.

HTML

<div id="button-box">
<button data-id="244">Eins</button>
<button data-id="943">Zwei</button>
<button data-id="143">Drei</button>
</div>

Javascript

// selector
    const buttonBox = document.getElementById('button-box');

// eventlistener
    buttonBox.addEventListener('click', event => {
    console.log("button clicked");
});

I m getting the following error:

Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)

Grateful for any tipps.

cypress can not find component.js file when start component testing in chrome but there is still exists file component.js exactly as the path

I am newbie with Cypress and here is my problem.

I add the component test case into the component folder and ran it by web browser as the guide, but they said I have this error

my error : can not find module

as you can see in this picture, they said that they can not find module component.js

but I had this file in exactly in this folder as you can see in this picture

my component.js file's path

I do not know why I have this error ? Could you please give me some advice about this problem ? Thank you in advance.