Problem while populating orders and an array of products

hope you are doing well,
I will be gratefull for any help ,
my problem is :
I’m trying to create an e commerce web site using react ,node and mongodb,
I create the order schema wich comport the cmdRef(string), theClient(Id of the user) and an array of Products(with ProductId nd qty) like the code bellow:
Orderchema=new mongoose.Schema({ CmdRef:String, Client:{type: mongoose.Schema.Types.ObjectId, ref: 'User'}, TotalProducts:[{ProductId:{type: mongoose.Schema.Types.ObjectId, ref: 'Product'},Quantity:Number}],

and now I’m trying to create the route to get all the Orders

    CommandRouter.get('/AllCommands',async(req,res)=>{
  try {
    const cmd= await  Command.find({}).populate({path: 'Client', select: 'firstName lastName'}).populate({path:'TotalProducts'})
    // 
    res.json(cmd)
} catch(error)
    { 
 
        return res.status(500).send({message : "error get orders"})

    } 
})

Here I found a problem while populating the products Id in the table
it populates the client Id and returns all informations about the User but fail with the product table this is the full response using PostMan

Have any of you any Idea about how to populate the productId in the TotalProducts table?

How to add event handlers to button elements rendered in an OL using Javascript and get the index position?

I’m trying to build a simple to do list application. I’ve linked my input field to an array which gets rendered out as an ordered list, and there are two buttons added to each item, one to state “completed” and one for “remove”.

I’ve having difficulty with two parts: 1) adding event handlers to the buttons rendered out in the OL (I’ve managed to in the code below but I’m not sure if it’s the right way. Part 2) identifying the index of the item so that I can modify it with the completed and remove buttons.

I’ve tried to use event delegation to tackle part 1 but I’m not sure if this is correct, and I don’t know how to relate it to part 2.

document.getElementById("parent-list").addEventListener("click", function(e) {
    if(e.target && e.target.nodeName == "BUTTON") {
        console.log(e.target);
    }
});

Cast $event.target to HTMLInputElement within Angular’s HTML template

From within a template’s input element, I wish to pass $event.target’s value to an onChange() function.

<input (input)="onChange($event.target?.value)">

This leads to an error: Property 'value' does not exist on type 'EventTarget'.ngtsc(2339). My thoughts are that $event.target by default has an EventTarget type and should be somehow cast to HTMLInputElement type, but I can’t find a way to achieve this. All examples I’ve found suggest to pass $event itself and make a cast within a component’s code. Disabling or lowering strictness is also not an option for me. Is there a way to set type directly within a template?

Thanks in advance.

Does Google Apps Script Session Information Work Different for Gmail accounts vs other Workspace Domain Accounts?

I’m writing a signoff script in Google Apps Script for GSheets that allows users to select their name from a dropdown list in a cell, then if the name matches the currently active account, another function will run to lock the row etc. Everything is working perfectly on my gmail account, but when the client tries to run the script using an account managed by google but with a non-gmail domain, the email address check fails. I’m waiting on the client to send me the log info as I don’t have permissions to access it in their file, but wanted to see if anyone else had run into this issue.

In the example code with modified company and username, the code does NOT work, but if I set atDomainString to “@gmail.com” and name to my gmail address and run under my account, it does.

const atDomainString = "@redactedcompany.com";
const name = "JSmith";

    function userMatchesSignature(name) {
      let user = Session.getEffectiveUser().toString().toLowerCase();
      let signUser = (name + atDomainString).toLowerCase();
      Logger.log("User: <"+user + "> vs <" + signUser +">");
    
      return user === signUser;
    }

How to divide an array into sub arrays based on object values (with min/max limits)?

I am looking for help with the data in a football related app I am building.

Take this as a sample of the data I am dealing with:

const squad = {
  goalkeepers: [
    { player1: { score: 10 } },
    { player2: { score: 12 } }
  ],
  defenders: [
    { player3: { score: 3 } },
    { player4: { score: 19 } },
    { player5: { score: 5 } },
    { player6: { score: 21 } },
    { player7: { score: 6 } },
  ],
  midfielders: [
    { player8: { score: 7 } },
    { player9: { score: 1 } },
    { player10: { score: 18 } },
    { player11: { score: 11 } },
    { player12: { score: 8 } },
  ],
  attackers: [
    { player13: { score: 7 } },
    { player14: { score: 2 } },
    { player15: { score: 16 } }
  ]
}

There are 15 players here and I want to divide them into two groups:

  • A strongest possible outfield team of 11 players based on their score value.
  • The remaining 4 players are to go on the bench.

The twist here is that there is a minimum number of players required in each position of the 11 outfield players.

  • Goalkeepers: EXACTLY 1.
  • Defenders: MIN 3, MAX 5.
  • Midfielders: MIN 2, MAX 5.
  • Forwards: MIN 1, MAX 3.

For anyone familiar with Fantasy Premier League, the rules work the same way:

Your team can play in any formation providing that 1 goalkeeper, at least 3 defenders and at least 1 forward are selected at all times.

I’ve tried concatinating the arrays to one large array and sorting them by player score value but I can’t work out how to calculate the strongest first 11 players from that point while adhering to the position rules.

Any help would be greatly appreciated.

tabBarOptions not applied to project (React Native)

I am creating a small app that has a to-do list and a calendar. At the bottom is a bottom tab navigator. Everything works and is functional, however, when I try to add style: {} inside tabBarOptions it isn’t being applied. Changing activeTintColor, inactiveTintColor and labelStyle works just fine.

I tried to create a stylesheet and replace everything inside tabBarOptions, but that didn’t work. My main goal is to simply create a slightly larger bar along the bottom of the screen. I don’t even want a crazy custom navigation bar, just slightly larger so I can make the items inside a little bigger.

MainContainer Class:

import React from 'react';
import {StyleSheet} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons'

//screens 
import Calendar from './screens/Calendar';
import ToDoList from './screens/ToDoList';

// Screen names
const calendarName = 'Calendar';
const ToDoListName = 'To Do List';

const Tab = createBottomTabNavigator();

export default function MainContainer() {
    return (
        <NavigationContainer>
            <Tab.Navigator
                tabBarOptions={{
                    activeTintColor: 'tomato',
                    inactiveTintColor: 'black',
                    labelStyle: {paddingBottom: 10, fontSize: 10},
                    style: {padding: 10, height: 70},
                }}
                initialRouteName={ToDoListName}
                           screenOptions={({route}) => ({
                               tabBarIcon: ({focused, color, size}) => {
                                   let iconName;
                                   let rn = route.name;

                                   if (rn === ToDoListName) {
                                       iconName = focused ? 'list' : 'list-outline'; //icons in package. Change later.
                                   } else if (rn === calendarName) {
                                       iconName = focused ? 'calendar' : 'calendar-outline'
                                   }
                                   return <Ionicons name={iconName} size={size} color={color}/>
                               },
                           })}>

                <Tab.Screen name={ToDoListName} component={ToDoList}/>
                <Tab.Screen name={calendarName} component={Calendar}/>

            </Tab.Navigator>
        </NavigationContainer>
    )
}

For reference here is my ToDoList class

import { KeyboardAvoidingView, StyleSheet, Text, View, TextInput, TouchableOpacity, Platform, Keyboard } from 'react-native';
import Task from '../../components/Task';
import React, { useState } from 'react';
import { ScrollView } from 'react-native-web';


export default function ToDoList() {
    const [task, setTask] = useState();
    const [taskItems, setTaskItems] = useState([]);

    const handleAddTask = () => {
        Keyboard.dismiss();
        setTaskItems([...taskItems, task])
        setTask(null);
    }


    const completeTask = (index) => {
        let itemsCopy = [...taskItems];
        itemsCopy.splice(index, 1);
        setTaskItems(itemsCopy)
    }

    return (
        <View style={styles.container}>
            {/* Scroll View when list gets longer than page */}
            <ScrollView contentContainerStyle={{
                flexGrow: 1
            }} keyboardShouldPersistTaps='handled'>

                {/*Today's Tasks */}
                <View style={styles.tasksWrapper}>
                    <Text style={styles.sectionTitle}>Today's Tasks</Text>
                    <View style={styles.items}>
                        {/* This is where the tasks will go*/}
                        {
                            taskItems.map((item, index) => {
                                return (
                                    <TouchableOpacity key={index} onPress={() => completeTask(index)}>
                                        <Task text={item} />
                                    </TouchableOpacity>
                                )
                            })
                        }
                    </View>
                </View>

            </ScrollView>

            {/* Write a task section */}
            {/* Uses a keyboard avoiding view which ensures the keyboard does not cover the items on screen */}
            <KeyboardAvoidingView
                behavior={Platform.OS === "ios" ? "padding" : "height"}
                style={styles.writeTaskWrapper}>
                <TextInput style={styles.input} placeholder={'Write a task'} value={task} onChangeText={text => setTask(text)} />
                <TouchableOpacity onPress={() => handleAddTask()}>
                    <View style={styles.addWrapper}>
                        <Text style={styles.addText}>+</Text>
                    </View>
                </TouchableOpacity>
            </KeyboardAvoidingView>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#E8EAED',
    },
    tasksWrapper: {
        paddingTop: 20,
        paddingHorizontal: 20,
    },
    sectionTitle: {
        fontSize: 24,
        fontWeight: 'bold',
    },
    items: {
        marginTop: 30,
    },
    writeTaskWrapper: {
        position: 'absolute',
        bottom: 20,
        paddingLeft: 10,
        paddingRight: 10,
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center'
    },
    input: {
        paddingVertical: 15,
        width: 250,
        paddingHorizontal: 15,
        backgroundColor: '#FFF',
        borderRadius: 60,
        borderColor: '#C0C0C0',
        borderWidth: 1,
    },
    addWrapper: {
        width: 60,
        height: 60,
        backgroundColor: '#FFF',
        borderRadius: 60,
        justifyContent: 'center',
        alignItems: 'center',
        borderColor: '#C0C0C0',
        borderWidth: 1,
    },
    addText: {

    },

});

