问:
Dependency error when install ggplot in R
When I try to install ggplot with this code

```<code>install.packages("png")
install.packages("RgoogleMaps")
install.packages("ggmap")
library(ggmap)
</code>```

It returns error

```<code>installing to /usr/local/Cellar/r/4.2.2/lib/R/library/00LOCK-png/00new/png/libs
** R
** inst
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded from temporary location
Error: package or namespace load failed for ‘png’ in dyn.load(file, DLLpath = DLLpath, ...):
 unable to load shared object '/usr/local/Cellar/r/4.2.2/lib/R/library/00LOCK-png/00new/png/libs/png.so':
  dlopen(/usr/local/Cellar/r/4.2.2/lib/R/library/00LOCK-png/00new/png/libs/png.so, 6): Library not loaded: @rpath/libz.1.dylib
  Referenced from: /usr/local/Cellar/r/4.2.2/lib/R/library/00LOCK-png/00new/png/libs/png.so
  Reason: image not found
Error: loading failed
Execution halted
ERROR: loading failed
* removing ‘/usr/local/Cellar/r/4.2.2/lib/R/library/png’
Warning in install.packages :
  installation of package ‘png’ had non-zero exit status
ERROR: dependency ‘png’ is not available for package ‘RgoogleMaps’
* removing ‘/usr/local/Cellar/r/4.2.2/lib/R/library/RgoogleMaps’
Warning in install.packages :
  installation of package ‘RgoogleMaps’ had non-zero exit status
ERROR: dependencies ‘RgoogleMaps’, ‘png’ are not available for package ‘ggmap’
* removing ‘/usr/local/Cellar/r/4.2.2/lib/R/library/ggmap’
Warning in install.packages :
  installation of package ‘ggmap’ had non-zero exit status

The downloaded source packages are in
    ‘/private/var/folders/fd/7vyffy191_l3j6fhyqbvsn0r0000gn/T/RtmptKSXHF/downloaded_packages’
Updating HTML index of packages in '.Library'
Making 'packages.html' ... done
Error in library(ggmap) : there is no package called ‘ggmap’

</code>```

I am installing all the dependencies that the error says are missing. By adding the install packages before installing the ggmap itself.

Body:
When I try to install ggplot with this code

install.packages("png")
install.packages("RgoogleMaps")
install.packages("ggmap")
library(ggmap)

It returns error

installing to /usr/local/Cellar/r/4.2.2/lib/R/library/00LOCK-png/00new/png/libs
** R
** inst
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded from temporary location
Error: package or namespace load failed for ‘png’ in dyn.load(file, DLLpath = DLLpath, ...):
 unable to load shared object '/usr/local/Cellar/r/4.2.2/lib/R/library/00LOCK-png/00new/png/libs/png.so':
  dlopen(/usr/local/Cellar/r/4.2.2/lib/R/library/00LOCK-png/00new/png/libs/png.so, 6): Library not loaded: @rpath/libz.1.dylib
  Referenced from: /usr/local/Cellar/r/4.2.2/lib/R/library/00LOCK-png/00new/png/libs/png.so
  Reason: image not found
Error: loading failed
Execution halted
ERROR: loading failed
* removing ‘/usr/local/Cellar/r/4.2.2/lib/R/library/png’
Warning in install.packages :
  installation of package ‘png’ had non-zero exit status
ERROR: dependency ‘png’ is not available for package ‘RgoogleMaps’
* removing ‘/usr/local/Cellar/r/4.2.2/lib/R/library/RgoogleMaps’
Warning in install.packages :
  installation of package ‘RgoogleMaps’ had non-zero exit status
ERROR: dependencies ‘RgoogleMaps’, ‘png’ are not available for package ‘ggmap’
* removing ‘/usr/local/Cellar/r/4.2.2/lib/R/library/ggmap’
Warning in install.packages :
  installation of package ‘ggmap’ had non-zero exit status

The downloaded source packages are in
    ‘/private/var/folders/fd/7vyffy191_l3j6fhyqbvsn0r0000gn/T/RtmptKSXHF/downloaded_packages’
Updating HTML index of packages in '.Library'
Making 'packages.html' ... done
Error in library(ggmap) : there is no package called ‘ggmap’

I am installing all the dependencies that the error says are missing. By adding the install packages before installing the ggmap itself.


来源: stackexchange

问:
Is there a way to tell when SpeechRecognizer.cancel() processing has completed successfully?
Once SpeechRecognizer.cancel() is invoked, is there a way to tell that it has been completely processed, to the point of not interpreting any sound an microphone and not invoking any of its ReognitionListener callbacks?

More specifically, when SpeechRecognizer.cancel() is invoked, all it does is place a MSG_CANCEL in the main thread's queue:

```<code>@MainThread
public void cancel() {
    checkIsCalledFromMainThread();
    putMessage(Message.obtain(mHandler, MSG_CANCEL));
}
</code>```

Then, at some point (no immediacy guarantee), the message is handled:

```<code>private Handler mHandler = new Handler(Looper.getMainLooper()) {

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_START:
                handleStartListening((Intent) msg.obj);
                break;
            case MSG_STOP:
                handleStopMessage();
                break;
            case MSG_CANCEL:
                handleCancelMessage();
                break;
</code>```

by further relaying it to the IRecognitionService service:

```<code>private void handleCancelMessage() {
    if (!checkOpenConnection()) {
        return;
    }
    try {
        mService.cancel(mListener, /*isShutdown*/ false);
        if (DBG) Log.d(TAG, "service cancel command succeeded");
    } catch (final RemoteException e) {
        Log.e(TAG, "cancel() failed", e);
        mListener.onError(ERROR_CLIENT);
    }
}
</code>```

But I have not been able to find any callback or listener that notifies the app when the IRecognitionService has completed successfully.

Any idea for a way to tell when SpeechRecognizer.cancel() processing has completed successfully?

ContentLicense: CC BY-SA 4.0

Body:
Once SpeechRecognizer.cancel() is invoked, is there a way to tell that it has been completely processed, to the point of not interpreting any sound an microphone and not invoking any of its ReognitionListener callbacks?

More specifically, when SpeechRecognizer.cancel() is invoked, all it does is place a MSG_CANCEL in the main thread's queue:

@MainThread
public void cancel() {
    checkIsCalledFromMainThread();
    putMessage(Message.obtain(mHandler, MSG_CANCEL));
}

Then, at some point (no immediacy guarantee), the message is handled:

private Handler mHandler = new Handler(Looper.getMainLooper()) {

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_START:
                handleStartListening((Intent) msg.obj);
                break;
            case MSG_STOP:
                handleStopMessage();
                break;
            case MSG_CANCEL:
                handleCancelMessage();
                break;

by further relaying it to the IRecognitionService service:

private void handleCancelMessage() {
    if (!checkOpenConnection()) {
        return;
    }
    try {
        mService.cancel(mListener, /*isShutdown*/ false);
        if (DBG) Log.d(TAG, "service cancel command succeeded");
    } catch (final RemoteException e) {
        Log.e(TAG, "cancel() failed", e);
        mListener.onError(ERROR_CLIENT);
    }
}

But I have not been able to find any callback or listener that notifies the app when the IRecognitionService has completed successfully.

Any idea for a way to tell when SpeechRecognizer.cancel() processing has completed successfully?


问:
TestCafe - ReferenceError: testController is not defined displayed when running Testcafe BDD implementation
I am very new to Testcafe and was trying out the code in the below link

https://dzone.com/articles/testcafe-integration-with-cucumber

I have done it exactly as is but I am getting "ReferenceError: testController is not defined"

If someone can help me figure out this, it would be great. Thanks in advance.


问:
Designing exe with batch file running
guys,i have to design exe , Which create folder and copy files inside after it run bat file.

I'm,New to this concepti don't have idea how to do it.

Title: Designing exe with batch file running


问:
How to convert html table to doc with the same styles
I have an html table with css which looks like this:

enter image description here

I use this link to convert it to doc file:

html to word

However I get it in word file as:

enter image description here

How can I convert this table with the same style?

I tried this:

```<code>function exportHTML(){
    // continue with your code
   var header = "<html xmlns:o='urn:schemas-microsoft-com:office:office' "+
        "xmlns:w='urn:schemas-microsoft-com:office:word' "+
        "xmlns='http://www.w3.org/TR/REC-html40'>"+
        "<head><meta charset='utf-8'><title>Export HTML to Word Document with JavaScript</title></head><body>";
   var footer = "</body></html>";
   var sourceHTML = header+document.getElementById("exportContent").innerHTML+footer;

   var source = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(sourceHTML);
   var fileDownload = document.createElement("a");
   document.body.appendChild(fileDownload);
   fileDownload.href = source;
   fileDownload.download = 'document.doc';
   fileDownload.click();
   document.body.removeChild(fileDownload);
}

</code>```

and in html file:

```<code><div style="float: left; padding: 5px; width:60%;" id="exportContent">
</code>```

Body:
I have an html table with css which looks like this:

enter image description here

I use this link to convert it to doc file:

html to word

However I get it in word file as:

enter image description here

How can I convert this table with the same style?

I tried this:

function exportHTML(){
    // continue with your code
   var header = ""+
        "<meta charset='utf-8'><title>Export HTML to Word Document with JavaScript</title>";
   var footer = "";
   var sourceHTML = header+document.getElementById("exportContent").innerHTML+footer;

   var source = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(sourceHTML);
   var fileDownload = document.createElement("a");
   document.body.appendChild(fileDownload);
   fileDownload.href = source;
   fileDownload.download = 'document.doc';
   fileDownload.click();
   document.body.removeChild(fileDownload);
}

and in html file:


问:
Using Delphi API from Django-based website
I am a beginner in Django.

I have a Desktop application API (Delphi based app) in DLL format, and I am trying to build a webpage that interacts with this Desktop app. Is there any way to do that?

If the answer is No, how can I use the DLL API to interact with this app using Kivy or PyQT5 or any Python framework?

PS: I don't have any knowledge of Delphi.

I didn't try anything, I'm just wondering if my idea is doable.


问:
Why is my Spaces and actual game not printing correctly
My game almost works perfectly but for some reason my space variable wont print correctly.
Also, the game automatically asks to play again after pressing enter. My code runs fine it s just not printing what I want it to print. The only problems are with the Spaces variable and maybe somewhere in 1 of the functions.

```<code>import random

HANGMANPICS = ['''
  +---+
  |   |
      |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========''']
words={
    'Colors':'red orange yellow green blue indigo violet white black brown'.split(),
    'Shapes':'square triangle rectangle circle ellipse rhombus trapezoid chevron pentagon hexagon septagon octagon'.split(),
    'Fruits':'apple orange lemon lime pear watermelon grape grapefruit cherry banana cantaloupe mango strawberry tomato'.split(),
    'Animals':'bat bear beaver cat cougar crab deer dog donkey duck eagle fish frog goat leech lion lizard monkey moose mouse otter owl panda python rabbit rat shark sheep skunk squid tiger turkey turtle weasel whale wolf wombat zebra'.split()}
def getRandomWord(wordDict):
    # This function returns a random string from the passed dictionary of lists of strings, and the key also.
    # First, randomly select a key from the dictionary:
    wordKey = random.choice(list(wordDict.keys()))
    # Second, randomly select a word from the key's list in the dictionary:
    wordIndex = random.randint(0, len(wordDict[wordKey]) - 1)
    return [wordDict[wordKey][wordIndex], wordKey]

def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
    print(HANGMANPICS[len(missedLetters)])
    print()

    print(' Missed letters:', end=' ')
    for letter in missedLetters:
        print(letter, end=' ')
    print()

    spaces = '_' * len(secretWord)

    for i in range(len(secretWord)): # replace blanks with correctly guessed letters
        if secretWord[i] in correctLetters:
            spaces = spaces[:i] + secretWord[i] + blanks[i+1:]

    for letter in spaces: # show the secret word with spaces in between each letter
        print(letter, end=' ')
    print()

def GetdaGuess(alreadyGuessed):
    while True:
        print('Pick a letter for the Hangman Game')
        R_I = input()
        R_I = R_I.lower()
        if len(R_I) != 1:
            print('Please enter 1 letter only')
        elif R_I in alreadyGuessed:
            print('You"ve chosen that letter. Please try again')
        if R_I not in 'abcdefghijklmnopqrstuvwxyz':
            print('Only letters please')
        return R_I

def Play1MoreTime():
    guess = input('Would you like to play again?\n')
    return input().lower().startswith('y')

print('H A N G M A N ')
missedLetters = ''
correctLetters = ''
secretWords = getRandomWord(words)
gameIsDone = False

while True:
    displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWords)

    guess = GetdaGuess(missedLetters + correctLetters)

    if guess in secretWords:
        correctLetters = correctLetters + guess

    foundAllDaLetters = True
    for i in range(len(secretWords)):
        if secretWords[i] not in correctLetters:
            foundAllDaLetters = False
            break
    if foundAllDaLetters:
        print('Good job. The correct word was'+ secretWord+'. ')

    if len(missedLetters) == len(HANGMANPICS) - 1:

        print('Your out of tries.\nAfter ' + str(len(missedLetters)) + ' wrong guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')

    gameIsDone = True

    if gameIsDone:
        if  Play1MoreTime():
            missedLetters = ''
            correctLetters = ''
            gameIsdone = False
            secretWord = getRandomWord(words)
        else:
            break
</code>```

Body:
My game almost works perfectly but for some reason my space variable wont print correctly.
Also, the game automatically asks to play again after pressing enter. My code runs fine it s just not printing what I want it to print. The only problems are with the Spaces variable and maybe somewhere in 1 of the functions.

import random

HANGMANPICS = ['''
  +---+
  |   |
      |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========''']
words={
    'Colors':'red orange yellow green blue indigo violet white black brown'.split(),
    'Shapes':'square triangle rectangle circle ellipse rhombus trapezoid chevron pentagon hexagon septagon octagon'.split(),
    'Fruits':'apple orange lemon lime pear watermelon grape grapefruit cherry banana cantaloupe mango strawberry tomato'.split(),
    'Animals':'bat bear beaver cat cougar crab deer dog donkey duck eagle fish frog goat leech lion lizard monkey moose mouse otter owl panda python rabbit rat shark sheep skunk squid tiger turkey turtle weasel whale wolf wombat zebra'.split()}
def getRandomWord(wordDict):
    # This function returns a random string from the passed dictionary of lists of strings, and the key also.
    # First, randomly select a key from the dictionary:
    wordKey = random.choice(list(wordDict.keys()))
    # Second, randomly select a word from the key's list in the dictionary:
    wordIndex = random.randint(0, len(wordDict[wordKey]) - 1)
    return [wordDict[wordKey][wordIndex], wordKey]

def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
    print(HANGMANPICS[len(missedLetters)])
    print()

    print(' Missed letters:', end=' ')
    for letter in missedLetters:
        print(letter, end=' ')
    print()

    spaces = '_' * len(secretWord)

    for i in range(len(secretWord)): # replace blanks with correctly guessed letters
        if secretWord[i] in correctLetters:
            spaces = spaces[:i] + secretWord[i] + blanks[i+1:]

    for letter in spaces: # show the secret word with spaces in between each letter
        print(letter, end=' ')
    print()

def GetdaGuess(alreadyGuessed):
    while True:
        print('Pick a letter for the Hangman Game')
        R_I = input()
        R_I = R_I.lower()
        if len(R_I) != 1:
            print('Please enter 1 letter only')
        elif R_I in alreadyGuessed:
            print('You"ve chosen that letter. Please try again')
        if R_I not in 'abcdefghijklmnopqrstuvwxyz':
            print('Only letters please')
        return R_I

def Play1MoreTime():
    guess = input('Would you like to play again?\n')
    return input().lower().startswith('y')

print('H A N G M A N ')
missedLetters = ''
correctLetters = ''
secretWords = getRandomWord(words)
gameIsDone = False

while True:
    displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWords)

    guess = GetdaGuess(missedLetters + correctLetters)

    if guess in secretWords:
        correctLetters = correctLetters + guess

    foundAllDaLetters = True
    for i in range(len(secretWords)):
        if secretWords[i] not in correctLetters:
            foundAllDaLetters = False
            break
    if foundAllDaLetters:
        print('Good job. The correct word was'+ secretWord+'. ')

    if len(missedLetters) == len(HANGMANPICS) - 1:

        print('Your out of tries.\nAfter ' + str(len(missedLetters)) + ' wrong guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')

    gameIsDone = True

    if gameIsDone:
        if  Play1MoreTime():
            missedLetters = ''
            correctLetters = ''
            gameIsdone = False
            secretWord = getRandomWord(words)
        else:
            break


