Dynamic Object Property Question with Reduce Function

I wanted to ask a simple question about dynamic object properties.
In this example function I made, I noticed that I need square brackets between the cur.name variable but not for cur.age in the return statement. I found that it was something about dynamic object properties but was unsure of when I exactly need square brackets for parameters. Could I ask when I need square brackets?

Here is an example function:

const array = [
  {name: 'A', age: 1},
  {name: 'B', age: 2},
  {name: 'C', age: 3},
];

const example = (array) => {
    return array.reduce((acc, cur) => {return {...acc, [cur.name]: cur.age} }, {})
}

console.log(example(array));

//Output that I want is {A: 1, B: 2, C: 3} and it works.

How to format x-axis time scale values in Chart.js v4.2.1

I am not able to format the display format of Time. I am using chart.js v4.2.1 and date-fns v3.0.0(this as script from cdnjs).
I am able to get the unit but the display format I want is Day of a week day.Month (e.g: Mo 12.04, Tue 13.04, etc…)

Here is the code:

scales: {
            x: {
                type: 'time',
                time: {
                    unit: 'day',
                    displayFormats: {
                        day: 'need to be done'
                    }
                }
            }

I am writing a project with flask (for python) and when I run from the Visual Studio Code 2. The project included html files I got this error message;

jinja2.exceptions.TemplateSyntaxError: expected token ‘,’, got ‘index'[enter image description here](https://i.stack.imgur.com/VIerN.png)

This was the code block from where I encountered the challenge

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
      integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
      crossorigin="anonymous"
    />
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
      crossorigin="anonymous"
    />

    <title>{% block title %}Home{% endblock %}</title>
  </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
      <button
        class="navbar-toggler"
        type="button"
        data-toggle="collapse"
        data-target="#navbar"
      >
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbar">
        <div class="navbar-nav">
          <a class="nav-item nav-link" id="login" href="/login">Login</a>
          <a class="nav-item nav-link" id="signUp" href="/sign-up">Sign Up</a>
          <a class="nav-item nav-link" id="logout" href="/logout">Logout</a>
          <a class="nav-item nav-link" id="home" href="/">Home</a>
        </div>
      </div>
    </nav>

    <script
      src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
      integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
      integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
      integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
      crossorigin="anonymous"
    ></script>

    <script
      type="text/javascript"
      src="{{ url_for('static, filename='index.js') }}"
    ></script>
  </body>
</html>

PLEASE I WILL APPRECIATE SOME INSIGHTS AS TO WHAT I WAS DOING WRONG

Javascript modify existing array with object of different key

I’ve got this snippet of code

const name = 'test1'
const payload = [
    {
        "manSegChildId": "5497",
        "manSegChildDesc": "test4"
    },
    {
        "manSegChildId": "5314",
        "manSegChildDesc": "test1"
    },
    {

        "manSegChildId": "5159",
        "manSegChildDesc": "test5"
    }
]

const newObj = payload.map(nameObj => {
  if(nameObj.manSegChildDesc === name) {
    return {
    "id": nameObj.manSegChildId,
    "label" : nameObj.manSegChildDesc,
    "disabled": true
    }
  }
});

console.log(newObj)

I need simply an object I’m returning and not an array and not this undefined ones. Also, is there any optimal way so perform this changes
expected O/P

{
   "id": 5314,
   "label" : "test1",
   "disabled": true
 }

ng-http-loader keeps on loading in angular electron app

I am sending an event from my electron main process to angular using IPC communication as below:

//in main.js

win.webContents.send(‘info’);

//in angular file which is listening to this event

this.electronService.ipcRenderer.on('info', () => {
  // calling a function here which is performing a HTTP request
})

I am using ng-http-loader to show a loader whenever a HTTP request is made. The problem I am facing is that the loader keeps alive (keeps on loading) here. I am not able to understand this behavior that why this is happening because it is working fine everywhere else.
The problem is coming only when I am sending the event from electron to angular. Can anybody help?

How to show loading of table whenever List filter changes in React Admin

Is there any way to get the loading or fetching state of Data provider in react admin?
So that we can show shimmer or loader on tables till the data fetching is done.

I have tried to get using useContextList() hook inside MyActions component but it don’t trigger. Sometimes it show or not.

 <List
            {...props}
            title="Data"
            exporter={false}
            filter={filter}
            empty={false}
            actions={<MyActions filter={filter} />}
>
    <Datagrid>
     <TextField source="name" label="Name" />
     <TextField source="age" label="Age" />
     <TextField source="gender" label="Gender" />
    </Datagrid>
</List>

Tipo de dado inexistente [closed]

Tenho uma chamada de api que um dos dados retornados é do tipo ENUM, porém o looker studio não ler ou não aceita este tipo de dados, já tentei formas de converter ele, mas não funciona, alguém teria alguma solução para converter ou ajustar?

vi sobre criar um novo FieldType, mas não sei como realizar o upload do arquivo com o novo fieldtype.

Chamar uma api para receber todos os dados dela.

Block local holidays and sundays at the native date-picker of HTML5

As far as possible, I avoid using third party resources and I prefer natives. For a project, I need the native HTML5 date container but showing local vacations and blocked sundays.

Many third-party components/plugins allow them to spend the holidays, but do not use the native date-picker, but are customized. I prefer the native not to have to deal with the Browser and the device being used (desktop, Android or iOS).

I will use min="xxxx-xx-xx" and max="xxxx-xx-xx" to establish the range of days available to choose, but is it possible to block specific days within that range or do I have to use the resource of a third?

Sharing code logic between php and javascript

I have a website that does some complex math on the server side (php) and on the client side (javascript). The math is identical on both sides, and the code was manually translated between the languages. The problem is in code maintenance: one always needs to update and validate both sides when doing a modification. Is there a way to have to maintain only one side, and have the other side reflect the changes?

Any other options? Are there automatic code translaters that could auto-generate some core files?

One solution not considered si to do ajax requests to the server instead of doing the math client-side. This has been rejected due to the response time being too long.

Javascript Tree (Array of object) Traversal with Ancestors

I am trying to make a tree traversal function in javascript. I also want ancestors of any nodes. That’s why I have written code like this:

const visit = (tree) => {
  if (!typeof ancestors){
    const ancestors = []
  }
  console.log(ancestors)
  if (Array.isArray(tree.children)) {
    ancestors.push(tree)
    tree.children.forEach((e) => {
      visit(e);
    })
  }
}

visit({
   "type":"root",
   "children":[
      {
         "type":"element",
         "children":[
            {
               "type":"element"
            },
            {
               "type":"element"
            },
            {
               "type":"element"
            },
            {
               "type":"element"
            }
         ]
      },
      {
         "type":"element"
      },
      {
         "type":"element"
      },
      {
         "type":"element"
      }
   ]
})

But it is giving me error:

Error: ancestors is not defined

Can someone help me what to do? (I don’t want to put this ancestors as property of object.)

How can I get an access to removeBtn without unnecessarily invoking renderBook() function this code? (vanilla JS)

I’m a beginner in programming and I’m making a simple interface where a user can remove the card on a webpage by clicking the remove button.

And now I’m trying to implement this removing functionality.

The whole code is in’test’ branch here, not ‘main’. https://codesandbox.io/p/github/Eveieve/library/test?workspaceId=5fe3d173-5c43-47d3-9b21-7447f2999e60&file=%2Fscript.js&selection=%5B%7B%22endColumn%22%3A2%2C%22endLineNumber%22%3A73%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A59%7D%5D

Currently I have a rendering function where I render elements to the page, including the remove button. Since I want to be able to click that and remove the book, I need an access to the remove button.

Problem is I don’t know how I can get an access to the remove button outside of the rendering function without unnecessarily invoking it (this throws an error, and i’m aware why it’s causing it)

The error is

Uncaught TypeError: Cannot read properties of undefined (reading 'title')
    at renderBook (script.js:44:33)
    at script.js:68:23```
//some code....
  // create removeBtn
  const removeBtn = document.createElement("button");
  removeBtn.classList.add = ("remove-btn", "property");
  removeBtn.textContent = "Remove";
  card.appendChild(removeBtn);

  return { removeBtn };
}

const { removeBtn } = renderBook();

function removeBook(idOfBook) {
  const filteredLibrary = myLibrary.filter((book) => book.id !== idOfBook);
  return { filteredLibrary };
}

I tried to ‘unpack’ removeBtn variable from renerBook() function but since I’m invoking it, the function gets called even before user adds a book so it throws me an error that whatever variable used in the renderBook() is not defined.

How can I get access to the removeBtn without unnecessarily invoking the function?

Or, is it a bad idea to have removeBook function outside the Class? Is it better to have them inside the Class as it’s a functionality that every instance of Book needs?

I separated the functions to make my code more organized but I always encounter this issue of not having access to variables that are scoped to the function. I was wondering if there’s a better way to go about this, or if there’s a fix that can be done to my code.

I’m aware I can just dump everything in the global scope, but I wanted to practice organizing the code better. Let me know if anything’s unclear,appreciate the help.

Error: Chat.find(…).populate(…).populate(…).strictPopulate is not a function

I am trying to populate group chat in mongoose and node and I receive the error that populate is not a function.

I use mongoose 5.12.9

Here the chatModel:

const mongoose = require('mongoose');

const chatModel = mongoose.Schema(
    {
        chatName: { type: String, trim: true },
        isGroupChat: { type: Boolean, default: false },
        users: [
            {
                type: mongoose.Schema.Types.ObjectId,
                ref: "User",
            },
        ],
        latestMassage: {
            type: mongoose.Schema.Types.ObjectId,
            // required: false,
            ref: "Message",
        },
        groupAdmin: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
        },
    },
    {
        timestamps: true,
    }
);


const Chat = mongoose.model("Chat", chatModel);

module.exports = Chat;

And then the find that I use:

const asyncHandler = require("express-async-handler");
const Chat = require("../models/chatModel");
// const chatModel = require('../models/chatModel');
const User = require("../models/userModel");

const accessChat = asyncHandler(async (req, res) => {
    const { userId } = req.body;

    if (!userId) {
        console.log("UserId param not sent with request");
        return res.sendStatus(400);
    }

    var isChat = await Chat.find({
        isGroupChat: false,
        $and: [
            { users: { $elemMatch: { $eq: req.user._id } } },
            { users: { $elemMatch: { $eq: userId } } },
        ],
    })
        .populate("users", "-password")
        .strictPopulate("latestMessage");

    isChat = await User.populate(isChat, {
        path: "'latestMessage.sender'",
        select: "name pic email",
    });

    if (isChat.length > 0) {
        res.send(isChat[0]);
    }
    else {
        var chatData = {
            chatName: "sender",
            isGroupChat: false,
            users: [req.user._id, userId],
        };

        try {
            const createdChat = await Chat.create(chatData);

            const FullChat = await Chat.findOne({ _id: createdChat._id }).populate("users", "-password");

            res.status(200).send(FullChat);
        } catch (error) {
            res.status(400);
            throw new Error(error.message);
        }
    }
});

module.exports = { accessChat, fetchChats, createGroupChat };

It show the chat in postman with post request using token

……………………………………………………

and it show the Error—

“message”: “Chat.find(…).populate(…).strictPopulate is not a function”,
“stack”: “TypeError: Chat.find(…).populate(…).strictPopulate is not a functionn at D:ProjectChatNETbackendcontrollerschatControllers.js:22:10n at asyncUtilWrap (D:ProjectChatNETnode_modulesexpress-async-handlerindex.js:3:20)n at Layer.handle [as handle_request] (D:ProjectChatNETnode_modulesexpresslibrouterlayer.js:95:5)n at next (D:ProjectChatNETnode_modulesexpresslibrouterroute.js:144:13)n at D:ProjectChatNETbackendmiddlewareauthMiddleware.js:18:13n at process.processTicksAndRejections (node:internal/process/task_queues:95:5)”

How to write unit test cases for my code for the confirmation madal

import {createConfirmationModal } from ‘/form.js’;

I’m trying to write unit test cases for my code, but unable to write it

    this.store.on('auth:signout:submit', async () => {
      const { pathname } = this.store.location;
      const pagePath = `${this.store.hrefRoot}/my-account/orders`;
      if (pathname === pagePath ) {
        this.ordersWarningModal(pathname);
      } else {
        this.orders(pathname);
      }
    });

  async pagePathWarningModal(pathname) {
    const ph = await getPlaceholders();
    const onConfirm = async () => {
      this.onSignOutPage(pathname);
    };

    try {
      await createConfirmationModal({
        onConfirm,
        title: ph.Delete,
        confirmText: ph.leave,
        abortText: ph.cancel,
      });
    } catch (e) {
      log.error('failed to open a modal: ', e);
    }
  }

  async onSignOutPage(pathname) {
    localStorage.removeItem(Hello_var);
  }

Here the createConfirmationModal is the function, to create a modals.

How to write the unit test cases for this js code where i can test if the modal is opened in pagepath and check with proper titles

How can i bind “store” correctly?

I wrote the code using a youtube video tutorial. I also wrote the same code written in the video tutorial on my computer, but the result was not good. The problem is that I am using redux to add an api file. If I connect index.js and store as follows, it gives me an error.

Cannot convert undefined or null to object
TypeError: Cannot convert undefined or null to object
    at Function.entries (<anonymous>)
    at Object.injectEndpoints (http://localhost:3000/static/js/bundle.js:66563:36)
    at baseCreateApi (http://localhost:3000/static/js/bundle.js:66581:16)
    at ./src/reducer/emehmonApi.js (http://localhost:3000/static/js/bundle.js:7038:85)
    at options.factory (http://localhost:3000/static/js/bundle.js:189281:31)
    at __webpack_require__ (http://localhost:3000/static/js/bundle.js:188687:33)
    at fn (http://localhost:3000/static/js/bundle.js:188938:21)
    at ./src/reducer/index.js (http://localhost:3000/static/js/bundle.js:7105:69)
    at options.factory (http://localhost:3000/static/js/bundle.js:189281:31)
    at __webpack_require__ (http://localhost:3000/static/js/bundle.js:188687:33)
import React, { Suspense } from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter, HashRouter } from "react-router-dom";
import Spinner from "./views/Spinner/Spinner";
import "./style.scss";
import { Provider } from "react-redux";
import store from "./reducer";

ReactDOM.render(
  <BrowserRouter>
    <Suspense fallback={<Spinner />}>
      <HashRouter>
        <Provider store={store}>
          <App />
        </Provider>
      </HashRouter>
    </Suspense>
  </BrowserRouter>,
  document.getElementById("root")
);