And my Calendar class

import * as React from 'react';
import { View, Text } from 'react-native';
export default function Calendar(){

    return(
        <View>
            <Text>Calendar Will go here</Text>
        </View>
    )

}

I made a Task component for the ToDoList. Not sure if you need it to solve this but I’ll paste it here anyway.

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { TouchableOpacity } from 'react-native-web';

const Task = (props) => {
    return (
        <View style={styles.item}>
            <View style={styles.itemLeft}>
                <View style={styles.square}></View>
                <Text style={styles.itemText}>{props.text}</Text>
            </View>
            <View style={styles.circular}></View>
        </View>
    )
}

const styles = StyleSheet.create({
    item: {
        backgroundColor: '#FFF',
        padding: 15,
        borderRadius: 10,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginBottom: 20,

    },
    itemLeft: {
        flexDirection: 'row',
        alignItems: 'center',
        flexWrap: 'wrap',
    },
    square: {
        width: 24,
        height: 24,
        backgroundColor: '#55BCF6',
        opacity: .4,
        borderRadius: 5,
        marginRight: 15,
    },
    itemText: {
        maxWidth: '80%',

    },
    circular: {
        width: 12,
        height: 12,
        borderColor: '#55BCF6',
        borderWidth: 2,
        borderRadius: 5
    },
});