问:
Custom fields for profile page using plugin are not created/updated
I am creating a plugin that creates custom fields on the author profile page.

-It creates custom fields on the user profile page
-We can save it for every user.

What is happening now:
-Creates field and it can be seen in the front end of the author profile page
-On saving the fields do not save.

Observation: I saw the custom meta key and data is not there is the user meta table. So I am thinking we are able to see fields in the front end but database meta key values are not created.

The same code works perfectly when added to functions.php. Please let me if I am missing anything or if any other hooks need to be fired when adding as a plugin.

```<code><?php

 class authorFieldsPlugin {
  function __construct() {
   //Uses author.php from plugin of not there in theme.
    add_filter( 'template_include', 'wpa_155871_template_loader' );
    function wpa_155871_template_loader( $template ) {
       $file = '';
       if ( is_author() ) {
            $file   = 'author.php'; // the name of your custom template
            $find[] = $file;
            $find[] = 'plugin-name/' . $file; // name of folder it could be in, in user's theme
        }

        if ( $file ) {
            $template       = locate_template( array_unique( $find ) );
            if ( ! $template ) {
              // if not found in theme, will use your plugin version
              $template = untrailingslashit( plugin_dir_path( __FILE__ ) ) . '/' . $file;
            }
        }

        return $template;
    }

    function memberpage_rewrite() {
      global $wp_rewrite;
      $wp_rewrite->flush_rules();
    }
 add_action('init','memberpage_rewrite');
   //Custom profile fields
 add_action( 'show_user_profile', 'extra_user_profile_fields' );
 add_action( 'edit_user_profile', 'extra_user_profile_fields' );

function extra_user_profile_fields( $user ) { ?>
    <h3><?php _e("Author Information", "blank"); ?></h3>
    <table class="form-table">
    <tr>
    <th><label for="author"><?php _e("Author Information"); ?></label></th>
    <td>
    <textarea name="author" id="author" rows="5" cols="10" ><?php echo esc_attr( get_the_author_meta( 'author', $user->ID ) ); ?></textarea><br />
    <span class="description"><?php _e("Please enter Author's Information from plugin."); ?></span>
    </td>
    </tr>

    <tr>
    <th><label for="author_title"><?php _e("Author Title"); ?></label></th>
    <td>
    <textarea name="author_title" id="author_title" rows="5" cols="10" ><?php echo esc_attr(             get_the_author_meta( 'author_title', $user->ID ) ); ?></textarea><br />
    <span class="author_title"><?php _e("Please enter author_title."); ?></span>
    </td>
    </tr>
    </table>
    <?php }

    add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
    add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );

    function save_extra_user_profile_fields( $user_id ) {

    if ( !current_user_can( 'edit_user', $user_id ) ) { return false; }

    update_user_meta( $user_id, 'author', $_POST['author'] );
    }

  }

}
$authorFieldsPlugin = new authorFieldsPlugin(); ?>
</code>```

Body:
I am creating a plugin that creates custom fields on the author profile page.

-It creates custom fields on the user profile page
-We can save it for every user.

What is happening now:
-Creates field and it can be seen in the front end of the author profile page
-On saving the fields do not save.

Observation: I saw the custom meta key and data is not there is the user meta table. So I am thinking we are able to see fields in the front end but database meta key values are not created.

The same code works perfectly when added to functions.php. Please let me if I am missing anything or if any other hooks need to be fired when adding as a plugin.

<?php

 class authorFieldsPlugin {
  function __construct() {
   //Uses author.php from plugin of not there in theme.
    add_filter( 'template_include', 'wpa_155871_template_loader' );
    function wpa_155871_template_loader( $template ) {
       $file = '';
       if ( is_author() ) {
            $file   = 'author.php'; // the name of your custom template
            $find[] = $file;
            $find[] = 'plugin-name/' . $file; // name of folder it could be in, in user's theme
        }

        if ( $file ) {
            $template       = locate_template( array_unique( $find ) );
            if ( ! $template ) {
              // if not found in theme, will use your plugin version
              $template = untrailingslashit( plugin_dir_path( __FILE__ ) ) . '/' . $file;
            }
        }

        return $template;
    }

    function memberpage_rewrite() {
      global $wp_rewrite;
      $wp_rewrite->flush_rules();
    }
 add_action('init','memberpage_rewrite');
   //Custom profile fields
 add_action( 'show_user_profile', 'extra_user_profile_fields' );
 add_action( 'edit_user_profile', 'extra_user_profile_fields' );

function extra_user_profile_fields( $user ) { ?>

<?php _e("Author Information", "blank"); ?>

    <?php _e("Author Information"); ?>

    <textarea name="author" id="author" rows="5" cols="10" ><?php echo esc_attr( get_the_author_meta( 'author', $user->ID ) ); ?></textarea>

    <?php _e("Please enter Author's Information from plugin."); ?>

    <?php _e("Author Title"); ?>

    <textarea name="author_title" id="author_title" rows="5" cols="10" ><?php echo esc_attr(             get_the_author_meta( 'author_title', $user->ID ) ); ?></textarea>

    <?php _e("Please enter author_title."); ?>

    <?php }

    add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
    add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );

    function save_extra_user_profile_fields( $user_id ) {

    if ( !current_user_can( 'edit_user', $user_id ) ) { return false; }

    update_user_meta( $user_id, 'author', $_POST['author'] );
    }

  }

}
$authorFieldsPlugin = new authorFieldsPlugin(); ?>


问:
How to mimic the `sha1_file($img)` method from the browser to verify a img file?
I'm trying my best to figure out how to send a sha-1 hash of the image file from my browser to verify the contents of a backblaze b2 upload.

