trying to return something in coding

ok here is my code
public class Password_Verifier {

private static String password;


private static int num1=0;
private static int num2=0;
private static int num3=0;












public Password_Verifier(String string) {
    // TODO Auto-generated constructor stub
}






public static  void main(String[] args) {
    

    String output = "";
    
    
            
    for (int i = 0; i < password.length(); i++){
        
        
        if (Character.isUpperCase(password.charAt(i)))
            {
            num1++;
            }
        
        if(Character.isLowerCase(password.charAt(i))) 
            {
            num2++;
            }
        
        if(Character.isDigit(password.charAt(i)))
            {
            num3++;
            }
    }
        
        
    

    
    
    if (password.length()<6) 
    {
        
        output = output + "nThe password should be at least six characters long";
    }


    if (num1 < 1) 
    {
        
        output = output + "nThe password should contain at least one uppercase letter";
    }
    
    if (num2 < 1) 
    {
        
        output = output + "nThe password should contain at least one lowercase letter";
    }
    

    if (num3 < 1) 
    {
        
        output = output + "nThe password should have at least one digit";
    }
    
    if(password.length()>=6 && num1 > 1 && num2 > 1 && num3 > 1 )
    {
        
        
        
        output = "Password Accepted";
    }
    
     


    
    

 




}



    

}

here is the password input

import java.util.Scanner;

public class Password_Input {

public static void main(String[] args) {
     
     
     Scanner Kb = new Scanner(System.in);
        
     

     
       
        // put in password to test it
        System.out.print("Please enter your password: ");
        
        String password =Kb.nextLine(); 
        
        boolean valid = false; 
        
        
        
        
        
        for (int i = 0; i < password.length(); i++){
           char c = password.charAt(i);

           
           
           do
           {
           if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9')) 
           {

               valid = true;
           } 

           else
            {
                    valid = false;
            
               System.out.print("Only letter or digits are acceptable. Please try again: ");
               
               password = Kb.nextLine();
              } 
            }while(valid =! true);
            }
        
            
        String password1;
        Password_Verifier password_Verifier = new Password_Verifier(
                
                password1 = password
                
                );


        System.out.println(password_Verifier);


     
}

}

now the problem i am having is trying to get output to print i already have the code for the input password but i get gibberish my idea was trying to call out output from the main method and having it return does anyone have any good ideas what i want is for my code to return out put to my input part of the code

show only the message of error object in fetch api javascript

I want to log the error message in the console. Everything is working fine expect that I could not log only the message for eg if the email already exist it should log “email exists”

const submitHandler = async(event) => {
    event.preventDefault();
    const enteredEmail = emailInputRef.current.value;
    const enteredPassword = passwordInputRef.current.value;
    try {
      if (isLogin) {
           //do something
      } 
      
      else {
        setstate("sending request")
        const response = await fetch(
          "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyB9epljL9fTX6GhIFodJAIjI89cSFFFElM",
          {
            method: "POST",
            body: JSON.stringify({
              email: enteredEmail,
              password: enteredPassword,
              returnSecureToken: true,
            }),
            headers: {
              "Content-Type": "application/json",
            },
          }
          )
        if(response.ok){
          alert("User added successfully")  
        }
        else{
          const data = await response.json()
          console.log(data);
          throw new Error(data);
        }
        setstate("Create new account")
      }
      
    } catch (error) {
      console.log(error.message);
    }
  };

Is it faster to read a signature or to decrypt a string when using tokens for authentication?

I’m new to everything related to authentication and have no knowledge about encryption algorithms. I was reading about JWT, but from what I gathered, it’d make more sense for my project to authenticate users using either one of these 2 strategies:

  1. Sign with the server’s private key a publicly readable JSON, such as:
const token = {
  "user": "johndoe",
  "iat": 4342342352,
  "exp": 4352234322
}
  1. Or encrypt that JSON content and only allow the server to decrypt it
E.g.: 
// server sets token
encryptionLibrary.encrypt(token, "AES-256", "server's super password")
// then decrypts it when there's a HTTP request
encryptionLibrary.decrypt(token, "AES-256", "server's super password")

Question: Would checking the signature only be faster than decrypting the whole string or is it absolutely dependable on the implementation? (i.e., using a fast/slow library).


Why not simply use JWT instead? Looks like too much bloat for my project, I just need a way of storing on the client’s end a JSON with user, iat and exp information and letting the server prove it’s legit. Signing or encrypting the whole payload should stop attackers from creating false tokens, I think

AddFavourites Component in my React app is not iterable

I am really new to React js and I am working on a basic movie app. I have an ‘Addfavourites’ component which adds a movie to favourites when clicked.