export default Task;

How to get a directory path with html5 tag

I want to get a directory’s full path through html’s <input> method, but when I try to use the type="file" webkitdirectory multiple tag, I just select all of the files in a directory to upload. How can I get the path a directory? And also, how can I get the path value in javascript?

Requesting page on button click with Spring, Thymeleaf and js

so I’ve done simple implementatnion on reload-less content loading.
It uses AJAX to load content from another controller.

    $(document.body).on('click', 'button#first', function() {
        $('#content').load("/first");
    });

    $(document.body).on('click', 'button#second',function() {
        $('#content').load("/second");
    });

For now I have 3 controllers:

  • HomeController (localhost/)
  • FirstController (localhost/first)
  • SecondController (localhost/second)
    @GetMapping("/first")
    public String getFirst() {
        return "includes/first:: content";
    }

    @GetMapping("/second")
    public String getSecond() {
        return "includes/second :: content";
    }

And that works fine, but of course I can also just enter /first or /second and get unproper content as they’re fragments. So my question is there any way to prevent people from just entering /first in their browser or handle loading content server-side instead of ajax?

REMOVE FIRST FALSE STATEMENTS [duplicate]

I just wanna ask if I possible to hide the first false output

Heres my code,

 let people = [
   {name:'john'}, 
   {name:'smith'}, 
   {name:'jerry'}, 
   {name:'peter'}, 
   {name:'justine'}, 
   {name:'rain'}];

 people.map(person => {
   if(person.name == 'jerry'){
     console.log('jerry');
   } else {
     console.log('false');
   }
}) 

  output:
   "false"
   "false"
   "jerry"
   "false"
   "false"
   "false"

