How to initialize to an empty array if my ‘students’ parameter is not passed

I am attempting to write code For the Bootcamp class (as shown in the code block) My goal is to write the code for the Bootcamp class so that if it the “students” parameter is not passed in, it is by default initialized to be an empty array from within the constructor parameter list itself. i took a stab at it with the function at the bottom of the code.

I am a bit confused regrading the proper syntax. Please See my Code Below

  • Thank you in advance 🙂
class Bootcamp{
    constructor(name,level,students){
        this.name = name;
        this.level = level;
        this.students = students;
    }
}
function student (students){
    return [];
} 

DOMContentLoaded and click event don’t occur

I have a spring boot application with thymeleaf.

I have an input box with a button. When I click on it, I do an ajax call and return a thymeleaf fragment.

I do this ajax call with this code in a fragment

    <script type="text/javascript" th:inline="javascript">

        document.addEventListener('DOMContentLoaded', function () {
            console.log("DOMContentLoaded");

            let searchAdsForm = document.getElementById("searchAdsForm")

            searchAdsForm.addEventListener("submit", function(event) {

                event.preventDefault();

                let jsonSearchAdsForm = FormDataJson.toJson(searchAdsForm)
                let urlParams = new URLSearchParams(jsonSearchAdsForm).toString();
                let url = "/findads?" + urlParams;

                fetch(url, {
                    method: "get"
                }).then(result => {
                    if (result.status != 200) {
                        throw new Error("Bad Server Response");
                    }
                    return result.text();

                }).then((content) => {
                    document.getElementById("main").innerHTML = content;
                }).catch((error) => {
                    console.log(error);
                });


            }, false);

        }, false);

        window.addEventListener('load', function () {
            console.log("full load page");
        }, false);

    </script>

It return a table of result. It’s displayed without problem.

Code who return fragment.

@GetMapping("/findads")
public String findAdsBy(Model model, @RequestParam(name="itemToSearch") String search){
    System.out.println(search);

    Flux<Ads> ads  = service.findAds(search);

    IReactiveDataDriverContextVariable data = new
                ReactiveDataDriverContextVariable((ads));
    model.addAttribute("ads", data);

    return "fragments/resultsearch::resultSearch";
}

Fragment returned

<div th:fragment="adsResultSearch" class="tabsearch">

    <table class="table table-striped">
      <tr>
       <th scope="col">Donateur</th>
       <th scope="col">Titre</th>
      </tr>
      <tr th:each="ad : ${ads}">
            <td><a href="#" th:attr="data-donor=${ad.donor}" th:text="${ad.donor}"/></td>
            <td th:text="${ad.title}"></td>
        </tr>
    </table>

    <script type="text/javascript" inline="javascript">
        console.log("js");
        document.addEventListener('DOMContentLoaded', function () {
            console.log("dom ready");
        });

        document.addEventListener('click', function (event) {
            console.log("click");
        });

    </script>

It’s like the javascript of the fragment return is never running.

Endpoint URL not found in axios PUT endpoint

When pressing a button, my app is suppose to subtract 1 from the current Quantity in the database where the name of the item is “CrossBag”

My PUT endpoint on the client:

confirm = () => {
    axios.put(`http://localhost:5000/merch/CrossBag`, {
        Quantity: this.state.merchInfo[0].Quantity - 1,
        });
};

The structure of my table merch where Name is the primary key:
enter image description here

The server side of the endpoint:

app.put('/merch', function (req, res) {

  connection.getConnection(function (err, connection) {

  if(err) 
  {
    console.log(err)
    return
  }

});
});

When I press the button though it states:

PUT http://localhost:5000/merch/CrossBag 404 (Not Found)

I’m a bit confused on how to update specifically that row’s Quantity. I read that you need some kind of ID to specify which row to change, so I made that ID my Primary Key (Name).

Can anyone provide me any guidance?

add url before output taken from javascript

I want to add a URL before the javascript output, basically, I want to enter the URL from the input field and my javascript convert it into Base64 and show it in the output box but problem is that I want to add URL as default before my base64 encoded code. Like below

User input: https://google.com
User Output (Base64): asdweoiuweosdj