import React from "react";

import React from "react";

const AddFavourite = () => {
    return (
        <>
            <span className="mr-2">Add To Favourites</span>
            <svg 
                xmlns="http://www.w3.org/2000/svg" 
                width="16" height="16" 
                fill="red" 
                className="bi bi-heart-fill" 
                viewBox="0 0 16 16"
            >
                <path 
                    fill-rule="evenodd"
                    d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z"
                />
            </svg>
        </>
    )

}



export default AddFavourite

However, when I try to add, I get an error message:
Uncaught TypeError: Favourites is not iterable.

I know what I should do but don’t just know how I should do it. Please help.

I’m trying to make a wordle clone, but for some reason my congratulations message isn’t displayed when the user gets the word right. How can I fix it?

let body = document.querySelector("body")
let container = document.querySelector("#container")
let enter = document.querySelector("#enter")
let restart = document.querySelector("#restart")





  let inputArr = []


 for (let rowCount = 0; rowCount < 6; rowCount++) {
  let row = []
   inputArr.push(row)
   for (let column = 0; column < 5; column++) {
     
     let space = document.createElement("input")
    space.classList.add("square")
     container.appendChild(space)
     row.push(space)
     
   
   }
   
 }

function wordle() {

  let wordSet = ["panic", "dupes", "crate", "great", "soare", "avoid", "knobs", "venom"]

  let correct = []
  let enteredLetters = []

  let num = Math.floor(Math.random()*wordSet.length)
  let word = wordSet[num]
  console.log(word)

let enterClicks = -1

enter.addEventListener("click", () => {

  enterClicks++
  for (let rowVal = 0; rowVal < 6; rowVal++) {
    for (let col = 0; col<5; col++) {

      let square = inputArr[rowVal][col] 
      let current = square.value

      

      if (current == word[col]) {
        square.style.backgroundColor = "green"
        correct.push(current)
        
      }

      


      if (current !== word[col] && word.indexOf(current) !== -1) {
        square.style.backgroundColor = "yellow"
      }

      if (current == "") {
        current.disabled = false
        for (let z = 0; z < 5; z++) {
          inputArr[rowVal][z].style.backgroundColor = "white"
        }
      }

    

      if (current !== word[col] && word.indexOf(current) == -1) {
        square.style.backgroundColor = "darkgray"
      }
    }
  }

    for (let c = 0; c < 6; c++) {

       inputArr[enterClicks][c].disabled = true
      enteredLetters.push(inputArr[enterClicks][c].value)
      

      
    }

  let foundLetters = []

  for (let w = 0; w < 5; w++) {
    if (correct.indexOf(word[w]) !== -1) {
      foundLetters.push(word[w])
    }
  }

  if (foundLetters.length == 5) {
    window.alert("Congratulations! You Beat Wordle 2.0! Click the 'PLAY AGAIN' button to start a new round.")
  }



  


   
  

})

}

wordle()

restart.onclick = () => {
  location.reload()
}

By the way, the foundLetters array basically stores the characters that match in both the word and the correct array. Everything else seems to be working perfectly fine, but it’s just the last bit of code, starting at the declaration of foundLetters until the end, that doesn’t seem to work as it should.

How to disable shipping address validation on Magento Checkout page via a Vertex validator

Magento 2.4 PHP 7.4

It appears that the shipping address is being validated on toggle of shipping method as can be seen in the screenshot below. As I consoled out the event that is triggered on selection of shipping method I see that it points to a vertex shipping address validator – vendorvertexincmodule-address-validationviewfrontendwebjsviewcheckoutshippingaddress-validation.js

I removed the shipping address validation from vendorvertexincmodule-address-validationviewfrontendlayoutcheckout_index_index.xml but that didn’t work

Following is the code for address-validation.js –

/**
 * @copyright  Vertex. All rights reserved.  https://www.vertexinc.com/
 * @author     Mediotype                     https://www.mediotype.com/
 */