I just want to remove the first false statement before getting the value.
Thank you in advance.

Querying Rest converting data into another query – ANGULAR

Good morning Devs.

I would like to know how to make my API access the data that is in the Rest and convert it to Json in Angular 11.

 {
    "id": 447281168,
    "node_id": "R_kgDOGqj4EA",
    "name": "eventos",
    "full_name": "keomasoliveira/eventos",
    "private": false,
    "owner": {
      "login": "keomasoliveira",
      "id": 59379283,
      "node_id": "MDQ6VXNlcjU5Mzc5Mjgz",
      "avatar_url": "https://avatars.githubusercontent.com/u/59379283?v=4",
      "gravatar_id": "",
      "url": "https://api.github.com/users/keomasoliveira",
      "html_url": "https://github.com/keomasoliveira",
      "followers_url": "https://api.github.com/users/keomasoliveira/followers",
      "following_url": "https://api.github.com/users/keomasoliveira/following{/other_user}",
      "gists_url": "https://api.github.com/users/keomasoliveira/gists{/gist_id}",
      "starred_url": "https://api.github.com/users/keomasoliveira/starred{/owner}{/repo}",
      "subscriptions_url": "https://api.github.com/users/keomasoliveira/subscriptions",
      "organizations_url": "https://api.github.com/users/keomasoliveira/orgs",
      "repos_url": "https://api.github.com/users/keomasoliveira/repos",
      "events_url": "https://api.github.com/users/keomasoliveira/events{/privacy}",
      "received_events_url": "https://api.github.com/users/keomasoliveira/received_events",
      "type": "User",
      "site_admin": false
    },
    "html_url": "https://github.com/keomasoliveira/eventos",
    "description": null,
    "fork": false,
    "url": "https://api.github.com/repos/keomasoliveira/eventos",
    "forks_url": "https://api.github.com/repos/keomasoliveira/eventos/forks",
    "keys_url": "https://api.github.com/repos/keomasoliveira/eventos/keys{/key_id}",
    "collaborators_url": "https://api.github.com/repos/keomasoliveira/eventos/collaborators{/collaborator}",
    "teams_url": "https://api.github.com/repos/keomasoliveira/eventos/teams",
    "hooks_url": "https://api.github.com/repos/keomasoliveira/eventos/hooks",
    "issue_events_url": "https://api.github.com/repos/keomasoliveira/eventos/issues/events{/number}",
    "events_url": "https://api.github.com/repos/keomasoliveira/eventos/events",
    "assignees_url": "https://api.github.com/repos/keomasoliveira/eventos/assignees{/user}",
    "branches_url": "https://api.github.com/repos/keomasoliveira/eventos/branches{/branch}",
    "tags_url": "https://api.github.com/repos/keomasoliveira/eventos/tags",
    "blobs_url": "https://api.github.com/repos/keomasoliveira/eventos/git/blobs{/sha}",
    "git_tags_url": "https://api.github.com/repos/keomasoliveira/eventos/git/tags{/sha}",
    "git_refs_url": "https://api.github.com/repos/keomasoliveira/eventos/git/refs{/sha}",
    "trees_url": "https://api.github.com/repos/keomasoliveira/eventos/git/trees{/sha}",
    "statuses_url": "https://api.github.com/repos/keomasoliveira/eventos/statuses/{sha}",
    "languages_url": "https://api.github.com/repos/keomasoliveira/eventos/languages",
    "stargazers_url": "https://api.github.com/repos/keomasoliveira/eventos/stargazers",
    "contributors_url": "https://api.github.com/repos/keomasoliveira/eventos/contributors",
    "subscribers_url": "https://api.github.com/repos/keomasoliveira/eventos/subscribers",
    "subscription_url": "https://api.github.com/repos/keomasoliveira/eventos/subscription",
    "commits_url": "https://api.github.com/repos/keomasoliveira/eventos/commits{/sha}",
    "git_commits_url": "https://api.github.com/repos/keomasoliveira/eventos/git/commits{/sha}",
    "comments_url": "https://api.github.com/repos/keomasoliveira/eventos/comments{/number}",
    "issue_comment_url": "https://api.github.com/repos/keomasoliveira/eventos/issues/comments{/number}",
    "contents_url": "https://api.github.com/repos/keomasoliveira/eventos/contents/{+path}",
    "compare_url": "https://api.github.com/repos/keomasoliveira/eventos/compare/{base}...{head}",
    "merges_url": "https://api.github.com/repos/keomasoliveira/eventos/merges",
    "archive_url": "https://api.github.com/repos/keomasoliveira/eventos/{archive_format}{/ref}",
    "downloads_url": "https://api.github.com/repos/keomasoliveira/eventos/downloads",
    "issues_url": "https://api.github.com/repos/keomasoliveira/eventos/issues{/number}",
    "pulls_url": "https://api.github.com/repos/keomasoliveira/eventos/pulls{/number}",
    "milestones_url": "https://api.github.com/repos/keomasoliveira/eventos/milestones{/number}",
    "notifications_url": "https://api.github.com/repos/keomasoliveira/eventos/notifications{?since,all,participating}",
    "labels_url": "https://api.github.com/repos/keomasoliveira/eventos/labels{/name}",
    "releases_url": "https://api.github.com/repos/keomasoliveira/eventos/releases{/id}",
    "deployments_url": "https://api.github.com/repos/keomasoliveira/eventos/deployments",
    "created_at": "2022-01-12T16:00:01Z",
    "updated_at": "2022-01-16T07:14:18Z",
    "pushed_at": "2022-01-30T23:00:07Z",
    "git_url": "git://github.com/keomasoliveira/eventos.git",
    "ssh_url": "[email protected]:keomasoliveira/eventos.git",
    "clone_url": "https://github.com/keomasoliveira/eventos.git",
    "svn_url": "https://github.com/keomasoliveira/eventos",
    "homepage": null,
    "size": 891,
    "stargazers_count": 1,
    "watchers_count": 1,
    "language": "C#",
    "has_issues": true,
    "has_projects": true,
    "has_downloads": true,
    "has_wiki": true,
    "has_pages": false,
    "forks_count": 0,
    "mirror_url": null,
    "archived": false,
    "disabled": false,
    "open_issues_count": 0,
    "license": null,
    "allow_forking": true,
    "is_template": false,
    "topics": [

    ],
    "visibility": "public",
    "forks": 0,
    "open_issues": 0,
    "watchers": 1,
    "default_branch": "master"
  },
  {

This tag looks like this:

“languages_url”: “https://api.github.com/repos/keomasoliveira/eventos/languages”,
I would like it to be like this:

{

languages_url”: {
“C#”: 32465,
“TypeScript”: 28380,
“HTML”: 15636,
“JavaScript”: 1424,
“SCSS”: 1019
}
}

Could anyone help?

Mock function call inside other function

How to mock a function call inside another function in JavaScript?

Code example:

returnNumber.js

export default function returnNumber() {
  return 5;
}

myFunction.js

import returnNumber from "./returnNumber";

export default function myFunction(input) {
  return input + returnNumber();
}

I would like to test it by doing something like this, but none if the code examples I saw seem to be working in my case

import myFunction from "./myFunction";

test("myFunction should equal 6", async () => {
  returnNumber = () => {
    return 1
  }

  expect(myFunction(5)).toEqual(6);
});

Considering the example above; can I test myFunction while overriding returnNumber’s return value?

How to hide THIS element when I click THIS element’s close button (with multiple elements)

I have an alert box that has its own close button. I didn’t know users would be placing multiple instances of it on a web page.

Currently, when the close button of an element is clicked, only the first instance gets hidden. I can’t close the other one after that. When I click its close button, nothing happens.

I want to be able to click each element’s close button to hide that element and have the ability to hide the elements one at a time. I feel like it has something to do with the THIS keyword, but I’m not sure.

Here’s my JavaScript code. Can anyone please help? Thank you.

const alert = document.querySelector('#dcom-c-alert');
const hideAlert = document.querySelector('.dcom-c-close-alert-wrapper');

function closeAlert() {
    alert.classList.add('hide');
}

hideAlert.addEventListener('click', function () {
    closeAlert();
});

hideAlert.addEventListener("keydown", e => {
    // ADA: Next button activates with spacebar or enter key
    if (e.key === " " || e.key === "Enter" || e.key === "Spacebar") {
        closeAlert();
    }
});

translate image to infinity 3 on screen and 8 total

i want transform this static image
IMG

into this site for see what i mean scroll down the page. The code that i did it is this, the objective is do 8 image total but only 3 on screen that go on to infinity. Javascript is not implemented, i should like know also the copyright if is a problem and what i can do to do same think without risk the copyright

    .content {
     display: flex;
     justify-content: space-around;
     align-items: center;
     padding: 20px;
     width: 100%;
      }
    .content__row {
     display: flex;
     width: 100%;
     margin: 5px 0;
     }
    .content__img {
     display: flex;
     width: 80%;
     height: 90%;
     padding: 0%;
     }
     .content__a {
      text-decoration: none;
      align-items: center;
     }
     .content__p {
      align-items: center;
      text-align: center; 
      width: 80%;
      font-size: 35px;
      font-weight: 900;
      font-family: 'Ubuntu', sans-serif;
      color: rgb(39, 39, 255);
      } 
        <div class="content">
      <div class="content__row">
        <a class="content__a" href="#">
          <img class="content__img" src="https://via.placeholder.com/300x600" alt="">
          <p class="content__p">COMPILARE
            <br>
            <span class="content__span">730?</span>
          </p>
        </a>
        <a class="content__a" href="#">
          <img class="content__img" src="https://via.placeholder.com/300x600" alt="">
          <p class="content__p">CALCOLARE
            <br>
            <span class="content__span">L'ISEE?</span>
          </p>
        </a>
        <a class="content__a" href="#">
          <img class="content__img" src="https://via.placeholder.com/300x600" alt="">
          <p class="content__p">CALCOLARE
            <br>
            <span class="content__span">L'ISEE?</span>
          </p>
        </a>
      </div>
    </div>