But I want this

User Input:  https://google.com
User Output: https://example.com?=asdweoiuweosdj

<!DOCTYPE html>
<html>

<body>

  <div id="container">
    <div class="IO-field">
      <input type="text" id="plain-text">
      <button type="button" onclick="getInputValue();" id="text-submit">click</button>
      <input class="text" id="base-64">
    </div>


    <script>
      var plainTextIOField = document.querySelector("#plain-text"),
        base64IOField = document.querySelector("#base-64"),
        textSubmit = document.querySelector("#text-submit"),


        //use the index of each character in the array as the key that links value and corresponding char in base64 table  
        base64Table = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
          "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
          "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/"
        ];


      //function that converts a standard ASCII character decimal value into its binary correspondant and turns it into a string
      function dec2bin(dec) {
        var bin = (dec >>> 0).toString(2);
        if (bin.length < 8) {
          var itrs = 8 - bin.length;
          for (var i = 0; i < itrs; i++) {
            bin = "0" + bin;
          }
        }
        return bin;
      }


      textSubmit.addEventListener("click", function(e) {

        //block browser form reloading the page
        e.preventDefault();

        //declare variables needed during the conversion
        var string = plainTextIOField.value,
          stringToArray = string.split(''),
          s = "",
          array64 = [];

        //for each letter in the stringToArray array get its charCode, convert it to binary form, make it a string and concatenate it with the s string
        for (var i = 0; i < stringToArray.length; i++) {

          var charCode = stringToArray[i].charCodeAt(0);
          s += dec2bin(charCode);

        }

        //make s an array made of each bit represented in the s string
        s = s.split('');


        //put all the strings of the s array inside array64 and separate each series of 6 consecutive elements with a single whitespace
        for (var i = 0; i < s.length; i++) {

          if (i > 0 && i % 6 === 0)
            array64.push(" ");
          array64.push(s[i]);

        }

        //concatenate all of array64's elements into a single string and then break the string using the whitespaces just added as divider
        array64 = array64.join('').split(' ');


        //make sure each string representing a binary value in array64 is 6 chars long
        if (array64[array64.length - 1].length < 6) {

          var array64Last = array64.pop(),
            nOf0s = 6 - array64Last.length;

          for (var i = 0; i < nOf0s; i++) {

            array64Last += "0";

          }

          array64.push(array64Last);

        }


        //make sure the array64's length is a multiple of 4, and if not add correct padding as base64 encoding requires
        if (array64.length % 4 !== 0) {

          var padding = 4 - (array64.length % 4);

          for (var i = 0; i < padding; i++) {

            array64.push("=");

          }

        }


        //substitute each string in array64 with its corresponding binary value and then with the value get the right character from the base 64 table
        for (var i = 0; i < array64.length; i++) {
          if (array64[i] == "=") {
            continue;
          }
          array64[i] = base64Table[parseInt(array64[i], 2)];
        }

        //concatenate all the characters inside of array64 and done :D
        base64IOField.value = array64.join('');

      })
    </script>

</body>

</html>

Please Help I am very confused about it. I am a beginner in javascript

discord.js guildMemberAdded not firing

I’m trying to make it so when a user joins, the bot sends a message in a certain channel. I saw that you needed to enable some things in the developer portal, so I did that but it still doesn’t run when a user joins, I tried printing when the user joins but it still wont do anything.

client.on('guildMemberAdd', joinMember => {
    console.log("a")
    const joinChannel = client.channels.cache.find(channel => channel.name === 'logs')
    let joinEmbed = {
        title : `Welcome to ${client.guild.name}, @${joinMember.tag}`,
        color : embedColor
    }
    joinChannel.send({embeds : [joinEmbed]})
})

conditional formatting of anki deck class style with javascript based on a hidden variable

I have a basic anki deck configuration, I’d like to add colors for gender of a noun word in latin languages (Portuguese, to be specific):

Front:
man

Back:
homem

Example:

Gender:
m

enter image description here

<– for contrast, I’ll write example of another card –>
Front:
woman

Back:
mulher

Example:

Gender:
f

enter image description here

For better memorization, I force to type my answers:

{{Front}}
<br>
{{type:Back}}

so far so good.

Now, I created my styling:

.card-m {
 font-family: Arial;
 font-size: 26px;
 text-align: center;
 color: white;
 background-color: #66d;
}

.card-f {
 font-family: Arial;
 font-size: 26px;
 text-align: center;
 color: white;
 background-color: #f5426f;
}

.card {
 font-family: Arial;
 font-size: 26px;
 text-align: center;
}

and my back Template card has the following format:

<div id=wrapper class=card-m>
{{FrontSide}}

<hr id=answer>

{{hint:Example}}
</div>

Here’s my question:
I would like to have a javascript to read the value of Gender variable, and apply class= highlight the back of the card in either Blue, or Pink (for feminine or masculine respectively):

<script>
var x = {{Gender}}.string;
if {{Gender}} == "m"
{ 
  document.getElementById("wrapper").class='card-m';
}
else
{ 
  document.getElementById("wrapper").class='card-f';
}
</script>

But the Gender variable seems to have no effect on the class that is being applied.

Any idea why?

i cant fetch data after deployment in react app

The app work perfectly locally. The error appears after i deploy it using firebase hosting. The code below is the component where i fetch the data from the api resource

import React, { useEffect, useState } from 'react'
import{ useSelector, useDispatch} from "react-redux"
import { setProducts } from "../containers/redux/actions/productActions"
import ProductComponent from './ProductComponent';
import axios from 'axios';

function ProductList() {
    const products  = useSelector((state) => state);
    const dispatch  = useDispatch()

    const [searchValue, setSearchValue] = useState('');

    const fetchProducts = async ( searchValue) => {
     

        const response = await axios
        .get(`http://www.omdbapi.com/?s=${searchValue}&apikey=??????`)
        .catch((err) => {
            console.log("Err", err);
        });
        if(response.data.Search){
            dispatch(setProducts(response.data.Search));
        }
    };

    useEffect(() => {
        fetchProducts(searchValue);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    },[searchValue]);

    console.log("Products: " , products)
    
    return (
        <div className='home'>
            <div className='search-box'>
                    <input 
                    value={searchValue} onChange={(e) => setSearchValue(e.target.value)} 
                    type="text" 
                    placeholder="Search.." 
                    >        
                    </input>
            </div>
            <div className='products-list'>
            <ProductComponent /> 
            </div>
        </div>
    )
}

export default ProductList

Error message appears on the console of the deployed app :

ProductList.js:21 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data')

Saving token in localStorage on Heroku

I have an app deployed on Heroku. The problem is when I run it on Heroku, the value of auth token does not store in browser’s local storage (when I run it locally everything works just fine).

Here is the JS code that gets the token and stores it:

document.querySelector("#submit").onclick = function(){ 
    var object = {
        "email": document.getElementById("email").value,
        "password": document.getElementById("password").value
    };

    sendRequest('POST', '/auth/sign-in', object)
    .then(data => {localStorage.token = data.token;console.log(data.token)})
    .catch(err => console.log(err))
}


function sendRequest(method, url, params = null) {
    return new Promise ( (resolve, reject) => {
        const xhr = new XMLHttpRequest()
    xhr.open(method, url)
    xhr.responseType = 'json'
    xhr.setRequestHeader('Content-Type', 'application/json')
    
    xhr.onload  = () => {
        if(xhr.status >= 400) {
            reject(xhr.response)
        } else {
            resolve(xhr.response)
        }
    }

    xhr.onerror = () => {
        reject(xhr.response)
    }

    xhr.send(JSON.stringify(params))
    })
}
    

The console always shows “null” when I submit the form and this code runs.

On the server’s side the email and password are getting checked in database and JSON with the token is sent. My backend is on Golang, the token is sent like this:

func (h *Handler) signIn(c *gin.Context) {
...

c.JSON(http.StatusOK, map[string]interface{}{
        "token": token,
    })
}

I logged the value of token before it is sent from the server and it seems like the token is getting generated fine.

I would be grateful for any help!

HTML, CSS and Angular: Something goes wrong