define([
    'jquery',
    'uiRegistry',
    'uiComponent',
    'Vertex_AddressValidation/js/action/address-validation-request',
    'Vertex_AddressValidation/js/model/checkout/shipping/address-resolver',
    'Magento_Checkout/js/model/full-screen-loader',
    'Magento_Checkout/js/checkout-data',
    'Magento_Checkout/js/model/error-processor',
    'Magento_Ui/js/model/messageList',
    'Vertex_AddressValidation/js/validation-messages',
    'Vertex_AddressValidation/js/action/convert-quote-address',
    'Vertex_AddressValidation/js/action/build-quote-address',
    'Vertex_AddressValidation/js/model/difference-determiner'
], function (
    $,
    registry,
    Component,
    addressValidationRequest,
    addressResolver,
    fullScreenLoader,
    checkoutData,
    errorProcessor,
    messageContainer,
    validationMessages,
    convertQuoteAddress,
    buildQuoteAddress,
    differenceDeterminer
) {
    'use strict';

    return Component.extend({
        validationConfig: window.checkoutConfig.vertexAddressValidationConfig || {},
        resolver: addressResolver,
        isAddressValid: false,
        message: null,
        defaults: {
            listens: {
                addressData: 'addressUpdated'
            },
            imports: {
                addressData: '${ $.provider }:shippingAddress'
            }
        },

        /**
         * Reset validation after address update
         */
        addressUpdated: function () {
            this.isAddressValid = false;
            this.updateAddress = false;
            console.log("trigger address updated");

            if (this.message) {
                this.message.clear();
                this.message.showSuccessMessage = false;
            }
        },

        /**
         * @returns {Object}
         */
        initialize: function () {
            this._super();
            this.message = registry.get(this.parentName);
            console.log(this.parentName + "parent name");

            return this;
        },

        /**
         * @returns {Object}
         */
        getFormData: function () {
            const formData = checkoutData.getShippingAddressFromData(),
                checkoutProvider = registry.get('checkoutProvider');

            // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
            // jscs:disable requireMultipleVarDecl
            if (checkoutProvider && checkoutProvider.dictionaries && checkoutProvider.dictionaries.region_id) {
                const region = registry.get('checkoutProvider').dictionaries.region_id.find(function (obj) {
                    return obj.value === formData.region_id;
                });

                if (region && region.label) {
                    formData.region = region.label;
                }
            }
            // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
            // jscs:enable requireMultipleVarDecl

            return formData;
        },

        /**
         * Triggers a request to the address validation builder and adds the response
         */
        addressValidation: function () {
            const deferred = $.Deferred();
            this.isAddressValid = false;
            fullScreenLoader.startLoader();

            addressValidationRequest(convertQuoteAddress(this.getFormData()))
                .done(function (response) {
                    this.isAddressValid = true;
                    console.log(response + "response");

                    if (this.handleAddressDifferenceResponse(response) === true) {
                        deferred.resolve();
                    }
                }.bind(this)).fail(function (response) {
                errorProcessor.process(response, messageContainer);
                console.log(response + "response");
            }).always(function () {
                fullScreenLoader.stopLoader();
            });

            return deferred;
        },

        /**
         * Get the message with the differences
         *
         * @param {?CleanAddress} response
         */
        handleAddressDifferenceResponse: function (response) {
            if (response === null || !Object.keys(response).length) {
                this.message.setWarningMessage(validationMessages.noAddressFound);

                return;
            }

            this.resolver.responseAddressData = buildQuoteAddress(response);

            const differences = differenceDeterminer(convertQuoteAddress(this.getFormData()), response),
                showSuccessMessage = this.validationConfig.showValidationSuccessMessage || false;

            if (differences.length === 0 && showSuccessMessage) {
                this.message.setSuccessMessage(validationMessages.noChangesNecessary);
            } else if (differences.length > 0) {
                this.message.setWarningMessage(validationMessages.changesFound, differences, response);
            } else {
                return true;
            }
        },

        /**
         * Get the update message
         */
        updateVertexAddress: function () {
            this.resolver.resolveAddressUpdate();

            this.message.setSuccessMessage(validationMessages.addressUpdated);
            this.isAddressValid = true;
        }
    });
});

Shipping address validation UI

Make javascript function wait until element class has changed before completing

I have a checkbox on my site that, when clicked, stores whether or not a user checked the box in the WordPress user table. When the “checked” value is stored in the user table, the box background changes to the image of a check. However, since the process of storing this info in the user table takes ~3 seconds, I want to create a javascript function that immediately gives the user an indication that the box was clicked (instead of waiting for the check to appear). The < a > link that initiates this data transfer is located inside a div with the class “checkbox”. General HTML layout:

<div class="checkbox">
  <a href="" class="wpc-button-complete wpc-complete">
  </a>
</div>

Right now I have a javascript function that changes the background color of the “checkbox” div on click, but just has a timeout that lasts long enough to cover the ~3 seconds of time for the data to be transferred and the check to appear:

document.querySelector('.checkbox').addEventListener('click', function (clicked) {
    return function () {
        if (!clicked) {
            this.style.backgroundColor = '#ce6480';
            clicked = true;
            setTimeout(function () {
                this.style.backgroundColor = '#f7f7f7';
                clicked = false;
            }.bind(this), 2500);
        }
    };
}(false), this);