From the browser, I need to: provide a (1) the 40-character hex checksum of the file which they verify using the PHP method sha1_file($img).

I have tried fileReader + crypto.subtle.digest('sha-1', file) and the cryptoJS package but nothing works and I get an error that the checksum didn't match.

Any ideas?

Here is the instructions I'm following: https://www.backblaze.com/b2/docs/uploading.html


问:
CombinedConfiguration.getString(key, defaultValue) is not working in MVN
I have a weird error with my short code. The code is running well when I ran the test class inside IntelliJ and also drone tasks (which just executing command mvn clean install).  But error occurred when I tried to run the mvn command using command line.

After debugging, I found out a NullPointerException occurred in the following code:
combinedConfiguration.getString("application.env", DEFAULT_ENVIRONMENT).toLowerCase();

combinedConfiguration is an instance of org.apache.commons.configuration2.CombinedConfiguration.

Based on the API documentation, a method getString(key, devaultValue) shall return the defaultValue when key is not exist in CombinedConfiguration. So I totally don't understand why the NullPointerException occurred. Can anyone help?


问:
Chrome Extension - make a full page screenshot - TypeError: chrome.tabs.captureTab is not a function
I'm trying to capture a full page screenshot of a web page through a chrome extension. I have managed to capture a screenshot with chrome.tabs.captureVisibleTab but I'd like to capture the full page.

I have tried chrome.tabs.captureTab but I always end up with the same error message:
TypeError: chrome.tabs.captureTab is not a function

Here is the code:

```<code>async function createTab (url) {
    return new Promise(resolve => {
        chrome.tabs.create({url}, tab => resolve(tab));
    });
}

(async() => {
    let tab = await createTab('https://www.laurentwillen.be');
    chrome.tabs.captureTab(tab.id, { format: "png" }, function(image) {
         chrome.downloads.download({
            url: image,
            filename: "screenshot.png",
            saveAs: false
        });
    });

})();
</code>```

I'm using Chrome 108 under Windows. Is the chrome.tabs.captureTab supported by this version ?

Thanks
Laurent

Body:
I'm trying to capture a full page screenshot of a web page through a chrome extension. I have managed to capture a screenshot with chrome.tabs.captureVisibleTab but I'd like to capture the full page.

I have tried chrome.tabs.captureTab but I always end up with the same error message:
TypeError: chrome.tabs.captureTab is not a function

Here is the code:

async function createTab (url) {
    return new Promise(resolve => {
        chrome.tabs.create({url}, tab => resolve(tab));
    });
}

(async() => {
    let tab = await createTab('https://www.laurentwillen.be');
    chrome.tabs.captureTab(tab.id, { format: "png" }, function(image) {
         chrome.downloads.download({
            url: image,
            filename: "screenshot.png",
            saveAs: false
        });
    });

})();

I'm using Chrome 108 under Windows. Is the chrome.tabs.captureTab supported by this version ?

Thanks
Laurent


问:
Contact Form Returning 409 Error PHP JavaScript HTML
I have a contact form on my personal website for the past few days and I ran into a problem that Google Chrome's Developer Console marks as error 409, as far as I know a error 409 can be caused by a series of issues such as:

Conflict between ID's (doesn't seem to be the problem)

Conflict problem with the server (I talked with HostGator customer support and no issues were found)

Conflict between code communication (I think this is the issue)

When I run the .php code by accessing it through my website /main.php, I am able to receive an empty email, which could probably mean that the communication between the files, JavaScript, PHP and HTML are not properly communicating which is my best bet. I can't seem to find whats causing the error.

Code on CodePen (NOTE: PHP is commented out on the javascript snippet)

https://codepen.io/jpgaviria/pen/WNKpyGV

HTML

    <form action="#" id="formcontact">

          Nombre
          <input
            type="text"
            id="yourname"
            placeholder="Ingresa tu nombre"
            name="name"
            class="mt-3 input-control inputtext"
            data-name="name"
          />

          E-Mail
          <input
            type="email"
            id="yourmail"
            placeholder="Ingresa tu e-mail"
            name="email"
            class="mt-3 input-control inputtext"
            data-name="email"
          />

          Mensaje
          <textarea
            class="comentarea mt-3 input-control"
            id="comment"
            placeholder="Tienes una campaña en mente? Descríbenos como la visualizas y cuales son tus metas, así podemos ayudarte."
            data-name="comment"
            name="comment"
          ></textarea>
          <button
            id="submitbutton"
            class="submitbuton button mt-5 mb-3"
            type="submit"
          >
            Enviar Ahora
          </button>

    </form>

```
<p>PHP:</p>
<pre class="lang-php prettyprint-override"><code><?php
$subject    = 'E-mail from' . $_REQUEST['email']; // Subject of your email
$to         = 'e-mail@example.com'; //Your e-mail address
$headers    = 'MIME-Version: 1.0' . "\r\n" .
              'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message    = 'Name: ' . $_REQUEST['name'] . ' <br/>' .
              'E-mail: ' . $_REQUEST['email'] . ' <br/>' .
              'Message: ' . $_REQUEST['comment'];
if (@mail($to, $subject, $message, $headers))
{
 echo 'your message send';
}
else
{
 echo 'failed';
}
?>
</code>```

JS:

/*
* ----------------------------------------------------------------------------------------
Version       : 1.1
Filename      : main.js
* ----------------------------------------------------------------------------------------
*/
const rushinit = (function() {
    "use strict";
    // variable
    var body = document.querySelector('body');
    var header = document.getElementById('wrap-header');
    var wrapload = document.querySelector('.loading');
    var glass = document.querySelector('.glasseffect');
    var GL = document.querySelectorAll(".gl");
    var menubar = document.querySelector('.menu-bar');
    var closemenu = document.querySelector('.wrap-close')
    var mobilenav = document.querySelector('.mobile-navwrap');
    var mobilelink = document.querySelectorAll('.navigation-listmobile li a');
    var testimonials = document.getElementById("wrap-testimonial");
    var buttonsubmit = document.getElementById('submitbutton');
    var formcontact = document.getElementById('formcontact');
    var allinputs = formcontact.querySelectorAll('.input-control');
    var information = document.querySelector('.contactform__loader');
    var inputelement = document.querySelector('.inputtext');
    var textareaelement = document.querySelector('.comentarea');
    // glass effect on desktop this will not work on firefox
    var glassx = true;
    // glass effect on mobile this will not work on firefox
    var glassonmobile = true;
    //detect mobile device
    var isMobile = {
        Android: function() {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function() {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }
    };
    // loader page
    const loadder = function(e) {
        setTimeout(() => {
            fadeOut(wrapload)
        }, 1000);
    };
    // testimonial slider
    const testimonialslider = function(e) {
        new KeenSlider(testimonials, {
            loop: true,
            mode: "free-snap",
            breakpoints: {
                "(min-width: 320px)": {
                    slides: { perView: 1, spacing: 5 },
                },
                "(min-width: 400px)": {
                    slides: { perView: 1, spacing: 5 },
                },
                "(min-width: 1000px)": {
                    slides: { perView: 1, spacing: 20 },
                },
            },
            slides: {
                perView: 2,
                spacing: 15,
            }
        });
    };
    // titlt image
    const tiltinit = function(e) {
        VanillaTilt.init(GL, {
            max: 10,
            speed: 400
        });
    };
    //fade in effect
    const fadeIn = function(el) {
        el.classList.add('show');
        el.classList.remove('hide');
    };
    //fade out effect
    const fadeOut = function(el) {
        el.classList.add('hide');
        el.classList.remove('show');
    };
    // form post submit
    const posttheform = function(e) {
        formcontact.onsubmit = async (e) => {
            e.preventDefault();
            var valid = [];
            allinputs.forEach(function(i, j) {
                if (i.getAttribute('data-name')) {
                    var checkAttr = i.getAttribute('data-name');
                } else {
                    var checkAttr = i.tagName;
                }
                var thisvalue = i.value;
                // check input valid
                switch (checkAttr) {
                    case 'name':
                        if (thisvalue == '') {
                            i.classList.add("error");
                            valid.push('
Please check your input name
');
                        } else if (thisvalue.length < 3) {
                            valid.push('
Sorry your name char is to short
');
                        } else {
                            i.classList.remove("error");
                        }

                        break;
                    case 'email':
                        var regEmail = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
                        if (i.value == '' || !regEmail.test(i.value)) {
                            i.classList.add("error");
                            valid.push('
Please check your mail address input
');
                        } else {
                            i.classList.remove("error");
                        }
                        break;
                    case 'comment':
                        if (thisvalue == '') {
                            i.classList.add("error");
                            valid.push('
Please write something
');
                        } else {
                            i.classList.remove("error");
                        }

                        break;
                    default:
                        if (i.value == '') {
                            valid.push('
Something was wrong
');
                            i.classList.add("error");
                        } else {
                            i.classList.remove("error");
                        }
                        break;
                };
            });
            if (valid.length) {
                information.innerHTML = `<div class="alert alert-danger" role="alert"><h4 class="alert-heading">There is something wrong !</h4> <hr><p class="mb-0"><ul class="errorlist">` + valid.join('') + `</ul></p></div>`;
            } else {
                information.innerHTML = `<div class="d-flex align-items-center"><strong class="font-weight-normal">Please wait...</strong><div class="spinner-border spinner-border-sm ml-auto" role="status" aria-hidden="true"></div></div>`;
                inputelement.setAttribute("readonly", "true");
                textareaelement.setAttribute("readonly", "true");
                buttonsubmit.setAttribute("disable", "true");
                // change the fetch address based on the mail.php file you put in your server's file directory ---------------------------
                let response = await fetch('mail.php', {
                        method: 'POST',
                        body: new FormData(formcontact)
                    })
                    .then((response) => response.text())
                    //Then with the data from the response in JSON...
                    .then((data) => {
                        if (data === 'your message send') {
                            formcontact.reset();
                            inputelement.removeAttribute("readonly");
                            textareaelement.removeAttribute("readonly");
                            buttonsubmit.removeAttribute("disable");
                            information.innerHTML = `<div class="alert alert-success  " role="alert"><h4 class="alert-heading">Message send successful !</h4> <hr><p class="mb-0">I will reply to your message soon thank you</p></div>`;
                        }
                    })
                    //Then with the error genereted...
                    .catch((error) => {
                        formcontact.reset();
                        inputelement.removeAttribute("readonly");
                        textareaelement.removeAttribute("readonly");
                        buttonsubmit.removeAttribute("disable");
                        information.innerHTML = `<div class="alert alert-danger " role="alert"><h4 class="alert-heading">There is something wrong !</h4> <hr><p class="mb-0">Sorry, your message failed to be sent due to an unknown error</p></div>`;
                    });
            }
            return false;
        };
    };
    // click button menu burger
    const buttonclick = function(e) {
        // menu mobile toggle
        menubar.addEventListener("click", function(e) {
            //your handler here
            this.style.display = 'none';
            mobilenav.style.display = 'block';
            mobilenav.classList.remove('closemenu');
            mobilenav.classList.add('showmenu');
            closemenu.style.display = 'block';
            body.classList.add('fixed');
            e.preventDefault();
        }, false);
        //close menu
        closemenu.addEventListener("click", function(e) {
            this.style.display = 'none';
            mobilenav.classList.remove('showmenu');
            mobilenav.classList.add('closemenu');
            body.classList.remove('fixed');
            menubar.style.display = 'block';
            e.preventDefault();
        }, false);
        // mobile link navigation
        for (var i = 0; i < mobilelink.length; i++) {
            mobilelink[i].addEventListener('click', function(e) {
                closemenu.style.display = 'none';
                mobilenav.classList.remove('showmenu');
                mobilenav.classList.add('closemenu');
                body.classList.remove('fixed');
                menubar.style.display = 'block';
            }, false);
        };
    };
    //binds event ----------------------------
    const bindEvents = function(e) {
        // window onbuffer
        window.onbeforeunload = function(e) {
            // force scroll to top when refresh page
            window.scrollTo(0, 0);
        };
        // window load
        window.addEventListener('load', (e) => {
            //load animation page
            loadder();
        });
        // document load
        window.addEventListener('DOMContentLoaded', (e) => {
            // menu
            buttonclick();
            // scroll spy
            new bootstrap.ScrollSpy(document.body, {
                target: '*',
                offset: 1
            });
            //init if not on mobile
            if (!isMobile.any()) {
                tiltinit();
            };
            //slider
            testimonialslider();
            // GLightbox
            GLightbox();
            // animated on scroll
            AOS.init({
                disable: function() {
                    var maxWidth = 999;
                    return window.innerWidth < maxWidth;
                },
                once: false
            });
            // post contact
            posttheform();
        });
        window.addEventListener("scroll", (e) => {
            if (window.pageYOffset > 10) {
                header.classList.add('fixi');
            } else {
                header.classList.remove('fixi');
            };
        });
        window.addEventListener("activate.bs.scrollspy", (e) => {
            // let links = navlinks.classList.contains('active');
            var index = document.querySelector('nav a.active').getAttribute('href');
            if (index == '#home') {
                fadeOut(glass);
            };
            if (isMobile.any()) {
                if (glassonmobile) {
                    // comment this line if dont want any glass blur effect
                    if (index == '#home') {
                        fadeOut(glass);
                    } else {
                        fadeIn(glass);
                    }
                };
            };
            if (!isMobile.any()) {
                if (glassx) {
                    // comment this line if dont want any glass blur effect
                    if (index == '#home' || index == '#contact-section') {
                        fadeOut(glass);
                    } else {
                        fadeIn(glass);
                    }
                };
            };
        });
    };
    // init - initilizes elements and events
    const Init = function(e) {
        bindEvents();
    };
    return {
        Init: Init
    };
}());
//initilizing app
rushinit.Init();
```

Body:
I have a contact form on my personal website for the past few days and I ran into a problem that Google Chrome's Developer Console marks as error 409, as far as I know a error 409 can be caused by a series of issues such as:

Conflict between ID's (doesn't seem to be the problem)

Conflict problem with the server (I talked with HostGator customer support and no issues were found)

Conflict between code communication (I think this is the issue)

When I run the .php code by accessing it through my website /main.php, I am able to receive an empty email, which could probably mean that the communication between the files, JavaScript, PHP and HTML are not properly communicating which is my best bet. I can't seem to find whats causing the error.

Code on CodePen (NOTE: PHP is commented out on the javascript snippet)

https://codepen.io/jpgaviria/pen/WNKpyGV

HTML

    <form action="#" id="formcontact">

          Nombre
          <input
            type="text"
            id="yourname"
            placeholder="Ingresa tu nombre"
            name="name"
            class="mt-3 input-control inputtext"
            data-name="name"
          />

          E-Mail
          <input
            type="email"
            id="yourmail"
            placeholder="Ingresa tu e-mail"
            name="email"
            class="mt-3 input-control inputtext"
            data-name="email"
          />

          Mensaje
          <textarea
            class="comentarea mt-3 input-control"
            id="comment"
            placeholder="Tienes una campaña en mente? Descríbenos como la visualizas y cuales son tus metas, así podemos ayudarte."
            data-name="comment"
            name="comment"
          ></textarea>
          <button
            id="submitbutton"
            class="submitbuton button mt-5 mb-3"
            type="submit"
          >
            Enviar Ahora
          </button>

    </form>

PHP:

<?php
$subject    = 'E-mail from' . $_REQUEST['email']; // Subject of your email
$to         = 'e-mail@example.com'; //Your e-mail address
$headers    = 'MIME-Version: 1.0' . "\r\n" .
              'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message    = 'Name: ' . $_REQUEST['name'] . '
' .
              'E-mail: ' . $_REQUEST['email'] . '
' .
              'Message: ' . $_REQUEST['comment'];
if (@mail($to, $subject, $message, $headers))
{
 echo 'your message send';
}
else
{
 echo 'failed';
}
?>

JS:

/*
* ----------------------------------------------------------------------------------------
Version       : 1.1
Filename      : main.js
* ----------------------------------------------------------------------------------------
*/
const rushinit = (function() {
    "use strict";
    // variable
    var body = document.querySelector('body');
    var header = document.getElementById('wrap-header');
    var wrapload = document.querySelector('.loading');
    var glass = document.querySelector('.glasseffect');
    var GL = document.querySelectorAll(".gl");
    var menubar = document.querySelector('.menu-bar');
    var closemenu = document.querySelector('.wrap-close')
    var mobilenav = document.querySelector('.mobile-navwrap');
    var mobilelink = document.querySelectorAll('.navigation-listmobile li a');
    var testimonials = document.getElementById("wrap-testimonial");
    var buttonsubmit = document.getElementById('submitbutton');
    var formcontact = document.getElementById('formcontact');
    var allinputs = formcontact.querySelectorAll('.input-control');
    var information = document.querySelector('.contactform__loader');
    var inputelement = document.querySelector('.inputtext');
    var textareaelement = document.querySelector('.comentarea');
    // glass effect on desktop this will not work on firefox
    var glassx = true;
    // glass effect on mobile this will not work on firefox
    var glassonmobile = true;
    //detect mobile device
    var isMobile = {
        Android: function() {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function() {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }
    };
    // loader page
    const loadder = function(e) {
        setTimeout(() => {
            fadeOut(wrapload)
        }, 1000);
    };
    // testimonial slider
    const testimonialslider = function(e) {
        new KeenSlider(testimonials, {
            loop: true,
            mode: "free-snap",
            breakpoints: {
                "(min-width: 320px)": {
                    slides: { perView: 1, spacing: 5 },
                },
                "(min-width: 400px)": {
                    slides: { perView: 1, spacing: 5 },
                },
                "(min-width: 1000px)": {
                    slides: { perView: 1, spacing: 20 },
                },
            },
            slides: {
                perView: 2,
                spacing: 15,
            }
        });
    };
    // titlt image
    const tiltinit = function(e) {
        VanillaTilt.init(GL, {
            max: 10,
            speed: 400
        });
    };
    //fade in effect
    const fadeIn = function(el) {
        el.classList.add('show');
        el.classList.remove('hide');
    };
    //fade out effect
    const fadeOut = function(el) {
        el.classList.add('hide');
        el.classList.remove('show');
    };
    // form post submit
    const posttheform = function(e) {
        formcontact.onsubmit = async (e) => {
            e.preventDefault();
            var valid = [];
            allinputs.forEach(function(i, j) {
                if (i.getAttribute('data-name')) {
                    var checkAttr = i.getAttribute('data-name');
                } else {
                    var checkAttr = i.tagName;
                }
                var thisvalue = i.value;
                // check input valid
                switch (checkAttr) {
                    case 'name':
                        if (thisvalue == '') {
                            i.classList.add("error");
                            valid.push('
Please check your input name
');
                        } else if (thisvalue.length < 3) {
                            valid.push('
Sorry your name char is to short
');
                        } else {
                            i.classList.remove("error");
                        }

                        break;
                    case 'email':
                        var regEmail = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
                        if (i.value == '' || !regEmail.test(i.value)) {
                            i.classList.add("error");
                            valid.push('
Please check your mail address input
');
                        } else {
                            i.classList.remove("error");
                        }
                        break;
                    case 'comment':
                        if (thisvalue == '') {
                            i.classList.add("error");
                            valid.push('
Please write something
');
                        } else {
                            i.classList.remove("error");
                        }

                        break;
                    default:
                        if (i.value == '') {
                            valid.push('
Something was wrong
');
                            i.classList.add("error");
                        } else {
                            i.classList.remove("error");
                        }
                        break;
                };
            });
            if (valid.length) {
                information.innerHTML = `<div class="alert alert-danger" role="alert"><h4 class="alert-heading">There is something wrong !</h4> <hr><p class="mb-0"><ul class="errorlist">` + valid.join('') + `</ul></p></div>`;
            } else {
                information.innerHTML = `<div class="d-flex align-items-center"><strong class="font-weight-normal">Please wait...</strong><div class="spinner-border spinner-border-sm ml-auto" role="status" aria-hidden="true"></div></div>`;
                inputelement.setAttribute("readonly", "true");
                textareaelement.setAttribute("readonly", "true");
                buttonsubmit.setAttribute("disable", "true");
                // change the fetch address based on the mail.php file you put in your server's file directory ---------------------------
                let response = await fetch('mail.php', {
                        method: 'POST',
                        body: new FormData(formcontact)
                    })
                    .then((response) => response.text())
                    //Then with the data from the response in JSON...
                    .then((data) => {
                        if (data === 'your message send') {
                            formcontact.reset();
                            inputelement.removeAttribute("readonly");
                            textareaelement.removeAttribute("readonly");
                            buttonsubmit.removeAttribute("disable");
                            information.innerHTML = `<div class="alert alert-success  " role="alert"><h4 class="alert-heading">Message send successful !</h4> <hr><p class="mb-0">I will reply to your message soon thank you</p></div>`;
                        }
                    })
                    //Then with the error genereted...
                    .catch((error) => {
                        formcontact.reset();
                        inputelement.removeAttribute("readonly");
                        textareaelement.removeAttribute("readonly");
                        buttonsubmit.removeAttribute("disable");
                        information.innerHTML = `<div class="alert alert-danger " role="alert"><h4 class="alert-heading">There is something wrong !</h4> <hr><p class="mb-0">Sorry, your message failed to be sent due to an unknown error</p></div>`;
                    });
            }
            return false;
        };
    };
    // click button menu burger
    const buttonclick = function(e) {
        // menu mobile toggle
        menubar.addEventListener("click", function(e) {
            //your handler here
            this.style.display = 'none';
            mobilenav.style.display = 'block';
            mobilenav.classList.remove('closemenu');
            mobilenav.classList.add('showmenu');
            closemenu.style.display = 'block';
            body.classList.add('fixed');
            e.preventDefault();
        }, false);
        //close menu
        closemenu.addEventListener("click", function(e) {
            this.style.display = 'none';
            mobilenav.classList.remove('showmenu');
            mobilenav.classList.add('closemenu');
            body.classList.remove('fixed');
            menubar.style.display = 'block';
            e.preventDefault();
        }, false);
        // mobile link navigation
        for (var i = 0; i < mobilelink.length; i++) {
            mobilelink[i].addEventListener('click', function(e) {
                closemenu.style.display = 'none';
                mobilenav.classList.remove('showmenu');
                mobilenav.classList.add('closemenu');
                body.classList.remove('fixed');
                menubar.style.display = 'block';
            }, false);
        };
    };
    //binds event ----------------------------
    const bindEvents = function(e) {
        // window onbuffer
        window.onbeforeunload = function(e) {
            // force scroll to top when refresh page
            window.scrollTo(0, 0);
        };
        // window load
        window.addEventListener('load', (e) => {
            //load animation page
            loadder();
        });
        // document load
        window.addEventListener('DOMContentLoaded', (e) => {
            // menu
            buttonclick();
            // scroll spy
            new bootstrap.ScrollSpy(document.body, {
                target: '*',
                offset: 1
            });
            //init if not on mobile
            if (!isMobile.any()) {
                tiltinit();
            };
            //slider
            testimonialslider();
            // GLightbox
            GLightbox();
            // animated on scroll
            AOS.init({
                disable: function() {
                    var maxWidth = 999;
                    return window.innerWidth < maxWidth;
                },
                once: false
            });
            // post contact
            posttheform();
        });
        window.addEventListener("scroll", (e) => {
            if (window.pageYOffset > 10) {
                header.classList.add('fixi');
            } else {
                header.classList.remove('fixi');
            };
        });
        window.addEventListener("activate.bs.scrollspy", (e) => {
            // let links = navlinks.classList.contains('active');
            var index = document.querySelector('nav a.active').getAttribute('href');
            if (index == '#home') {
                fadeOut(glass);
            };
            if (isMobile.any()) {
                if (glassonmobile) {
                    // comment this line if dont want any glass blur effect
                    if (index == '#home') {
                        fadeOut(glass);
                    } else {
                        fadeIn(glass);
                    }
                };
            };
            if (!isMobile.any()) {
                if (glassx) {
                    // comment this line if dont want any glass blur effect
                    if (index == '#home' || index == '#contact-section') {
                        fadeOut(glass);
                    } else {
                        fadeIn(glass);
                    }
                };
            };
        });
    };
    // init - initilizes elements and events
    const Init = function(e) {
        bindEvents();
    };
    return {
        Init: Init
    };
}());
//initilizing app
rushinit.Init();


问:
String cannot be cast to class UserDetailsImpl
I already tried to find something related to this but all questions are different and I caught myself staring at the screen for the past three hours without success to solve this.

So previously I had a login and registration on same page, and back then login controller worked fine. I had to do some refactoring and needed to separate login and registration form on two HTML pages and now login form doesn't work. So now when I insert username and password and click on login I get There was an unexpected error (type=Internal Server Error, status=500). and this error in stack trace

Error is:

```<code> class java.lang.String cannot be cast to class com.budgettracker.demo.security.token.services.UserDetailsImpl (java.lang.String is in module java.base of loader 'bootstrap'; com.budgettracker.demo.security.token.services.UserDetailsImpl is in unnamed module of loader 'app')
</code>```

This is UserDetailsImpl which is mentioned in error:

```<code>public class UserDetailsImpl implements UserDetails {
private static final long serialVersionUID = 1L;

private Long id;

private String username;

private String email;

private String firstName;

@JsonIgnore
private String password;

private Collection<? extends GrantedAuthority> authorities;

public UserDetailsImpl(Long id, String username, String email, String firstName, String password,
                       Collection<? extends GrantedAuthority> authorities) {
    this.id = id;
    this.username = username;
    this.email = email;
    this.firstName = firstName;
    this.password = password;
    this.authorities = authorities;
}

public static UserDetailsImpl build(User user) {
    List<GrantedAuthority> authorities = user.getRoles().stream()
            .map(role -> new SimpleGrantedAuthority(role.getName().name()))
            .collect(Collectors.toList());

    return new UserDetailsImpl(
            user.getId(),
            user.getUsername(),
            user.getEmail(),
            user.getFirstName(),
            user.getPassword(),
            authorities);
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return authorities;
}

@Override
public String getPassword() {
    return password;
}

@Override
public String getUsername() {
    return username;
}

@Override
public boolean isAccountNonExpired() {
    return true;
}

@Override
public boolean isAccountNonLocked() {
    return true;
}

@Override
public boolean isCredentialsNonExpired() {
    return true;
}

@Override
public boolean isEnabled() {
    return true;
}

@Override
public boolean equals(Object o) {
    if (this == o)
        return true;
    if (o == null || getClass() != o.getClass())
        return false;
    UserDetailsImpl user = (UserDetailsImpl) o;
    return Objects.equals(id, user.id);
}
</code>```

}

Any suggestion what can be the problem? Do I need to provide something more, maybe something else is also related to this error? I'm here just ask.

EDIT 1

I also found that maybe this can cause problem, this is inside my UserDetailsServiceImpl

```<code>  @Override
  @Transactional
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username)
        .orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));

    return UserDetailsImpl.build(user);
  }
</code>```

This is login controller:

```<code> @PostMapping("/login")
@Transactional
public String login(@ModelAttribute("login") @Valid LoginRequest loginRequest, BindingResult result, Model model) {
    Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
    SecurityContextHolder.getContext().setAuthentication(authentication);
    UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();

    ResponseCookie jwtCookie = jwtUtils.generateJwtCookie(user);

    boolean thereAreErrors = result.hasErrors();
    if (thereAreErrors) {
        model.addAttribute("login", loginRequest);
        return "login";
    }

    model.addAttribute("login", loginRequest);

    ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, jwtCookie.toString());

    return "redirect:/api/test/homePage";

}
</code>```

Thymeleaf form:

```<code> <form
            method="post"
            role="form"
            th:action="@{/api/auth/login}"
            th:object="${login}">

        <label for="chk" aria-hidden="true">Login</label>

        <input
                class="form-control"
                id="usernameLogin"
                name="username"
                placeholder="Enter username"
                th:field="*{username}"
                type="text"
                required/>

        <p th:errors="*{username}" class="text-danger"
           th:if="${#fields.hasErrors('username')}"></p>

        <input
                class="form-control"
                id="passwordLogin"
                name="password"
                placeholder="Enter password"
                th:field="*{password}"
                type="password"
                required/>

        <p th:errors="*{password}" class="text-danger"
           th:if="${#fields.hasErrors('password')}"></p>

        <button>Login</button>
    </form>
</code>```

Full stack trace:

```<code>java.lang.ClassCastException: class java.lang.String cannot be cast to class com.budgettracker.demo.security.models.User (java.lang.String is in module java.base of loader 'bootstrap'; com.budgettracker.demo.security.models.User is in unnamed module of loader 'app')
at com.budgettracker.demo.security.controllers.TestController.index(TestController.java:47) ~[classes/:na]
at com.budgettracker.demo.security.controllers.TestController$$FastClassBySpringCGLIB$$de5ce390.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.3.22.jar:5.3.22]
at org.springframework.aop.framework.CglibAopProxy.invokeMethod(CglibAopProxy.java:386) ~[spring-aop-5.3.22.jar:5.3.22]
at org.springframework.aop.framework.CglibAopProxy.access$000(CglibAopProxy.java:85) ~[spring-aop-5.3.22.jar:5.3.22]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:704) ~[spring-aop-5.3.22.jar:5.3.22]
at com.budgettracker.demo.security.controllers.TestController$$EnhancerBySpringCGLIB$$6e3ec78e.index(<generated>) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1070) ~[spring-webmvc-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.22.jar:5.3.22]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) ~[tomcat-embed-core-9.0.65.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.22.jar:5.3.22]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.65.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:111) ~[spring-web-5.3.22.jar:5.3.22]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:337) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:122) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:116) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:109) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:223) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at com.budgettracker.demo.security.token.jwt.AuthTokenFilter.doFilterInternal(AuthTokenFilter.java:51) ~[classes/:na]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:91) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:112) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:82) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.session.DisableEncodeUrlFilter.doFilterInternal(DisableEncodeUrlFilter.java:42) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:221) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:186) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:354) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267) ~[spring-web-5.3.22.jar:5.3.22]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
</code>```

Index controller:

```<code>@GetMapping("/homePage")
public String index(Model model, Principal principal) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
    long userId = user.getId();
    model.addAttribute("userId", userId);

    return "homepage";
}
</code>```

Body:
I already tried to find something related to this but all questions are different and I caught myself staring at the screen for the past three hours without success to solve this.

So previously I had a login and registration on same page, and back then login controller worked fine. I had to do some refactoring and needed to separate login and registration form on two HTML pages and now login form doesn't work. So now when I insert username and password and click on login I get There was an unexpected error (type=Internal Server Error, status=500). and this error in stack trace

Error is:

 class java.lang.String cannot be cast to class com.budgettracker.demo.security.token.services.UserDetailsImpl (java.lang.String is in module java.base of loader 'bootstrap'; com.budgettracker.demo.security.token.services.UserDetailsImpl is in unnamed module of loader 'app')

This is UserDetailsImpl which is mentioned in error:

public class UserDetailsImpl implements UserDetails {
private static final long serialVersionUID = 1L;

private Long id;

private String username;

private String email;

private String firstName;

@JsonIgnore
private String password;

private Collection<? extends GrantedAuthority> authorities;

public UserDetailsImpl(Long id, String username, String email, String firstName, String password,
                       Collection<? extends GrantedAuthority> authorities) {
    this.id = id;
    this.username = username;
    this.email = email;
    this.firstName = firstName;
    this.password = password;
    this.authorities = authorities;
}

public static UserDetailsImpl build(User user) {
    List<GrantedAuthority> authorities = user.getRoles().stream()
            .map(role -> new SimpleGrantedAuthority(role.getName().name()))
            .collect(Collectors.toList());

    return new UserDetailsImpl(
            user.getId(),
            user.getUsername(),
            user.getEmail(),
            user.getFirstName(),
            user.getPassword(),
            authorities);
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return authorities;
}

@Override
public String getPassword() {
    return password;
}

@Override
public String getUsername() {
    return username;
}

@Override
public boolean isAccountNonExpired() {
    return true;
}

@Override
public boolean isAccountNonLocked() {
    return true;
}

@Override
public boolean isCredentialsNonExpired() {
    return true;
}

@Override
public boolean isEnabled() {
    return true;
}

@Override
public boolean equals(Object o) {
    if (this == o)
        return true;
    if (o == null || getClass() != o.getClass())
        return false;
    UserDetailsImpl user = (UserDetailsImpl) o;
    return Objects.equals(id, user.id);
}

}

Any suggestion what can be the problem? Do I need to provide something more, maybe something else is also related to this error? I'm here just ask.

EDIT 1

I also found that maybe this can cause problem, this is inside my UserDetailsServiceImpl

  @Override
  @Transactional
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username)
        .orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));

    return UserDetailsImpl.build(user);
  }

This is login controller:

 @PostMapping("/login")
@Transactional
public String login(@ModelAttribute("login") @Valid LoginRequest loginRequest, BindingResult result, Model model) {
    Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
    SecurityContextHolder.getContext().setAuthentication(authentication);
    UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();

    ResponseCookie jwtCookie = jwtUtils.generateJwtCookie(user);

    boolean thereAreErrors = result.hasErrors();
    if (thereAreErrors) {
        model.addAttribute("login", loginRequest);
        return "login";
    }

    model.addAttribute("login", loginRequest);

    ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, jwtCookie.toString());

    return "redirect:/api/test/homePage";

}

Thymeleaf form:

 <form
            method="post"
            role="form"
            th:action="@{/api/auth/login}"
            th:object="${login}">

        Login

        <input
                class="form-control"
                id="usernameLogin"
                name="username"
                placeholder="Enter username"
                th:field="*{username}"
                type="text"
                required/>

        <input
                class="form-control"
                id="passwordLogin"
                name="password"
                placeholder="Enter password"
                th:field="*{password}"
                type="password"
                required/>

        <button>Login</button>
    </form>

Full stack trace:

java.lang.ClassCastException: class java.lang.String cannot be cast to class com.budgettracker.demo.security.models.User (java.lang.String is in module java.base of loader 'bootstrap'; com.budgettracker.demo.security.models.User is in unnamed module of loader 'app')
at com.budgettracker.demo.security.controllers.TestController.index(TestController.java:47) ~[classes/:na]
at com.budgettracker.demo.security.controllers.TestController$$FastClassBySpringCGLIB$$de5ce390.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.3.22.jar:5.3.22]
at org.springframework.aop.framework.CglibAopProxy.invokeMethod(CglibAopProxy.java:386) ~[spring-aop-5.3.22.jar:5.3.22]
at org.springframework.aop.framework.CglibAopProxy.access$000(CglibAopProxy.java:85) ~[spring-aop-5.3.22.jar:5.3.22]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:704) ~[spring-aop-5.3.22.jar:5.3.22]
at com.budgettracker.demo.security.controllers.TestController$$EnhancerBySpringCGLIB$$6e3ec78e.index(<generated>) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1070) ~[spring-webmvc-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.22.jar:5.3.22]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) ~[tomcat-embed-core-9.0.65.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.22.jar:5.3.22]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.65.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:111) ~[spring-web-5.3.22.jar:5.3.22]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:337) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:122) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:116) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:109) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:223) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at com.budgettracker.demo.security.token.jwt.AuthTokenFilter.doFilterInternal(AuthTokenFilter.java:51) ~[classes/:na]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:91) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:112) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:82) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.session.DisableEncodeUrlFilter.doFilterInternal(DisableEncodeUrlFilter.java:42) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:221) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:186) ~[spring-security-web-5.7.3.jar:5.7.3]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:354) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267) ~[spring-web-5.3.22.jar:5.3.22]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.22.jar:5.3.22]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.22.jar:5.3.22]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]

Index controller:

@GetMapping("/homePage")
public String index(Model model, Principal principal) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
    long userId = user.getId();
    model.addAttribute("userId", userId);

    return "homepage";
}


问:
mstest - /resultsfile doesnt work when /testsettings switch is used
I need to specify the location of the MSTest log file.  I was doing this just fine with /resultfile:path but we needed the global timout, etc from the .settings file so i added the /testsettings:testfile.testsettings switch.  Now that ive done that, MSTest no longer creates the log.

Any ideas?  Ive tried specifying /resultfile switch after /testsettings

ContentLicense: CC BY-SA 3.0


问:
Pre-built Drupal twig component - how to attain
I'm a Marketing/Web Designer working in the Drupal 9 CMS. I have experience with HTML/CSS/JavaScript, but we have limited developer support.

Whats the quickest way to attain prebuilt twig components that we can add/incorporate into our CMS? Specifically looking for standard (paragraph types) Hero banner, Carousel etc..
I am aware of Drupal Marketplace, but that seems to only offer working through existing companies. We're able to pay for services, but not sure if companies within the Drupal Marketplace are able to do one-offs?