I’m learning Codecademy course: AngularJS 1.X and I decided to do an app like that (chapter ‘Your first app’). First I copied the code from Codecademy and pasted it into VS Code. But the output isn’t like in Codecademy.

Error:
Error

I found that the wrong code is in line 20 – 30 HTML but I don’t know how fix it. Here is my code:

HTML

<html>
  <head>
      <link href="https://content.codecademy.com/projects/bootstrap.min.css" rel="stylesheet" />
    <link href='http://fonts.googleapis.com/css?family=Roboto:500,300,700,400' rel='stylesheet' type='text/css'>
    <link href="css/main.css" rel="stylesheet" />

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
  </head>
  <body ng-app="Untitled-1">
    <div class="header">
      <div class="container">
        <h1>Book End</h1>
      </div>
    </div>

    <div class="main" ng-controller="MainController">
      <div class="container">

        <h1>{{ title }}</h1>
        <h2>{{ promo }}</h2>

        <div ng-repeat="product in products" class="col-md-6"> 
                <div class="thumbnail"> 
                    <img ng-src="{{ product.cover }}"> 
                    <p class="title">{{ product.name }}</p> 
                    <p class="price">{{ product.price | currency }}</p> 
                    <p class="date">{{ product.pubdate | date }}</p> 
                    <div class="rating">
                        <p class="likes" ng-click="plusOne($index)">+ {{ product.likes }} </p>
                    </div>
                </div> 
                </div>

      </div>
    </div>

    <div class="footer">
      <div class="container">
        <h2>Available for iPhone and Android.</h2>
        <img src="https://content.codecademy.com/projects/shutterbugg/app-store.png" width="120px" />
        <img src="https://content.codecademy.com/projects/shutterbugg/google-play.png" width="110px" />
      </div>
    </div>


    <!-- Modules -->
    <script src="js/Untitled-1.js"></script>

    <!-- Controllers -->
    <script src="js/index-liked-MainController.js"></script>
    <!--Styles-->
    <style src='html, body {.css'></style>
  </body>
</html>

I also want to post CSS and Angular if there are some wrongs:

Untitled-1.js

  $scope.title = 'This Month's Bestsellers'; 
  $scope.promo = 'The most popular books this month.';
  $scope.products = [
    { 
        name: 'The Book of Trees', 
        price: 19, 
        pubdate: new Date('2014', '03', '08'), 
        cover: 'img/the-book-of-trees.jpg',
        likes: 0,
      dislikes: 0
    }, 
    { 
        name: 'Program or be Programmed', 
        price: 8, 
        pubdate: new Date('2013', '08', '01'), 
        cover: 'img/program-or-be-programmed.jpg',
        likes: 0 ,
      dislikes: 0
    }, 
    { 
        name: 'Harry Potter & The Prisoner of Azkaban', 
        price: 11.99, 
        pubdate: new Date('1999', '07', '08'), 
        cover: 'http://upload.wikimedia.org/wikipedia/en/b/b4/Harry_Potter_and_the_Prisoner_of_Azkaban_(US_cover).jpg',
        likes: 0 ,
      dislikes: 0
    }, 
    { 
        name: 'Ready Player One', 
        price: 7.99, 
        pubdate: new Date('2011', '08', '16'), 
        cover: 'http://upload.wikimedia.org/wikipedia/en/a/a4/Ready_Player_One_cover.jpg',
        likes: 0 ,
      dislikes: 0
    }
  ];
  $scope.plusOne = function(index) { 
    $scope.products[index].likes += 1; 
  };
  
}]);

index-linked-MainController.js

var app = angular.module("myApp", []);