The WP plugin that makes this data transfer possible changes the class of the checkbox < a > element from “wpc-button-complete wpc-complete” to “wpc-button-completed wpc-completed” when the “checked” value is stored in the user table and shows as such on the front end with the checkmark being present. I would rather have this function be so that the background color changes to “#ce6480” on click and then once the class of this element changes, the “#ce6480” background color goes away at the same time so the change in background color is only present during the short window between when the user clicks and when the check appears. Is there any way instead of the setTimeout function, I could just tell the function to wait for the class of the < a > element to change and then remove the changed background color?

Thanks.

Adding more than one ternary operators to a span in React

I currently have this code on a span in React:

<span

    style={
      Price > cinemaWorldPrice ? { color: "green" } : { color: "red" }
    }
  >
    {Number(cinemaWorldPrice).toFixed(2)}
  </span>

But I would like to add another ternary operator stating something like :

if (cinemaWorld === NaN){
cinemaWorld = "Please refresh the page"}

and have that display. If cinemaWorld is a number then proceed with the:

{
              Price > cinemaWorldPrice ? { color: "green" } : { color: "red" }
            }

Display/ Hide Markers on Video based on current time Javascript

I am trying to implement a function that displays/ hides markers (could be subtitles, highlighted area) based on “timeUpdate” event which tracks current time.

My content source has multiple tracks. Based on current time, one or more tracks containing marker objects may be shown or hidden.

Here’s the starter code

player.on('timeUpdate', function(event) {

    // currentTime (seconds, float)

    // your algorithm will be called here with the currentTime as the argument

});



// tracks = [

   [annotation1, annotation2, annotationN...],

   [annotation1, annotation2, annotationN...], ...

]

// annotations, each looks like:

{

    "startTime": timestamp,

    "endTime": timestamp,

    "show": fn,

    "hide": fn

}

Switch statement for RegExp falling to default?

In this switch statement, why does it fail in the regex check and falls to the default case?

The regex matches when I do it as if ... else, but, it doesn’t matches when I do it as a switch statement and it falls to the default case!

let siteUrl = 'http://example.com';
let check1 = checkSite(siteUrl);
let check2 = checkSite();

function checkSite(siteUrl) {
    let url = (siteUrl) ? siteUrl : 'http://example.com';
    let regex = /^http://example.com$/gi;
    let result = {};

    if (regex.test(url)) {
        console.log('regex match!');
    } else {
        console.log('regex does NOT match!');
    }
    
    switch (true) {
        case regex.test(url) : //<-- Why this doesn't match?
            console.log('case 1'); 
            result.case = 1;
            break;
            
        case /another-regex/.test(url) :
            console.log('case 2');
            result.case = 2;
            break;
                        
        default : //<-- Why do I get here?
            console.log('default');
            result.case = 3;
    }
    console.log(result);
    return result;
}

I do not want to show all the default option list on click the datalist input box

On click the input field, I do not want to display or show all the options or list. I just want to display while inputting some text only.

 <!DOCTYPE html>
     <html>
     <body>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
     <label for="browser">Choose your country:</label>
     <input list="browsers" name="browser" id="browser">
     <datalist id="browsers">
      <option value="Australia">
       <option value="USA">
       <option value="Inda">
       <option value="Bhutan">
       <option value="Thailand">
       <option value="Canada">
       <option value="Japan">
       <option value="China">
       <option value="France">
       </datalist>
       </body>
       </html>

For Loops and Set Intervals. I am trying to create a quiz with forward, backward, and loop features

Noobie here. I am trying to create a simple quiz. Starting the quiz would execute a function that runs a question array AND start a timer. The current and total count would be visible. The timer would countdown from 10. Once it hits 0, the next item in the array would run.

I created an earlier code (not shown here) that worked well enough, but I broke it when I tried adding a loop question feature (keep array count while repeating countdown). I tried recreating the code, but now it won’t work after the first item:

Any ideas?

Question: <div id="interview_questions"></div>
Timer: <div id="countdown"></div>
Current count question: <div id="questions_count"></div>
Total count questions: <div id="questions_total"></div>
<button onclick="start_interview()">start interview</button>

