问:
Java login with MySQL database
Hi at the moment I can't log in to MySQL database with SQL statement and open next MenuForm. Not sure what's wrong with it. There is no error. I have added additional if "//if(password.contains("123") && username.contains("test")) {" to check if it works and it does work but still can't compare it with MySQL.

```<code>private void jButton_LoginActionPerformed(java.awt.event.ActionEvent evt) {

       PreparedStatement st;
       ResultSet rs;

       // get the username & password
       String username = jTextField_Username.getText();
       String password = String.valueOf(jPasswordField.getPassword());

       //create a select query to check if the username and the password exist in the database
       String query = "SELECT * FROM users_db.users WHERE 'username' = ? and 'password' = ?";

        try {
            st = My_CNX.getConnection().prepareStatement(query);

            st.setString(1, username);
            st.setString(2, password);
            rs = st.executeQuery();

            //if(password.contains("123") && username.contains("test")) {
            if(rs.next()){
                // show a new form
                MenuForm form = new MenuForm();
                form.setVisible(true);
                form.pack(); // rozmiarem ma się zająć automatycznie manager rozmiaru? druga opcja to ustalenie romziaru x i y, za pomocą innej funkcji
                form.setLocationRelativeTo(null);
                //close the current form(login form)
                form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                this.dispose();

            }else{
            // error message

            JOptionPane.showMessageDialog(null, "Invalid Username or Password", "Login Error",2);

        }

        } catch (SQLException ex) {
            Logger.getLogger(Login_Form.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
</code>```

I have added whole code here.
I have included the whole login Form below.

```/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Login_register_design;

import java.awt.Color;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.border.Border;
import javax.swing.BorderFactory;
import javax.swing.JFrame;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author tomas
 */
public class Login_Form extends javax.swing.JFrame {

    /**
     * Creates new form Login_Form
     */
    public Login_Form() {
        initComponents();
        /* - Downalod The Connector For Java & MySQL database*/
        /* Link -> https://dev.mysql.com/downloads/connector/j/ */

        /* OPEN */
        /*Create a connection with the database */

        // Center the form
       this.setLocationRelativeTo(null);
       // create a yellow border for the panel_title
       // 0 border in the top
       Border jpanel_title_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.blue);
       // set the border to the jpanel_title
       jPanel_title.setBorder(jpanel_title_border);

       // create a orange border for the global panel
       Border global_panel_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.orange);
       jPanel5.setBorder(global_panel_border);

       // create a black border for the close & minimize jlables
       Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black);
       jLabel_minimize.setBorder(label_border);
       jLabel_close.setBorder(label_border);

       // create border for the username and password field
       Border field_border = BorderFactory.createMatteBorder(1, 5, 1, 1, Color.white);
       jTextField_Username.setBorder(field_border);
       jPasswordField.setBorder(field_border);

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jLabel_username = new javax.swing.JLabel();
        jLabel_password = new javax.swing.JLabel();
        jTextField_Username = new javax.swing.JTextField();
        jPasswordField = new javax.swing.JPasswordField();
        jButton_Login = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel_minimize = new javax.swing.JLabel();
        jLabel_close = new javax.swing.JLabel();
        jPanel_title = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();

        jPanel1.setForeground(new java.awt.Color(0, 255, 153));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 462, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 330, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setUndecorated(true);

        jPanel2.setBackground(new java.awt.Color(0, 204, 204));

        jLabel_username.setIcon(new javax.swing.ImageIcon(getClass().getResource("/grafika/Loginemail-100px.png"))); // NOI18N

        jLabel_password.setIcon(new javax.swing.ImageIcon(getClass().getResource("/grafika/Hasło-100px.png"))); // NOI18N

        jTextField_Username.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jTextField_Username.setForeground(new java.awt.Color(153, 153, 153));
        jTextField_Username.setText("username");
        jTextField_Username.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextField_UsernameFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextField_UsernameFocusLost(evt);
            }
        });
        jTextField_Username.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField_UsernameActionPerformed(evt);
            }
        });

        jPasswordField.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jPasswordField.setForeground(new java.awt.Color(153, 153, 153));
        jPasswordField.setText("password");
        jPasswordField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jPasswordFieldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                jPasswordFieldFocusLost(evt);
            }
        });

        jButton_Login.setBackground(new java.awt.Color(0, 84, 140));
        jButton_Login.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
        jButton_Login.setForeground(new java.awt.Color(255, 255, 255));
        jButton_Login.setText("Login");
        jButton_Login.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jButton_Login.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                jButton_LoginMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                jButton_LoginMouseExited(evt);
            }
        });
        jButton_Login.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_LoginActionPerformed(evt);
            }
        });

        jPanel3.setBackground(new java.awt.Color(0, 153, 153));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton_Login, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel_password)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel_username)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField_Username, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(24, Short.MAX_VALUE))
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(174, 174, 174)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(45, 45, 45)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jTextField_Username)
                    .addComponent(jLabel_username, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel_password, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPasswordField))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton_Login, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(53, Short.MAX_VALUE))
        );

        // set icon to the jlabel
        // set icon to the jlabel

        jLabel_minimize.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel_minimize.setText("-");
        jLabel_minimize.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jLabel_minimize.setPreferredSize(new java.awt.Dimension(17, 29));
        jLabel_minimize.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel_minimizeMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                jLabel_minimizeMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                jLabel_minimizeMouseExited(evt);
            }
        });

        jLabel_close.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
        jLabel_close.setText("X");
        jLabel_close.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jLabel_close.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel_closeMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                jLabel_closeMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                jLabel_closeMouseExited(evt);
            }
        });

        jPanel_title.setBackground(new java.awt.Color(51, 153, 255));

        jLabel3.setBackground(new java.awt.Color(51, 153, 255));
        jLabel3.setFont(new java.awt.Font("Arial", 1, 48)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Login");

        javax.swing.GroupLayout jPanel_titleLayout = new javax.swing.GroupLayout(jPanel_title);
        jPanel_title.setLayout(jPanel_titleLayout);
        jPanel_titleLayout.setHorizontalGroup(
            jPanel_titleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_titleLayout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jLabel3)
                .addContainerGap(42, Short.MAX_VALUE))
        );
        jPanel_titleLayout.setVerticalGroup(
            jPanel_titleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_titleLayout.createSequentialGroup()
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 10, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(118, 118, 118)
                        .addComponent(jPanel_title, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(57, 57, 57)
                        .addComponent(jLabel_minimize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel_close))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(14, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addComponent(jPanel_title, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel_close)
                            .addComponent(jLabel_minimize, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(23, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>

    private void jLabel_minimizeMouseEntered(java.awt.event.MouseEvent evt) {

       Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.white);
       jLabel_minimize.setBorder(label_border);
       jLabel_minimize.setForeground(Color.white);

    }

    private void jLabel_minimizeMouseExited(java.awt.event.MouseEvent evt) {

        Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black);
        jLabel_minimize.setBorder(label_border);
        jLabel_minimize.setForeground(Color.black);
    }

    private void jLabel_closeMouseEntered(java.awt.event.MouseEvent evt) {

       Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.white);
       jLabel_close.setBorder(label_border);
       jLabel_close.setForeground(Color.white);
    }

    private void jLabel_closeMouseExited(java.awt.event.MouseEvent evt) {

       Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black);
       jLabel_close.setBorder(label_border);
       jLabel_close.setForeground(Color.black);

    }

    private void jTextField_UsernameFocusGained(java.awt.event.FocusEvent evt) {

        // clear the testfield on focus if the text is "username"
        if(jTextField_Username.getText().trim().toLowerCase().equals("username"));
        {
            jTextField_Username.setText("");
            jTextField_Username.setForeground(Color.black);
        }

         Border jpanel_icon = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.blue);

        jLabel_username.setBorder(jpanel_icon);

    }

    private void jTextField_UsernameFocusLost(java.awt.event.FocusEvent evt) {

        // if the text field is equal to username or empty
        // we will set the "username" text in the field on
        // on focus lost event

        if(jTextField_Username.getText().trim().equals("") ||
           jTextField_Username.getText().trim().toLowerCase().equals("username"))
        {
           jTextField_Username.setText("username");
           jTextField_Username.setForeground(new Color(153,153,153));
        }
         // create a border with the color of the parent jpanel for the icons label to remove the move
       Border label_icons_border = BorderFactory.createMatteBorder(1, 1, 1, 1, new Color(153,153,153));
       jLabel_username.setBorder(label_icons_border);
    }

    private void jPasswordFieldFocusGained(java.awt.event.FocusEvent evt) {

        // clear the password on focus if the text is "password"
        // get the password text
        String pass = String.valueOf(jPasswordField.getPassword());

        if(pass.trim().toLowerCase().equals("password"));
        {
            jPasswordField.setText("");
            jPasswordField.setForeground(Color.black);
        }

        // set a yellow border to the jlabel icon
         Border jpanel_icon = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.blue);
       // set the border to the jpanel_title
        jLabel_password.setBorder(jpanel_icon);

    }

    private void jPasswordFieldFocusLost(java.awt.event.FocusEvent evt) {

           // get the password text
        String pass = String.valueOf(jPasswordField.getPassword());

        if(pass.trim().equals("") ||
           pass.trim().toLowerCase().equals("password"))
        {
           jPasswordField.setText("password");
           jPasswordField.setForeground(new Color(153,153,153));
        }

         // create a border with the color of the parent jpanel for the icons label to remove the move
       Border label_icons_border = BorderFactory.createMatteBorder(1, 1, 1, 1, new Color(153,153,153));
       jLabel_password.setBorder(label_icons_border);
    }

    private void jButton_LoginActionPerformed(java.awt.event.ActionEvent evt) {

       PreparedStatement st;
       ResultSet rs;

       // get the username & password
       String username = jTextField_Username.getText();
       String password = String.valueOf(jPasswordField.getPassword());

       //create a select query to check if the username and the password exist in the database
       String query = "SELECT * FROM users_db.users WHERE 'username' = ? and 'password' = ?";

        try {
            st = My_CNX.getConnection().prepareStatement(query);

            st.setString(1, username);
            st.setString(2, password);
            rs = st.executeQuery();

            //if(password.contains("123") && username.contains("test")) {
            if(rs.next()){
                // show a new form
                MenuForm form = new MenuForm();
                form.setVisible(true);
                form.pack(); // rozmiarem ma się zająć automatycznie manager rozmiaru? druga opcja to ustalenie romziaru x i y, za pomocą innej funkcji
                form.setLocationRelativeTo(null);
                //close the current form(login form)
                form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                this.dispose();

            }else{
            // error message

            JOptionPane.showMessageDialog(null, "Invalid Username or Password", "Login Error",2);

        }

        } catch (SQLException ex) {
            Logger.getLogger(Login_Form.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void jButton_LoginMouseEntered(java.awt.event.MouseEvent evt) {

         //set jbutton backbround
        jButton_Login.setBackground(new Color(0, 101, 183));

    }

    private void jButton_LoginMouseExited(java.awt.event.MouseEvent evt) {

        //set jbutton backbround
        jButton_Login.setBackground(new Color(0, 84, 104));

    }

    private void jLabel_minimizeMouseClicked(java.awt.event.MouseEvent evt) {

        this.setState(JFrame.ICONIFIED);

    }

    private void jLabel_closeMouseClicked(java.awt.event.MouseEvent evt) {

        System.exit(0);

    }

    private void jTextField_UsernameActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Login_Form().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton_Login;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel_close;
    private javax.swing.JLabel jLabel_minimize;
    private javax.swing.JLabel jLabel_password;
    private javax.swing.JLabel jLabel_username;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel_title;
    private javax.swing.JPasswordField jPasswordField;
    private javax.swing.JTextField jTextField_Username;
    // End of variables declaration
}

```