html-body{.css

  margin: 0;
  padding: 0;
  font-family: 'Roboto', sans-serif;
  width:100%;
 }
 
 .header {
  padding: 15px;
 }
 
 .header img {
    display: inline-block;
 }
 
 .header h1 {
    display: inline-block;
 }
 
 .main {
  background-color: #f2f2f2 ;
  padding: 40px 0;
 }
 
 .main h1 {
  color: #F65A5B ;
  font-size: 64px;
  margin: 0 0 80px 0;
  padding: 20px 0;
    line-height: 60px;
    width: 50%;
 }
 
 .main h2 {
  background-color: #DDDDDD ;
  color: #999999 ;
  font-size: 20px;
  margin: 0 0 40px 0;
  padding: 20px 0;
 }
 
 .thumbnail {
  border: 0px;
  position: relative;
  padding: 50px;
    border-radius: 0;
    margin-bottom:50px;
 }
 
 .thumbnail img {
    margin-top: 10px;
  margin-bottom: 30px;
  max-width: 100%;
 }
 
 .title,
 .date {
  color: #444;
  margin: 0;
  font-size: 18px;
    font-weight: 800;
 }
 
 .date {
    color: #a3a3a3 ;
    font-size: 14px;
    font-weight: 200;
 }
 
 .price {
  background-color: #39D1B4 ;
  color: #fff;
  font-size: 18px;
    border-radius: 50%;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    font-weight: 200;
    height: 80px;
    line-height: 80px;
    text-align: center;
    width: 80px;
  position: absolute;
  top: -40px;
  right: 20px;
 }
 
 .rating {
  text-align: right;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
  margin: 30px 0 -30px 20px;
 }
 
 .likes,
 .dislikes {
    background: #F65A5B ;
  color: #fff;
  cursor: pointer;
  display: inline-block;
  font-size: 15px;
    line-height: 40px;
    min-width: 40px;
    height: 40px;
    border-radius: 50%;
  margin: 0 -30px 0 40px;
    text-align: center;
    font-weight: 200;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    transition: background 500ms;
 }
 
 .likes:hover,
 .dislikes:hover {
  color: #F65A5B ;
    background: rgba(246, 90, 91, 0.25);
    transition: background 500ms;
 }
 
 .footer {
  text-align: center;
  margin: 80px 0 110px;
 }
 
 .footer h2 {
  font-size: 24px;
  margin-bottom: 25px;
 }
 
 .footer img {
    margin: 0 10px;
 }

Can spread operator replace an object with same uuid?

I was trying to replace a property of an Object in an array with the spread syntax like this:

const origArray = [
  {
    "uuid":"c752cf08-d142-42f8-b9df-b1e6c4e1fba6",
    "name":"Team 1",
    "players":[
      "41ed7b28-5a52-48a3-8587-1355b40fc81f"
    ]
  },
  {
    "uuid":"d46829db-f2c6-44a3-bd59-e18e2740c069",
    "name":"Team 2",
    "players":[
    ]
  }
]

const doesNotWork = (prev) => [...prev, {...prev[match], name: e.target.value}]

const result1 = doesNotWork(origArray)

console.log(result1)

// # I know this works:

const doesWork = (prev) => {
  let old = [...prev]
  old.splice(match, 1, {...prev[match], name: e.target.value});
  return old;
})

const result2 = doesNotWork(origArray)

console.log(result2)

I expect reslut1 to be like result2, but i seem to be wrong. I would like to write this in a singe line function and not with the workaround I have, if possible.

As you can see, i have found a work around, but just to make sure I fully understand the problem, it is not replacing the object because its assuming its a different one, right?

Office JS Dialog – How to get back/keep context with Excel

I’m messing around w/ Office Dialog for Add-Ins in JS. I’ve got it so far where I can open a dialog, capture input to console, run a function from a button and close the dialog box, but I can’t seem to get my function to interact with Excel. It’s lost context I beleive, I tried using this and I get no errors, but it doesn’t work –> var context = new Excel.RequestContext().

Here is my open function and my main function and the end function.

main.js

export async function helloworld(event) {
    try {
        await Excel.run(async (context) => {
            //Start Func
            console.log("BEFORE OPEN UI");
            openDialog("/yo/dist/dialog.html", 30, 20);
            console.log("AFTER OPEN UI");
            await context.sync()
                .then(function () {
                    console.log("AFTER SYNC UI");
                    var ws = context.workbook.worksheets.getActiveWorksheet();
                    var range = ws.getRange("A1:D5");
                    range.select();
                })
            //End Func
            await context.sync();
        });
    } catch (error) {
        console.error(error);
    }
    console.log("EVENT COMPLETEED HELLOW");
    //event.completed();
}