<script>
    // Questions
    var questions = ["Why do you want to work here?",
                      "Why are you a good fit?",
                      "What are your strengths?"
    ];

    // Givens
    let questions_total = questions.length;
    let questions_count = 0;

    function start_interview() {
        document.getElementById("questions_total").innerHTML = questions_total;
        let question_count = 1;
        for (let questions_count = 0; questions_count < questions_total; questions_count++) {
            // Show questions
            timer();
            console.log(questions[questions_count]);
            //questions_count++;
            // console.log(questions_count);
        }
    }

    // Timer
    function timer() {
        let timer = 10;
        if (timer > 0) {
            let question_timer = setInterval(function() {
                if (timer === 0) {
                    clearInterval(question_timer);
                }
                document.getElementById("interview_questions").innerHTML = questions[questions_count];
                document.getElementById("questions_count").innerHTML = questions_count;
                document.getElementById("countdown").innerHTML = timer;
                timer--;
                
                console.log(timer);
                console.log(questions_count);
                
            }, 1000);
        } else {
            questions_count++;
            start_interview();
        }
    }
</script>

How do you load scripts to pass Content Security Policy directive: default-src ‘none’?

I have a React+Node.js app that works fine on localhost but runs into errors when deployed to Heroku, resulting in a 404 response status.

These are the console errors I get when loading the app on Chrome:

Refused to load the script 'https://ssl.google-analytics.com/ga.js' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'script-src-elem' was not explicitly set, so 'default-src' is used as a fallback.
(anonymous) @ 1:3

Refused to load the script 'https://www.pagespeed-mod.com/v1/taas?id=cs&ak=55c85bbdd6e4d21e7278fbbbb89a9502&si=fb4741a02e044f61940836e20590e7f6&tag=1005&rand=7e511f5336f16d2e87e9ac560e754a19&ord=7220108846457940' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'script-src-elem' was not explicitly set, so 'default-src' is used as a fallback.
(anonymous) @ 1:3

myapp.herokuapp.com/:1 Refused to load the stylesheet 'https://fonts.googleapis.com/css?family=Lato:300,400,700,900' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'style-src-elem' was not explicitly set, so 'default-src' is used as a fallback.

DevTools failed to load source map: Could not load content for chrome-extension://mihdfbecejheednfigjpdacgeilhlmnf/react-draggable.js.map: System error: net::ERR_BLOCKED_BY_CLIENT
myapp.herokuapp.com/:1  (warning)       

Failed to load resource: the server responded with a status of 404 (Not Found)

I have tried adding fixes for script-src and style-src in public/index.html, public/manifest.json, src/server/index.js, and App.js, but I always see the same errors.

Frontend attempted fix:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src-elem 'self' 'unsafe-inline' https://ssl.google-analytics.com https://www.pagespeed-mod.com; style-src-elem 'self' 'unsafe-inline' https://fonts.googleapis.com; object-src 'self'" />

Backend attempted fix:

const helmet = require("helmet")
...
app.use(
  helmet({
    contentSecurityPolicy: false,
  })
)

Python requests-html render() has no href link URL

I’d like to search on Paravi(https://www.paravi.jp/search) with a movie title and get a link to the movie. My current code is below.

from bs4 import BeautifulSoup
from requests_html import HTMLSession

title = 'invisible'
url = f'https://www.paravi.jp/search?q={title}'
session = HTMLSession()
res = session.get(url)
res.html.render(sleep=10)
soup = BeautifulSoup(res.html.html, 'html.parser')
print(soup)

It contains something like this, but it doesn’t contain an ‘a’ tag or href link.

<div aria-label='w-inds. LIVE TOUR 2017 "INVISIBLE"' class="sliderRefocus lockup" id="title-card-0-0" role="link" tabindex="0">
  <div class="ptrack-content" data-ui-tracking-context="">
    <div class="artwork" style='background-image: url("https://img.paravi.jp/files/88c22fdf228d4ee0baf33171fff70aba/95671030163.jpg?w=800&amp;h=800&amp;p=t");'></div>
    <div class="video-preload-title">
      <div class="video-preload-title-label">w-inds. LIVE TOUR 2017 "INVISIBLE"</div>
    </div>
  </div>
</div>

<div class="text-wrapper hasTextArea">
  <h3 class="title-card-title">
    <p class="link">w-inds. LIVE TOUR 2017 "INVISIBLE"</p>
  </h3>
  <div class="synopsis">アルバム...</div>
</div>

I am new to javascript and html.
From where can I get the link?

Found reverse numbers with javascript

I need help to resolve a problem with javascript, heres the thing:

Some positive integers n have a property in which the sum of n + reverse(n) results in odd numbers. For example, 36 + 63 = 99 and 409 + 904 = 1313. Assume that n or reverse(n) cannot start with 0.

There are 120 reversible numbers below 1000.

Build an algorithm that displays all n numbers on the screen where the sum of n + reverse(n) results in odd numbers that are below 1 million.

I am struggling, how can i found the 120 reversible numbers below 1000?

I am using some udemy courses to help-me but i am stucked really hard on that.