答:
Replace

```<code>"SELECT * FROM users_db.users WHERE 'username' = ? and 'password' = ?"
</code>```

with

```<code>"SELECT * FROM users_db.users WHERE username = ? AND password = ?"
</code>```

Note that I have removed single quotes enclosing fields.

Title: Java login with MySQL database

Body:
Hi at the moment I can't log in to MySQL database with SQL statement and open next MenuForm. Not sure what's wrong with it. There is no error. I have added additional if "//if(password.contains("123") && username.contains("test")) {" to check if it works and it does work but still can't compare it with MySQL.

private void jButton_LoginActionPerformed(java.awt.event.ActionEvent evt) {

       PreparedStatement st;
       ResultSet rs;

       // get the username & password
       String username = jTextField_Username.getText();
       String password = String.valueOf(jPasswordField.getPassword());

       //create a select query to check if the username and the password exist in the database
       String query = "SELECT * FROM users_db.users WHERE 'username' = ? and 'password' = ?";

        try {
            st = My_CNX.getConnection().prepareStatement(query);

            st.setString(1, username);
            st.setString(2, password);
            rs = st.executeQuery();

            //if(password.contains("123") && username.contains("test")) {
            if(rs.next()){
                // show a new form
                MenuForm form = new MenuForm();
                form.setVisible(true);
                form.pack(); // rozmiarem ma się zająć automatycznie manager rozmiaru? druga opcja to ustalenie romziaru x i y, za pomocą innej funkcji
                form.setLocationRelativeTo(null);
                //close the current form(login form)
                form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                this.dispose();

            }else{
            // error message

            JOptionPane.showMessageDialog(null, "Invalid Username or Password", "Login Error",2);

        }

        } catch (SQLException ex) {
            Logger.getLogger(Login_Form.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

I have added whole code here.
I have included the whole login Form below.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Login_register_design;

import java.awt.Color;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.border.Border;
import javax.swing.BorderFactory;
import javax.swing.JFrame;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author tomas
 */
public class Login_Form extends javax.swing.JFrame {

    /**
     * Creates new form Login_Form
     */
    public Login_Form() {
        initComponents();
        /* - Downalod The Connector For Java & MySQL database*/
        /* Link -> https://dev.mysql.com/downloads/connector/j/ */

        /* OPEN */
        /*Create a connection with the database */

        // Center the form
       this.setLocationRelativeTo(null);
       // create a yellow border for the panel_title
       // 0 border in the top
       Border jpanel_title_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.blue);
       // set the border to the jpanel_title
       jPanel_title.setBorder(jpanel_title_border);

       // create a orange border for the global panel
       Border global_panel_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.orange);
       jPanel5.setBorder(global_panel_border);

       // create a black border for the close & minimize jlables
       Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black);
       jLabel_minimize.setBorder(label_border);
       jLabel_close.setBorder(label_border);

       // create border for the username and password field
       Border field_border = BorderFactory.createMatteBorder(1, 5, 1, 1, Color.white);
       jTextField_Username.setBorder(field_border);
       jPasswordField.setBorder(field_border);

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jLabel_username = new javax.swing.JLabel();
        jLabel_password = new javax.swing.JLabel();
        jTextField_Username = new javax.swing.JTextField();
        jPasswordField = new javax.swing.JPasswordField();
        jButton_Login = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel_minimize = new javax.swing.JLabel();
        jLabel_close = new javax.swing.JLabel();
        jPanel_title = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();

        jPanel1.setForeground(new java.awt.Color(0, 255, 153));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 462, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 330, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setUndecorated(true);

        jPanel2.setBackground(new java.awt.Color(0, 204, 204));

        jLabel_username.setIcon(new javax.swing.ImageIcon(getClass().getResource("/grafika/Loginemail-100px.png"))); // NOI18N

        jLabel_password.setIcon(new javax.swing.ImageIcon(getClass().getResource("/grafika/Hasło-100px.png"))); // NOI18N

        jTextField_Username.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jTextField_Username.setForeground(new java.awt.Color(153, 153, 153));
        jTextField_Username.setText("username");
        jTextField_Username.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextField_UsernameFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextField_UsernameFocusLost(evt);
            }
        });
        jTextField_Username.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField_UsernameActionPerformed(evt);
            }
        });

        jPasswordField.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jPasswordField.setForeground(new java.awt.Color(153, 153, 153));
        jPasswordField.setText("password");
        jPasswordField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jPasswordFieldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                jPasswordFieldFocusLost(evt);
            }
        });

        jButton_Login.setBackground(new java.awt.Color(0, 84, 140));
        jButton_Login.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
        jButton_Login.setForeground(new java.awt.Color(255, 255, 255));
        jButton_Login.setText("Login");
        jButton_Login.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jButton_Login.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                jButton_LoginMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                jButton_LoginMouseExited(evt);
            }
        });
        jButton_Login.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_LoginActionPerformed(evt);
            }
        });

        jPanel3.setBackground(new java.awt.Color(0, 153, 153));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton_Login, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel_password)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel_username)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField_Username, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(24, Short.MAX_VALUE))
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(174, 174, 174)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(45, 45, 45)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jTextField_Username)
                    .addComponent(jLabel_username, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel_password, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPasswordField))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton_Login, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(53, Short.MAX_VALUE))
        );

        // set icon to the jlabel
        // set icon to the jlabel

        jLabel_minimize.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel_minimize.setText("-");
        jLabel_minimize.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jLabel_minimize.setPreferredSize(new java.awt.Dimension(17, 29));
        jLabel_minimize.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel_minimizeMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                jLabel_minimizeMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                jLabel_minimizeMouseExited(evt);
            }
        });

        jLabel_close.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
        jLabel_close.setText("X");
        jLabel_close.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jLabel_close.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel_closeMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                jLabel_closeMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                jLabel_closeMouseExited(evt);
            }
        });

        jPanel_title.setBackground(new java.awt.Color(51, 153, 255));

        jLabel3.setBackground(new java.awt.Color(51, 153, 255));
        jLabel3.setFont(new java.awt.Font("Arial", 1, 48)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Login");

        javax.swing.GroupLayout jPanel_titleLayout = new javax.swing.GroupLayout(jPanel_title);
        jPanel_title.setLayout(jPanel_titleLayout);
        jPanel_titleLayout.setHorizontalGroup(
            jPanel_titleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_titleLayout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jLabel3)
                .addContainerGap(42, Short.MAX_VALUE))
        );
        jPanel_titleLayout.setVerticalGroup(
            jPanel_titleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_titleLayout.createSequentialGroup()
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 10, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(118, 118, 118)
                        .addComponent(jPanel_title, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(57, 57, 57)
                        .addComponent(jLabel_minimize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel_close))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(14, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addComponent(jPanel_title, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel_close)
                            .addComponent(jLabel_minimize, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(23, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>

    private void jLabel_minimizeMouseEntered(java.awt.event.MouseEvent evt) {

       Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.white);
       jLabel_minimize.setBorder(label_border);
       jLabel_minimize.setForeground(Color.white);

    }

    private void jLabel_minimizeMouseExited(java.awt.event.MouseEvent evt) {

        Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black);
        jLabel_minimize.setBorder(label_border);
        jLabel_minimize.setForeground(Color.black);
    }

    private void jLabel_closeMouseEntered(java.awt.event.MouseEvent evt) {

       Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.white);
       jLabel_close.setBorder(label_border);
       jLabel_close.setForeground(Color.white);
    }

    private void jLabel_closeMouseExited(java.awt.event.MouseEvent evt) {

       Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black);
       jLabel_close.setBorder(label_border);
       jLabel_close.setForeground(Color.black);

    }

    private void jTextField_UsernameFocusGained(java.awt.event.FocusEvent evt) {

        // clear the testfield on focus if the text is "username"
        if(jTextField_Username.getText().trim().toLowerCase().equals("username"));
        {
            jTextField_Username.setText("");
            jTextField_Username.setForeground(Color.black);
        }

         Border jpanel_icon = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.blue);

        jLabel_username.setBorder(jpanel_icon);

    }

    private void jTextField_UsernameFocusLost(java.awt.event.FocusEvent evt) {

        // if the text field is equal to username or empty
        // we will set the "username" text in the field on
        // on focus lost event

        if(jTextField_Username.getText().trim().equals("") ||
           jTextField_Username.getText().trim().toLowerCase().equals("username"))
        {
           jTextField_Username.setText("username");
           jTextField_Username.setForeground(new Color(153,153,153));
        }
         // create a border with the color of the parent jpanel for the icons label to remove the move
       Border label_icons_border = BorderFactory.createMatteBorder(1, 1, 1, 1, new Color(153,153,153));
       jLabel_username.setBorder(label_icons_border);
    }

    private void jPasswordFieldFocusGained(java.awt.event.FocusEvent evt) {

        // clear the password on focus if the text is "password"
        // get the password text
        String pass = String.valueOf(jPasswordField.getPassword());

        if(pass.trim().toLowerCase().equals("password"));
        {
            jPasswordField.setText("");
            jPasswordField.setForeground(Color.black);
        }

        // set a yellow border to the jlabel icon
         Border jpanel_icon = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.blue);
       // set the border to the jpanel_title
        jLabel_password.setBorder(jpanel_icon);

    }

    private void jPasswordFieldFocusLost(java.awt.event.FocusEvent evt) {

           // get the password text
        String pass = String.valueOf(jPasswordField.getPassword());

        if(pass.trim().equals("") ||
           pass.trim().toLowerCase().equals("password"))
        {
           jPasswordField.setText("password");
           jPasswordField.setForeground(new Color(153,153,153));
        }

         // create a border with the color of the parent jpanel for the icons label to remove the move
       Border label_icons_border = BorderFactory.createMatteBorder(1, 1, 1, 1, new Color(153,153,153));
       jLabel_password.setBorder(label_icons_border);
    }

    private void jButton_LoginActionPerformed(java.awt.event.ActionEvent evt) {

       PreparedStatement st;
       ResultSet rs;

       // get the username & password
       String username = jTextField_Username.getText();
       String password = String.valueOf(jPasswordField.getPassword());

       //create a select query to check if the username and the password exist in the database
       String query = "SELECT * FROM users_db.users WHERE 'username' = ? and 'password' = ?";

        try {
            st = My_CNX.getConnection().prepareStatement(query);

            st.setString(1, username);
            st.setString(2, password);
            rs = st.executeQuery();

            //if(password.contains("123") && username.contains("test")) {
            if(rs.next()){
                // show a new form
                MenuForm form = new MenuForm();
                form.setVisible(true);
                form.pack(); // rozmiarem ma się zająć automatycznie manager rozmiaru? druga opcja to ustalenie romziaru x i y, za pomocą innej funkcji
                form.setLocationRelativeTo(null);
                //close the current form(login form)
                form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                this.dispose();

            }else{
            // error message

            JOptionPane.showMessageDialog(null, "Invalid Username or Password", "Login Error",2);

        }

        } catch (SQLException ex) {
            Logger.getLogger(Login_Form.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void jButton_LoginMouseEntered(java.awt.event.MouseEvent evt) {

         //set jbutton backbround
        jButton_Login.setBackground(new Color(0, 101, 183));

    }

    private void jButton_LoginMouseExited(java.awt.event.MouseEvent evt) {

        //set jbutton backbround
        jButton_Login.setBackground(new Color(0, 84, 104));

    }

    private void jLabel_minimizeMouseClicked(java.awt.event.MouseEvent evt) {

        this.setState(JFrame.ICONIFIED);

    }

    private void jLabel_closeMouseClicked(java.awt.event.MouseEvent evt) {

        System.exit(0);

    }

    private void jTextField_UsernameActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Login_Form().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton_Login;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel_close;
    private javax.swing.JLabel jLabel_minimize;
    private javax.swing.JLabel jLabel_password;
    private javax.swing.JLabel jLabel_username;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel_title;
    private javax.swing.JPasswordField jPasswordField;
    private javax.swing.JTextField jTextField_Username;
    // End of variables declaration
}

Body:
Replace

"SELECT * FROM users_db.users WHERE 'username' = ? and 'password' = ?"

with

"SELECT * FROM users_db.users WHERE username = ? AND password = ?"

Note that I have removed single quotes enclosing fields.


来源: stackexchange

问:
react-big-calendar How to update SASS variables?
I need to style react-big-calendar as per my application styling. This can be achieved by writing custom css classes and importing them. But I am wondering if there is any way to change SCSS variables.
Thanks in advance!!</p>

答:
RBC provides SCSS for you to use in compiling your own CSS, overriding any of it's variables with your own. In your own SCSS file:

```<code>@import '~react-big-calendar/lib/sass/styles';
// your override variables and classes
</code>```

ContentLicense: CC BY-SA 4.0

Body:
RBC provides SCSS for you to use in compiling your own CSS, overriding any of it's variables with your own. In your own SCSS file:

@import '~react-big-calendar/lib/sass/styles';
// your override variables and classes


问:
Strongly Typed Ids in Entity Framework Core
I'm trying to have a strongly typed Id class, which now holds 'long' internally. Implementation below.
The problem I'm having the using this in my entities is that Entity Framework gives me a message that the property Id is already mapped onto it. See my IEntityTypeConfiguration below.

Note: I am not aiming to have a rigid DDD implementation. So please keep this in mind when commenting or answering. The whole id behind the typed Id is for developers coming to the project they're strongly typed to use Id in all of their entities, of course translated to long (or BIGINT) - but it is clear then for others.

Below the class & configuration, which doesn't work.
The repo can be found at https://github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31,

Id class at (commented out now): https://github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31/blob/master/Source/Common/Kf.CANetCore31/DomainDrivenDesign/Id.cs

Entity and ValueObject classes (where for an Entity the property Id was of the type Id.cs (above): https://github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31/tree/master/Source/Common/Kf.CANetCore31/DomainDrivenDesign

Configurations at: https://github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31/tree/master/Source/Infrastructure/Persistence/Kf.CANetCore31.Infrastructure.Persistence.Ef/EntityTypeConfigurations

Id class implementation (marked obsolete now, because I abandoned the idea until I found a solution for this)

```<code>namespace Kf.CANetCore31.DomainDrivenDesign
{
    [DebuggerDisplay("{DebuggerDisplayString,nq}")]
    [Obsolete]
    public sealed class Id : ValueObject
    {
        public static implicit operator Id(long value)
            => new Id(value);
        public static implicit operator long(Id value)
            => value.Value;
        public static implicit operator Id(ulong value)
            => new Id((long)value);
        public static implicit operator ulong(Id value)
            => (ulong)value.Value;
        public static implicit operator Id(int value)
            => new Id(value);

        public static Id Empty
            => new Id();

        public static Id Create(long value)
            => new Id(value);

        private Id(long id)
            => Value = id;
        private Id()
            : this(0)
        { }

        public long Value { get; }

        public override string DebuggerDisplayString
            => this.CreateDebugString(x => x.Value);

        public override string ToString()
            => DebuggerDisplayString;

        protected override IEnumerable<object> EquatableValues
            => new object[] { Value };
    }
}
</code>```

EntityTypeConfiguration I was using when Id not marked obsolete for entity Person Unfortunately though, when of type Id, EfCore didn't want to map it... when of type long it was no problem... Other owned types, as you see (with Name) work fine.

```<code>public sealed class PersonEntityTypeConfiguration
        : IEntityTypeConfiguration<Person>
    {
        public void Configure(EntityTypeBuilder<Person> builder)
        {
            // this would be wrapped in either a base class or an extenion method on
            // EntityTypeBuilder<TEntity> where TEntity : Entity
            // to not repeated the code over each EntityTypeConfiguration
            // but expanded here for clarity
            builder
                .HasKey(e => e.Id);
            builder
                .OwnsOne(
                e => e.Id,
                id => {
                   id.Property(e => e.Id)
                     .HasColumnName("firstName")
                     .UseIdentityColumn(1, 1)
                     .HasColumnType(SqlServerColumnTypes.Int64_BIGINT);
                }

            builder.OwnsOne(
                e => e.Name,
                name =>
                {
                    name.Property(p => p.FirstName)
                        .HasColumnName("firstName")
                        .HasMaxLength(150);
                    name.Property(p => p.LastName)
                        .HasColumnName("lastName")
                        .HasMaxLength(150);
                }
            );

            builder.Ignore(e => e.Number);
        }
    }
</code>```

Entity base class (when I was still using Id, so when it wasn't marked obsolete)

```<code>namespace Kf.CANetCore31.DomainDrivenDesign
{
    /// <summary>
    /// Defines an entity.
    /// </summary>
    [DebuggerDisplay("{DebuggerDisplayString,nq}")]
    public abstract class Entity
        : IDebuggerDisplayString,
          IEquatable<Entity>
    {
        public static bool operator ==(Entity a, Entity b)
        {
            if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
                return true;

            if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
                return false;

            return a.Equals(b);
        }

        public static bool operator !=(Entity a, Entity b)
            => !(a == b);

        protected Entity(Id id)
            => Id = id;

        public Id Id { get; }

        public override bool Equals(object @object)
        {
            if (@object == null) return false;
            if (@object is Entity entity) return Equals(entity);
            return false;
        }

        public bool Equals(Entity other)
        {
            if (other == null) return false;
            if (ReferenceEquals(this, other)) return true;
            if (GetType() != other.GetType()) return false;
            return Id == other.Id;
        }

        public override int GetHashCode()
            => $"{GetType()}{Id}".GetHashCode();

        public virtual string DebuggerDisplayString
            => this.CreateDebugString(x => x.Id);

        public override string ToString()
            => DebuggerDisplayString;
    }
}
</code>```

Person (the domain and references to the other ValueObjects can be found at https://github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31/tree/master/Source/Core/Domain/Kf.CANetCore31.Core.Domain/People)

```<code>namespace Kf.CANetCore31.Core.Domain.People
{
    [DebuggerDisplay("{DebuggerDisplayString,nq}")]
    public sealed class Person : Entity
    {
        public static Person Empty
            => new Person();

        public static Person Create(Name name)
            => new Person(name);

        public static Person Create(Id id, Name name)
            => new Person(id, name);

        private Person(Id id, Name name)
            : base(id)
            => Name = name;
        private Person(Name name)
            : this(Id.Empty, name)
        { }
        private Person()
            : this(Name.Empty)
        { }

        public Number Number
            => Number.For(this);
        public Name Name { get; }

        public override string DebuggerDisplayString
            => this.CreateDebugString(x => x.Number.Value, x => x.Name);
    }
}
</code>```

答:
So after searching a long while, and trying to get some more answer, I found it, here it is then. Thanks to Andrew Lock.

Strongly-typed IDs in EF Core: Using strongly-typed entity IDs to avoid primitive obsession - Part 4: https://andrewlock.net/strongly-typed-ids-in-ef-core-using-strongly-typed-entity-ids-to-avoid-primitive-obsession-part-4/

TL;DR / Summary of Andrew
In this post I describe a solution to using strongly-typed IDs in your EF Core entities by using value converters and a custom IValueConverterSelector. The base ValueConverterSelector in the EF Core framework is used to register all built-in value conversions between primitive types. By deriving from this class, we can add our strongly-typed ID converters to this list, and get seamless conversion throughout our EF Core queries

Body:
I'm trying to have a strongly typed Id class, which now holds 'long' internally. Implementation below.
The problem I'm having the using this in my entities is that Entity Framework gives me a message that the property Id is already mapped onto it. See my IEntityTypeConfiguration below.

Note: I am not aiming to have a rigid DDD implementation. So please keep this in mind when commenting or answering. The whole id behind the typed Id is for developers coming to the project they're strongly typed to use Id in all of their entities, of course translated to long (or BIGINT) - but it is clear then for others.

Below the class & configuration, which doesn't work.
The repo can be found at https://github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31,

Id class at (commented out now): https://github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31/blob/master/Source/Common/Kf.CANetCore31/DomainDrivenDesign/Id.cs

Entity and ValueObject classes (where for an Entity the property Id was of the type Id.cs (above): https://github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31/tree/master/Source/Common/Kf.CANetCore31/DomainDrivenDesign

Configurations at: https://github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31/tree/master/Source/Infrastructure/Persistence/Kf.CANetCore31.Infrastructure.Persistence.Ef/EntityTypeConfigurations

Id class implementation (marked obsolete now, because I abandoned the idea until I found a solution for this)

namespace Kf.CANetCore31.DomainDrivenDesign
{
    [DebuggerDisplay("{DebuggerDisplayString,nq}")]
    [Obsolete]
    public sealed class Id : ValueObject
    {
        public static implicit operator Id(long value)
            => new Id(value);
        public static implicit operator long(Id value)
            => value.Value;
        public static implicit operator Id(ulong value)
            => new Id((long)value);
        public static implicit operator ulong(Id value)
            => (ulong)value.Value;
        public static implicit operator Id(int value)
            => new Id(value);

        public static Id Empty
            => new Id();

        public static Id Create(long value)
            => new Id(value);

        private Id(long id)
            => Value = id;
        private Id()
            : this(0)
        { }

        public long Value { get; }

        public override string DebuggerDisplayString
            => this.CreateDebugString(x => x.Value);

        public override string ToString()
            => DebuggerDisplayString;

        protected override IEnumerable<object> EquatableValues
            => new object[] { Value };
    }
}

EntityTypeConfiguration I was using when Id not marked obsolete for entity Person Unfortunately though, when of type Id, EfCore didn't want to map it... when of type long it was no problem... Other owned types, as you see (with Name) work fine.

public sealed class PersonEntityTypeConfiguration
        : IEntityTypeConfiguration<Person>
    {
        public void Configure(EntityTypeBuilder<Person> builder)
        {
            // this would be wrapped in either a base class or an extenion method on
            // EntityTypeBuilder<TEntity> where TEntity : Entity
            // to not repeated the code over each EntityTypeConfiguration
            // but expanded here for clarity
            builder
                .HasKey(e => e.Id);
            builder
                .OwnsOne(
                e => e.Id,
                id => {
                   id.Property(e => e.Id)
                     .HasColumnName("firstName")
                     .UseIdentityColumn(1, 1)
                     .HasColumnType(SqlServerColumnTypes.Int64_BIGINT);
                }

            builder.OwnsOne(
                e => e.Name,
                name =>
                {
                    name.Property(p => p.FirstName)
                        .HasColumnName("firstName")
                        .HasMaxLength(150);
                    name.Property(p => p.LastName)
                        .HasColumnName("lastName")
                        .HasMaxLength(150);
                }
            );

            builder.Ignore(e => e.Number);
        }
    }

Entity base class (when I was still using Id, so when it wasn't marked obsolete)

namespace Kf.CANetCore31.DomainDrivenDesign
{
    ///
    /// Defines an entity.
    ///
    [DebuggerDisplay("{DebuggerDisplayString,nq}")]
    public abstract class Entity
        : IDebuggerDisplayString,
          IEquatable<Entity>
    {
        public static bool operator ==(Entity a, Entity b)
        {
            if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
                return true;

            if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
                return false;

            return a.Equals(b);
        }

        public static bool operator !=(Entity a, Entity b)
            => !(a == b);

        protected Entity(Id id)
            => Id = id;

        public Id Id { get; }

        public override bool Equals(object @object)
        {
            if (@object == null) return false;
            if (@object is Entity entity) return Equals(entity);
            return false;
        }

        public bool Equals(Entity other)
        {
            if (other == null) return false;
            if (ReferenceEquals(this, other)) return true;
            if (GetType() != other.GetType()) return false;
            return Id == other.Id;
        }

        public override int GetHashCode()
            => $"{GetType()}{Id}".GetHashCode();

        public virtual string DebuggerDisplayString
            => this.CreateDebugString(x => x.Id);

        public override string ToString()
            => DebuggerDisplayString;
    }
}

Person (the domain and references to the other ValueObjects can be found at https://github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31/tree/master/Source/Core/Domain/Kf.CANetCore31.Core.Domain/People)

namespace Kf.CANetCore31.Core.Domain.People
{
    [DebuggerDisplay("{DebuggerDisplayString,nq}")]
    public sealed class Person : Entity
    {
        public static Person Empty
            => new Person();

        public static Person Create(Name name)
            => new Person(name);

        public static Person Create(Id id, Name name)
            => new Person(id, name);

        private Person(Id id, Name name)
            : base(id)
            => Name = name;
        private Person(Name name)
            : this(Id.Empty, name)
        { }
        private Person()
            : this(Name.Empty)
        { }

        public Number Number
            => Number.For(this);
        public Name Name { get; }

        public override string DebuggerDisplayString
            => this.CreateDebugString(x => x.Number.Value, x => x.Name);
    }
}


问:
xxHash convert resulting in hash too long
I'm using xxHash for C# to hash a value for consistency.
ComputeHash returns a byte[], but I need to store the results in a long.

I'm able to convert the results into an int32 using the BitConverter. Here is what I've tried:

```<code>var xxHash = new System.Data.HashFunction.xxHash();
byte[] hashedValue = xxHash.ComputeHash(Encoding.UTF8.GetBytes(valueItem));
long value = BitConverter.ToInt64(hashedValue, 0);
</code>```

When I use int this works fine, but when I change to ToInt64 it fails.

Here's the exception I get:

Destination array is not long enough to copy all the items in the collection. Check array index and length.

答:
Adding a new answer because current implementation of xxHash from Brandon Dahler uses a hashing factory where you initialize the factory with a configuration containing hashsize and seed:</p>

```<code>using System.Data.HashFunction.xxHash;

//can also set seed here, (ulong) Seed=234567
xxHashConfig config = new xxHashConfig() { HashSizeInBits = 64 };
var factory = xxHashFactory.Instance.Create(config);
byte[] hashedValue = factory.ComputeHash(Encoding.UTF8.GetBytes(valueItem)).Hash;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using xxHash for C# to hash a value for consistency.
ComputeHash returns a byte[], but I need to store the results in a long.

I'm able to convert the results into an int32 using the BitConverter. Here is what I've tried:

var xxHash = new System.Data.HashFunction.xxHash();
byte[] hashedValue = xxHash.ComputeHash(Encoding.UTF8.GetBytes(valueItem));
long value = BitConverter.ToInt64(hashedValue, 0);

When I use int this works fine, but when I change to ToInt64 it fails.

Here's the exception I get:

Destination array is not long enough to copy all the items in the collection. Check array index and length.

Body:
Adding a new answer because current implementation of xxHash from Brandon Dahler uses a hashing factory where you initialize the factory with a configuration containing hashsize and seed:

using System.Data.HashFunction.xxHash;

//can also set seed here, (ulong) Seed=234567
xxHashConfig config = new xxHashConfig() { HashSizeInBits = 64 };
var factory = xxHashFactory.Instance.Create(config);
byte[] hashedValue = factory.ComputeHash(Encoding.UTF8.GetBytes(valueItem)).Hash;


问:
How to use asdf as root user?
I need to read some hardware data with privileges permissions, so I need to use the asdf plugin as root. How can I do that?

I tried to start the root user sudo su but I cannot access asdf

答:
The existing answer on this post pointed me in the right direction: sudo -E is required in order to carry over environment variables (including the important PATH) into the sudo shell.

However, I was still getting the unknown command: THECOMMAND. Perhaps you have to reshim?. What worked for me is getting the path to both the command you want to run and the binary you want to run it through.

In my case, I was trying to use the hostile host management tool. It failed because it couldn't find node. By specifying both the full node path and the direct path to the hostile script I was able to get around the reshim errors.

```<code>sudo -E `asdf which node` `asdf which hostile` load the_file.txt
</code>```

Title: How to use asdf as root user?

Body:
The existing answer on this post pointed me in the right direction: sudo -E is required in order to carry over environment variables (including the important PATH) into the sudo shell.

However, I was still getting the unknown command: THECOMMAND. Perhaps you have to reshim?. What worked for me is getting the path to both the command you want to run and the binary you want to run it through.

In my case, I was trying to use the hostile host management tool. It failed because it couldn't find node. By specifying both the full node path and the direct path to the hostile script I was able to get around the reshim errors.

sudo -E `asdf which node` `asdf which hostile` load the_file.txt


问:
how in python Remove files with .log Extension
How can I list all file of a directory in Python and remove them by .log?

```<code>for root, dirs, files in os.walk(r'/home/m110/public_html/ts/'):
print(files)

output1281.log
output1020.log
log3.log
mem.py
output1087.log
bunker3.py
output1248.log
output1311.log
output1099.log
output1261.log
output1282.log
output1213.log
log43.log
output1291.log
output1095.log
output1209.log
usr.txt
output1210.log
log7.log
output1042.log
attack.py
output1032.log
output1318.log
</code>```

i run this code in Centos7 but i just need list file with .log file extension for delete times

答:
```<code>import os
import shutil
files= next(os.walk(r'/home/m110/public_html/ts/'))[2]
for filename in files:
    ex=filename.split(".")[-1]
    if ex=='log':
       #print ex
       os.remove(filename)
</code>```

Body:
How can I list all file of a directory in Python and remove them by .log?

for root, dirs, files in os.walk(r'/home/m110/public_html/ts/'):
print(files)

output1281.log
output1020.log
log3.log
mem.py
output1087.log
bunker3.py
output1248.log
output1311.log
output1099.log
output1261.log
output1282.log
output1213.log
log43.log
output1291.log
output1095.log
output1209.log
usr.txt
output1210.log
log7.log
output1042.log
attack.py
output1032.log
output1318.log

i run this code in Centos7 but i just need list file with .log file extension for delete times


问:
php - problem with set_error_handler
I'm trying to setup a custom landing error page in the event there is php errros, I'm using:

```<code>function xhandler($number,$string,$file,$line,$context){
  include('/path/to/error_text_page.tpl');
  exit;
}
error_reporting(E_ALL ^ E_NOTICE);
set_error_handler('xhandler',E_ALL ^ E_NOTICE);
</code>```

This isn't working though, anyone know what I'm doing wrong?

答:
According to php.net and to continue with Dr. Molle's reply:

The following error types cannot be
  handled with a user defined function:
  E_ERROR, E_PARSE, E_CORE_ERROR,
  E_CORE_WARNING, E_COMPILE_ERROR,
  E_COMPILE_WARNING, and most of
  E_STRICT raised in the file where
  set_error_handler() is called.

That might explain your problem.

Title: php - problem with set_error_handler

Body:
I'm trying to setup a custom landing error page in the event there is php errros, I'm using:

function xhandler($number,$string,$file,$line,$context){
  include('/path/to/error_text_page.tpl');
  exit;
}
error_reporting(E_ALL ^ E_NOTICE);
set_error_handler('xhandler',E_ALL ^ E_NOTICE);

This isn't working though, anyone know what I'm doing wrong?


问:
Type of argument/value that is passed in a AsyncTask
Just 3 simple questions about AsyncTasks.
If we declare this AsyncTask:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long>

1- What type of value is passed to doInBackground() method? Is it URL?

2- What type of value is passed to the callback that informs the task progress?

3- What type of value is passed to the callback that is executed when the task ends?

Thank you all. Rest of a good day

答:
AsyncTask consists of Input Parameter Type, Progress Parameter Type, Result Type respectively.
So in your case

```<code>DownloadFilesTask extends AsyncTask<URL, Integer, Long>
</code>```

URL is the Input Parameter Type

Integer is the  Progress Parameter Type

Long is the Result Type

What type of value is passed to doInBackground() method? Is it URL?

Answer: Yes its the URL

What type of value is passed to the callback that informs the task
progress?

Answer: its Integer

What type of value is passed to the callback that is executed when
    the task ends?

Answer : Its Long value and it is the value that is expected to
return from doInBackground and passed as a callback to
onPostExecute`.

Body:
AsyncTask consists of Input Parameter Type, Progress Parameter Type, Result Type respectively.
So in your case

DownloadFilesTask extends AsyncTask<URL, Integer, Long>

URL is the Input Parameter Type

Integer is the  Progress Parameter Type

Long is the Result Type

What type of value is passed to doInBackground() method? Is it URL?

Answer: Yes its the URL

What type of value is passed to the callback that informs the task
progress?

Answer: its Integer

What type of value is passed to the callback that is executed when
    the task ends?

Answer : Its Long value and it is the value that is expected to
return from doInBackground and passed as a callback to
onPostExecute`.


问:
How to get back original position of a word in a preprocessed sentence using python?
I am trying to get a sentence from User and preprocessing the same to remove special characters using regex at backend then I need to send back the position of a particular word in order to highlight that word to User, but facing conflict as the position of original and the preprocessed sentence are different.

Is there any best method to solve the above issue using Python?

For example:

```<code>import re

def text_preprocessing(input_text, string_to_find):

    print("Original text is:", input_data)
    cleaned_text = [re.sub('[^a-zA-Z0-9#.+]', " ", input_data)]
    cleaned_text = [re.sub(' +', " ", text) for text in cleaned_text]
    for cleaned_text in cleaned_text:  # just to convert list to string
        print("preprocessed text is:", cleaned_text)
        position = cleaned_text.find(string_to_find)
        position = [position, position + len(string_to_find)]
        return position

input_text = 'Hi! Hello'
string_to_find = 'Hello'
position = text_preprocessing(input_text, string_to_find)
print(position)
</code>```

Actual Output

```<code>Original text is: Hi! Hello
preprocessed text is: Hi Hello
[3, 8]
</code>```

original sentence = 'Hi! Hello'

Preprocessed sentence = 'Hi Hello' (just removed '!' symbol)

In case i need to highlight the word "Hello" I just returning the position from backend as (3,8) but the actual position in UI is (4, 9)

Expected Output

```<code>Original text is: Hi! Hello
preprocessed text is: Hi Hello
[4, 9]
</code>```

OS: windows 10,
Python 3.7,
used regex for preprocessing

答:
The first character in a string is at position 0, then, Hello is at position 3 in the string Hi Hello.

H is at 0

i is at 1

 is at 2

H is at 3

e is at 4

and so on ...

Body:
I am trying to get a sentence from User and preprocessing the same to remove special characters using regex at backend then I need to send back the position of a particular word in order to highlight that word to User, but facing conflict as the position of original and the preprocessed sentence are different.

Is there any best method to solve the above issue using Python?

For example:

import re

def text_preprocessing(input_text, string_to_find):

    print("Original text is:", input_data)
    cleaned_text = [re.sub('[^a-zA-Z0-9#.+]', " ", input_data)]
    cleaned_text = [re.sub(' +', " ", text) for text in cleaned_text]
    for cleaned_text in cleaned_text:  # just to convert list to string
        print("preprocessed text is:", cleaned_text)
        position = cleaned_text.find(string_to_find)
        position = [position, position + len(string_to_find)]
        return position

input_text = 'Hi! Hello'
string_to_find = 'Hello'
position = text_preprocessing(input_text, string_to_find)
print(position)

Actual Output

Original text is: Hi! Hello
preprocessed text is: Hi Hello
[3, 8]

original sentence = 'Hi! Hello'

Preprocessed sentence = 'Hi Hello' (just removed '!' symbol)

In case i need to highlight the word "Hello" I just returning the position from backend as (3,8) but the actual position in UI is (4, 9)

Expected Output

Original text is: Hi! Hello
preprocessed text is: Hi Hello
[4, 9]

OS: windows 10,
Python 3.7,
used regex for preprocessing


问:
NavigationLink with conditional in a List
I want to show the categories and subcategories of some data. I have the data obtained from json, when a category does not have subcategories they have parent = 0 and if it is different from zero it is understood that said category has subcategories.

Then from the list of caregivers I wish to have a NavigationLink according to the value ofparent.

How can I have the NavigationLink with a conditional?

If the category does not have subcategories you must go to the Product () view otherwise you must go to the Scategory view

Something like that, to be added to the Navigation Link

```<code>if parent == 0 {
Product()
} else {
Scategory()
}
</code>```

Basic Sample Code

```<code>struct ContentView: View {
    private let cats = [
        "Category 1", "Category 2"
    ]

    //Here I am assuming this value, when changing to zero you must change the destination of `navigationLInk`
    var parent = 20

    var body: some View {
        NavigationView {
            List(cats, id: \.self) { item in
                //Here, how can I add a conditional to the `NavigationLink` using the value of` parent`
                NavigationLink(destination: Scategory(item: item)) {
                    Text(item)
                }
            }.navigationBarTitle("Category")
        }
    }
}

struct Scategory: View {
    let item: String

    var body: some View {
        VStack {
            Text("Subcategory View \(item)")
                .font(.largeTitle)
        }
    }
}

struct Product: View {
    let item: String

    var body: some View {
        VStack {
            Text("Produc View \(item)")
                .font(.largeTitle)
        }
    }
}
</code>```

答:
Try casting your custom views into AnyView like this:

```<code>if parent == 0 {
    AnyView(Product())
} else {
    AnyView(Scategory())
}
</code>```

Body:
I want to show the categories and subcategories of some data. I have the data obtained from json, when a category does not have subcategories they have parent = 0 and if it is different from zero it is understood that said category has subcategories.

Then from the list of caregivers I wish to have a NavigationLink according to the value ofparent.

How can I have the NavigationLink with a conditional?

If the category does not have subcategories you must go to the Product () view otherwise you must go to the Scategory view

Something like that, to be added to the Navigation Link

if parent == 0 {
Product()
} else {
Scategory()
}

Basic Sample Code

struct ContentView: View {
    private let cats = [
        "Category 1", "Category 2"
    ]

    //Here I am assuming this value, when changing to zero you must change the destination of `navigationLInk`
    var parent = 20

    var body: some View {
        NavigationView {
            List(cats, id: \.self) { item in
                //Here, how can I add a conditional to the `NavigationLink` using the value of` parent`
                NavigationLink(destination: Scategory(item: item)) {
                    Text(item)
                }
            }.navigationBarTitle("Category")
        }
    }
}

struct Scategory: View {
    let item: String

    var body: some View {
        VStack {
            Text("Subcategory View \(item)")
                .font(.largeTitle)
        }
    }
}

struct Product: View {
    let item: String

    var body: some View {
        VStack {
            Text("Produc View \(item)")
                .font(.largeTitle)
        }
    }
}

Body:
Try casting your custom views into AnyView like this:

if parent == 0 {
    AnyView(Product())
} else {
    AnyView(Scategory())
}


问:
Reordering a daily data series into weekly rows with Mon, Tue, Wed, Thur and Fri as the weekly columns
I have a daily time series containing weekdays, excluding weekends.
I would like to reorder it so that each column represents a week and the subsequent five rows show the data for  Mon, Tue, Wed, Thur and Fri of that week.

I tried using cast (package: reshape) but am having problems in obtaining the above.

Thank you for your help.

example:

```<code>Date        Day Value
06/01/2020  mon 15
07/01/2020  tue 16
08/01/2020  wed 17
09/01/2020  thu 18
10/01/2020  fri 19
13/01/2020  mon 20
14/01/2020  tue 21
15/01/2020  wed 22
16/01/2020  thu 23
17/01/2020  fri 24
</code>```

to be reformated to:

```<code>Start of week   mon tue wed thu fri
06/01/2020      15  16  17  18  19
13/01/2020      20  21  22  23  24
</code>```

答:
Here is an example using the tidyverse package. I also used lubridate to convert the Date from character to date class.

The key is to use pivot_wider from the tidyr package to convert the data to the wide format.

```<code>library(tidyverse)
library(lubridate)

dat2 <- dat %>%
  # Convert W to factor for ordering
  mutate(Day = factor(Day, levels = c("mon", "tue", "wed", "thu", "fri"))) %>%
  # Create a goruping variable to show the week number
  group_by(Day) %>%
  mutate(Group = 1:n()) %>%
  ungroup() %>%
  # Change the Date based on Group
  group_by(Group) %>%
  mutate(Date = min(dmy(Date))) %>%
  # Convert to wide format
  pivot_wider(names_from = Day, values_from = Value) %>%
  # Remove Group
  ungroup() %>%
  select(-Group)

dat2
# # A tibble: 2 x 6
#   Date         mon   tue   wed   thu   fri
#   <date>     <int> <int> <int> <int> <int>
# 1 2020-01-06    15    16    17    18    19
# 2 2020-01-13    20    21    22    23    24
</code>```

DATA

```<code># Create example data frame
dat <- read.table(text = "Date Day Value

'06/01/2020' mon 15

'07/01/2020' tue 16

'08/01/2020' wed 17

'09/01/2020' thu 18

'10/01/2020' fri 19

'13/01/2020' mon 20

'14/01/2020' tue 21

'15/01/2020' wed 22

'16/01/2020' thu 23

'17/01/2020' fri 24",
                  header = TRUE, stringsAsFactors = FALSE)
</code>```

Body:
I have a daily time series containing weekdays, excluding weekends.
I would like to reorder it so that each column represents a week and the subsequent five rows show the data for  Mon, Tue, Wed, Thur and Fri of that week.

I tried using cast (package: reshape) but am having problems in obtaining the above.

Thank you for your help.

example:

Date        Day Value
06/01/2020  mon 15
07/01/2020  tue 16
08/01/2020  wed 17
09/01/2020  thu 18
10/01/2020  fri 19
13/01/2020  mon 20
14/01/2020  tue 21
15/01/2020  wed 22
16/01/2020  thu 23
17/01/2020  fri 24

to be reformated to:

Start of week   mon tue wed thu fri
06/01/2020      15  16  17  18  19
13/01/2020      20  21  22  23  24

Body:
Here is an example using the tidyverse package. I also used lubridate to convert the Date from character to date class.

The key is to use pivot_wider from the tidyr package to convert the data to the wide format.

library(tidyverse)
library(lubridate)

dat2 <- dat %>%
  # Convert W to factor for ordering
  mutate(Day = factor(Day, levels = c("mon", "tue", "wed", "thu", "fri"))) %>%
  # Create a goruping variable to show the week number
  group_by(Day) %>%
  mutate(Group = 1:n()) %>%
  ungroup() %>%
  # Change the Date based on Group
  group_by(Group) %>%
  mutate(Date = min(dmy(Date))) %>%
  # Convert to wide format
  pivot_wider(names_from = Day, values_from = Value) %>%
  # Remove Group
  ungroup() %>%
  select(-Group)

dat2
# # A tibble: 2 x 6
#   Date         mon   tue   wed   thu   fri
#   <date>     <int> <int> <int> <int> <int>
# 1 2020-01-06    15    16    17    18    19
# 2 2020-01-13    20    21    22    23    24

DATA

# Create example data frame
dat <- read.table(text = "Date Day Value

'06/01/2020' mon 15

'07/01/2020' tue 16

'08/01/2020' wed 17

'09/01/2020' thu 18

'10/01/2020' fri 19

'13/01/2020' mon 20

'14/01/2020' tue 21

'15/01/2020' wed 22

'16/01/2020' thu 23

'17/01/2020' fri 24",
                  header = TRUE, stringsAsFactors = FALSE)


问:
When setting up uwsgi and nginx, do I have to create the socket file myself?
Am following up this tutorial to setup uwsgi + nginx to serve my django app

uwsgi-docs

all going well despite it assuming that the user understand a few things about uwsgi!

Am in the section where am suppose to use sockets instead of ports for serving pages, this is the instruction

edit your mysite_nginx.conf ( I can do that) to;

```<code>server unix:///path/to/your/mysite/mysite.sock; # for a file socket
# server 127.0.0.1:8001; # for a web port socket (we'll use this first)
</code>```

my question/confusion, What is "mysite.sock" is it a file i should create or what? What are the contents?

Paul

答:
as @Louis's answer.

server unix:///path/to/your/mysite/mysite.sock; # for a file socket

You just change

unix:///path/to/your/mysite/mysite.sock;

to

unix:///home/h/workspace/sun-asterisk/POC-makeup/deploy-tutorial/nginx-tutorial/mysite/mysite.sock;

Note: /home/h/workspace/sun-asterisk/POC-makeup/deploy-tutorial/nginx-tutorial/mysite is my project path.

Body:
Am following up this tutorial to setup uwsgi + nginx to serve my django app

uwsgi-docs

all going well despite it assuming that the user understand a few things about uwsgi!

Am in the section where am suppose to use sockets instead of ports for serving pages, this is the instruction

edit your mysite_nginx.conf ( I can do that) to;

server unix:///path/to/your/mysite/mysite.sock; # for a file socket
# server 127.0.0.1:8001; # for a web port socket (we'll use this first)

my question/confusion, What is "mysite.sock" is it a file i should create or what? What are the contents?

Paul


问:
How to setup wallaby.js in nrwl nx monorepo with angular and nest.js
I try to setup wallaby in my nrwl/nx monorepo. I have a angular 8 and a nest.js app in this monorep. I use Jest for testing and latest Jetbrains Webstorm IDE.  I could not find any instructions on how to get wallaby up and running in this setup.  The only half way helpful resources I was able to find are the sample repos from TomWhiteOmni on GitHub.  However, they are targeted to older Nx versions.  Does anyone ever got such a setup to work and would be willing to share instructions?</p>

答:
I have wallaby running using the official documentation.

https://wallabyjs.com/docs/integration/nrwl.html

But as the docs state, you have to choose the library to run the tests against, which is a bummer.

Maybe it will improve over time.


问:
Including a href in a picture source media element
I'm using the following code to show an image in my website:

```<code>  <div id="wideheader">
     <div id="header">
        <div id="headerimage">
            <picture>
              <source
                media="(max-width: 900px)"
                srcset="images/eye1.jpg">
              <img
                src="images/eye2.jpg"
                alt="">
            </picture>
           <div id="headerteaser">
              Beautiful Eyes
           </div>
        </div>
     </div>
  </div>
</code>```

How could I include an href so that a click on the image would take the visitor to another page?

Thank you!

答:
You just need to enclose the html in anchor tags  where you need a clickable link

        <picture>
          <source
            media="(max-width: 900px)"
            srcset="images/eye1.jpg">

        </picture>

          Beautiful Eyes

```

edit:
Incase you need the href to be only on the image, Enclose the required html snippet in the anchor tags with the required href, And it should work as expected

Body:
I'm using the following code to show an image in my website:

            <picture>
              <source
                media="(max-width: 900px)"
                srcset="images/eye1.jpg">

            </picture>

              Beautiful Eyes

How could I include an href so that a click on the image would take the visitor to another page?

Thank you!

Body:
You just need to enclose the html in anchor tags <a> where you need a clickable link

<div id="wideheader">
  <div id="header">
    <a id="headerimage" href="#">
        <picture>
          <source
            media="(max-width: 900px)"
            srcset="images/eye1.jpg">
          <img
            src="images/eye2.jpg"
            alt="">
        </picture>
       <div id="headerteaser">
          Beautiful Eyes
       </div>
    </a>
 </div>
</div>

edit:
Incase you need the href to be only on the image, Enclose the required html snippet in the anchor tags with the required href, And it should work as expected


问:
Items on left to be added in the box on the right upon clicked
I have a list of items placed on the left (itemDrop) and would like to add it in the box on the right (itemList) when selected. Terms: unable to select the same item, unable to select more than 3 items. Can only edit javascript file, HTML file untouchable.

HTML:

```<code><div id="itemSelectHeader"> <H2>Item List</H2>
<div id="itemSelect">SELECT FROM HERE
<div id="itemDrop" class="itemSetup">
<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>
</ul>
</div>
</div>
</div>
<div id="itemListSection">
    <H3>Items Selected</H3>
    <div id="itemList" class="itemSetup"> <ul></ul></div>
</div>
</code>```

Add ons:
- clear box when clear button clicked
- submit only when there are 3 items selected

```<code>    <div id="itemBtn">
         <button type="button" id="clearItem">CLEAR ALL</button>
         <button type="button" id="selectItem">SUBMIT</button>
    </div>
</code>```

tried the following for clear button but it doesn't work. But worked for alert

```<code>    $("#clearItem").click(function(){
        //alert("try");
        $("#itemList").reset();
    });
</code>```

答:
You can get lists in html by tag selector and then add an click event listener to first list for appending childs to second list.

Look at the following:

let lists = document.getElementsByTagName("ul");

lists[0].addEventListener("click",function(e) {
        if(e.target && e.target.nodeName == "LI" && lists[1].childElementCount<3) {
            lists[1].appendChild(e.target)
        }
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="itemSelectHeader">
<H2>Item List</H2>
<div id="itemSelect">SELECT FROM HERE
<div id="itemDrop" class="itemSetup">
<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>
</ul>
</div>
</div>
</div>
<div id="itemListSection">
    <H3>Items Selected</H3>
    <div id="itemList" class="itemSetup"> <ul></ul></div>
</div></code>```

Body:
I have a list of items placed on the left (itemDrop) and would like to add it in the box on the right (itemList) when selected. Terms: unable to select the same item, unable to select more than 3 items. Can only edit javascript file, HTML file untouchable.

HTML:

Item List

SELECT FROM HERE

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Item 7

Item 8

Items Selected

Add ons:
- clear box when clear button clicked
- submit only when there are 3 items selected

         <button type="button" id="clearItem">CLEAR ALL</button>
         <button type="button" id="selectItem">SUBMIT</button>

tried the following for clear button but it doesn't work. But worked for alert

    $("#clearItem").click(function(){
        //alert("try");
        $("#itemList").reset();
    });

Body:
You can get lists in html by tag selector and then add an click event listener to first list for appending childs to second list.

Look at the following:

let lists = document.getElementsByTagName("ul");

lists[0].addEventListener("click",function(e) {
        if(e.target && e.target.nodeName == "LI" && lists[1].childElementCount<3) {
            lists[1].appendChild(e.target)
        }
    });

<div id="itemSelectHeader">
<H2>Item List</H2>
<div id="itemSelect">SELECT FROM HERE
<div id="itemDrop" class="itemSetup">
<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>
</ul>
</div>
</div>
</div>
<div id="itemListSection">
    <H3>Items Selected</H3>
    <div id="itemList" class="itemSetup"> <ul></ul></div>
</div>