open.js

function openDialog(RelURLStr, H, W) {
    Office.context.ui.displayDialogAsync(window.location.origin + RelURLStr,
        { height: H, width: W }, dialogCallback);
}

run func //this gets ran, but nothing output to worksheet and no errors.

function dobuttonrun() {
    console.log("ENDING");
    var context = new Excel.RequestContext()
    var ws = context.workbook.worksheets.getActiveWorksheet();
    var fakedatarng = ws.getRange("A1");
    fakedatarng.values = "TEST";
}

document.addEventListener blocking highlight in textarea

I did a div that is moveable but unfortunetaly the function that let user move the div also block the highlight of the text in the text area behind.

I would like to keep the possibility to move the div and to highlight the text in textarea like I want.

Ps: I already tried to put the addEventListener on varMoveButtonNotesWindow but it’s really ncomfortable to use it like that (we need to keep the cursor in the little box, and I dont want the box to be bigger it wouldn’t look good).

Here’s the code:

var mousePosition;
var offset = [0,0];
var isDown = false;
var varMoveButtonNotesWindow = document.getElementById('moveButtonNotesWindow');
var varNotesWindow = document.getElementById('notesWindow');

varMoveButtonNotesWindow.addEventListener('mousedown', function(e) {
    isDown = true;
    offset = [
        varNotesWindow.offsetLeft - e.clientX,
        varNotesWindow.offsetTop - e.clientY
    ];
}, true);

document.addEventListener('mouseup', function() {
    isDown = false;
}, true);

//The bug occurs here
document.addEventListener('mousemove', function(event) { 
    event.preventDefault();
    if (isDown) {
        mousePosition = {
    
            x : event.clientX,
            y : event.clientY
    
        };
        varNotesWindow.style.left = (mousePosition.x + offset[0]) + 'px';
        varNotesWindow.style.top  = (mousePosition.y + offset[1]) + 'px';
    }
}, true); 
//so far


function closeNotesWindow() {
  varNotesWindow.classList.remove('show');
}

function openNotesWindow() {
  windowsModalContainer.classList.remove('show');
  varNotesWindow.classList.add('show');
};
.firstTextarea {
  height: 300px;
  width: 300px;
}

#notesWindow {
  display: block;
  position: absolute;
  width: 300px;
  height: 275px;
  top: 0px;
  left: 0px;
  border: 2px solid #313131;
  z-index: 2;
  resize: both;
  overflow: auto;
}

#headerNotesWindow {
  height: 35px;
  background-color: black;
}


#moveButtonNotesWindow {
  position: absolute;
  background-color: blue;
  color: white;
  width: 20px;
  height: 20px;
  right: 5px;
  z-index: 1;
  top: 7.5px;
}

#closeButtonNotesWindow {
  position: absolute;
  background-color: red;
  color: white;
  width: 20px;
  height: 20px;
  right: 30px;
  z-index: 1;
  top: 7.5px;
}

#divTextareaNotesWindow {
  text-align: center;
  height: calc(100% - 6px - 35px);
}

#textareaNotesWindow {
  resize: none;
  width: calc(100% - 6px);
  height: 100%;
  outline: none;
}
<textarea class="firstTextarea">Pokemon is the best game of my childhood.</textarea>

<div class="divWindow" id="notesWindow">
    <div id="headerNotesWindow">
      <div id="moveButtonNotesWindow"></div>
      <div id="closeButtonNotesWindow" onclick="closeNotesWindow()"></div>
    </div>
  
    <div id="divTextareaNotesWindow">
      <textarea id="textareaNotesWindow"></textarea>
    </div>
  </div>

Mongoose 3 to 6 and modelSchemas

I’m working on migrating an old project from mongoose 3 to 6 and can’t seem to find anything in the change docs about modelSchemas and how they’ve been superseded.. In some unit tests, I have this v3 code;

function clearModels(models) {
  models.forEach(model => {
    delete mongoose.models[model];
    delete mongoose.modelSchemas[model];
  });
}

This of course fails because mongoose.modelSchemas no longer exists — so the question is, how do I re-write this in a v6 compatible way?