问:
How to lookup values from code and make some new columns based on it
I want to lookup value from a database and make some new columns in a file
actually I have a file like this

```<code>promo code item stok
sale1  100   a   200
sale2  101   b   300
sale3  102   c   100
sale4  103   d    50
</code>```

and a database looks like this

```<code>code item1 code_item1 amount_item1 item2 code_item2 amount_item2
100   a1     1001          2        a2     1002          1
102   a2     1002          1        a3     1003          1
</code>```

and then I want to add my first file several columns which are taken from the database

```<code>promo code item stok item1 code_item1 amount_item1 item2 code_item2 amount_item2
sale1  100   a   200   a1     1001          400        a2     1002          200
sale2  101   b   300
sale3  102   c   100   a2     1002          100        a3     1003          100
sale4  103   d    50
</code>```

How do I do this?

答:
You can use left_join() from dplyr:

```<code>library(dplyr)

my_df <- data.frame(promo = c("sale1", "sale2", "sale3", "sale4"), code = c(100, 101, 102, 103), item = c("a", "b", "c", "d"), stok = c(200, 300, 100, 50))
db_df <- data.frame(code = c(100, 102), item1 = c("a1", "a2"), code_item1 = c(1001, 1002), amount_item1 = c(2,1), item2 = c("a2", "a3"), code_item2 = c(1002, 1003), amount_item2 = c(1,1))

result_df <- left_join(my_df, db_df, by = c("code" = "code"))
result_df

  promo code item stok item1 code_item1 amount_item1 item2 code_item2 amount_item2
1 sale1  100    a  200    a1       1001            2    a2       1002            1
2 sale2  101    b  300  <NA>         NA           NA  <NA>         NA           NA
3 sale3  102    c  100    a2       1002            1    a3       1003            1
4 sale4  103    d   50  <NA>         NA           NA  <NA>         NA           NA
>
</code>```

EDIT: Related to your comment, you can do the multiplying after the left_join as well, there is no need to do it before:

```<code>result_df$amount_item1 <- result_df$amount_item1 * result_df$stok
result_df$amount_item2 <- result_df$amount_item2 * result_df$stok
</code>```

Body:
I want to lookup value from a database and make some new columns in a file
actually I have a file like this

promo code item stok
sale1  100   a   200
sale2  101   b   300
sale3  102   c   100
sale4  103   d    50

and a database looks like this

code item1 code_item1 amount_item1 item2 code_item2 amount_item2
100   a1     1001          2        a2     1002          1
102   a2     1002          1        a3     1003          1

and then I want to add my first file several columns which are taken from the database

promo code item stok item1 code_item1 amount_item1 item2 code_item2 amount_item2
sale1  100   a   200   a1     1001          400        a2     1002          200
sale2  101   b   300
sale3  102   c   100   a2     1002          100        a3     1003          100
sale4  103   d    50

How do I do this?

Body:
You can use left_join() from dplyr:

library(dplyr)

my_df <- data.frame(promo = c("sale1", "sale2", "sale3", "sale4"), code = c(100, 101, 102, 103), item = c("a", "b", "c", "d"), stok = c(200, 300, 100, 50))
db_df <- data.frame(code = c(100, 102), item1 = c("a1", "a2"), code_item1 = c(1001, 1002), amount_item1 = c(2,1), item2 = c("a2", "a3"), code_item2 = c(1002, 1003), amount_item2 = c(1,1))

result_df <- left_join(my_df, db_df, by = c("code" = "code"))
result_df

  promo code item stok item1 code_item1 amount_item1 item2 code_item2 amount_item2
1 sale1  100    a  200    a1       1001            2    a2       1002            1
2 sale2  101    b  300  <NA>         NA           NA  <NA>         NA           NA
3 sale3  102    c  100    a2       1002            1    a3       1003            1
4 sale4  103    d   50  <NA>         NA           NA  <NA>         NA           NA
>

EDIT: Related to your comment, you can do the multiplying after the left_join as well, there is no need to do it before:

result_df$amount_item1 <- result_df$amount_item1 * result_df$stok
result_df$amount_item2 <- result_df$amount_item2 * result_df$stok


来源: stackexchange

问:
Detect browser refresh in an Angular project
I want to detect when a page is refreshed using a router  in my single-page application (Angular project).

Is there an alternate way?

答:
I want to detect when page is refresh using router

You add a top level resolver to the router. If you have a single top level router, then it will only be resolved once and children will handle page navigation. Each time the resolver is resolved is equal to a page refresh in the browser.

```<code>const routes: Routes = [
  {
    path: '',
    component: TopComponent,
    resolve: { loaded: PageLoadedResolver },
    children: [
         ...
    ]
  }
];
</code>```

There are many other ways of detecting a page load event in Angular.

The constructor of your AppModule.

```<code>@NgModule({...})
export class AppModule {
     public constructor() {
          console.log('page loaded');
     }
}
</code>```

A service injected into the root that is used at least once.

```<code>@Injector({provideIn: 'root'})
export class MyService {
     public constructor() {
          console.log('page loaded');
     }
}
</code>```

There is also the main.ts file which bootstraps the Angular application.

```<code>    platformBrowserDynamic().bootstrapModule(AppModule)
        .then(() => console.log('page loaded'))
        .catch(err => console.error(err));
</code>```

Basically, anywhere there is JavaScript that runs once...

ContentLicense: CC BY-SA 4.0

Body:
I want to detect when page is refresh using router

You add a top level resolver to the router. If you have a single top level router, then it will only be resolved once and children will handle page navigation. Each time the resolver is resolved is equal to a page refresh in the browser.

const routes: Routes = [
  {
    path: '',
    component: TopComponent,
    resolve: { loaded: PageLoadedResolver },
    children: [
         ...
    ]
  }
];

There are many other ways of detecting a page load event in Angular.

The constructor of your AppModule.

@NgModule({...})
export class AppModule {
     public constructor() {
          console.log('page loaded');
     }
}

A service injected into the root that is used at least once.

@Injector({provideIn: 'root'})
export class MyService {
     public constructor() {
          console.log('page loaded');
     }
}

There is also the main.ts file which bootstraps the Angular application.

    platformBrowserDynamic().bootstrapModule(AppModule)
        .then(() => console.log('page loaded'))
        .catch(err => console.error(err));

Basically, anywhere there is JavaScript that runs once...


问:
Getting the Length of a Text widget
I'm trying to get the length of the text inside a Text widget and len() does not work.

I have tried doing this:

```<code>variable = len(text_widget)
</code>```

which does not work.

This is the error I am getting:

```<code>AttributeError: Text instance has no attribute '__len__'
</code>```

This is the creation of text_widget:

```<code>self.text_widget= Text(self.frame1, font=("Arial", 20), fg="white", bg="#DAA520", height = 12)
</code>```

答:
to get the text from the widget use

```<code>actual_text = text_widget.get(1.0, END)
</code>```

then you can do

```<code>len(actual_text)
</code>```

Title: Getting the Length of a Text widget

Body:
I'm trying to get the length of the text inside a Text widget and len() does not work.

I have tried doing this:

variable = len(text_widget)

which does not work.

This is the error I am getting:

AttributeError: Text instance has no attribute '__len__'

This is the creation of text_widget:

self.text_widget= Text(self.frame1, font=("Arial", 20), fg="white", bg="#DAA520", height = 12)

Body:
to get the text from the widget use

actual_text = text_widget.get(1.0, END)

then you can do

len(actual_text)


问:
How can i maintain position in recycler adapter when removing an item?
I have a recycler adapter, in the view item there is a delete button (del).
I use the following code in click event.

```<code>@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
    holder.del.setTag(position);
    holder.del.setOnClickLintener(new View.OnClickListener() {

        @Override
        public void onClick(View v)
        {
            int pos= (int) v.getTag();
            //remove view item
            notifyItemRemoved(pos);
            //remove equivalent arraylist item
            listitems.remove(pos);
        }
    });
}
</code>```

This does not update the tag values in the view items i assume because the onBindViewHolder() is not called for the already existing items. How can i update the values or is there a different approach to this.

答:
Don't use the position as the tag if you want to use notifyItemRemoved and keep the removing animation. Use the Object in your items as the tag and find it when you need the index.</p>

```<code>@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
    Object item = listitems.get(position);
    holder.del.setTag(item);
    holder.del.setOnClickLintener(new View.OnClickListener() {

        @Override
        public void onClick(View v)
        {
            Object item = (Object) v.getTag();
            int pos = listitems.indexOf(item);
            if (pos >= 0) {
             //remove equivalent arraylist item
             listitems.remove(pos);
             //remove view item
             notifyItemRemoved(pos);
           }
        }
    });
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a recycler adapter, in the view item there is a delete button (del).
I use the following code in click event.

@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
    holder.del.setTag(position);
    holder.del.setOnClickLintener(new View.OnClickListener() {

        @Override
        public void onClick(View v)
        {
            int pos= (int) v.getTag();
            //remove view item
            notifyItemRemoved(pos);
            //remove equivalent arraylist item
            listitems.remove(pos);
        }
    });
}

This does not update the tag values in the view items i assume because the onBindViewHolder() is not called for the already existing items. How can i update the values or is there a different approach to this.

Body:
Don't use the position as the tag if you want to use notifyItemRemoved and keep the removing animation. Use the Object in your items as the tag and find it when you need the index.

@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
    Object item = listitems.get(position);
    holder.del.setTag(item);
    holder.del.setOnClickLintener(new View.OnClickListener() {

        @Override
        public void onClick(View v)
        {
            Object item = (Object) v.getTag();
            int pos = listitems.indexOf(item);
            if (pos >= 0) {
             //remove equivalent arraylist item
             listitems.remove(pos);
             //remove view item
             notifyItemRemoved(pos);
           }
        }
    });
}


问:
How to link multiple frames in java
I created Login and Register frames separated which both connected to MySQL. If I just run the register frame, I can insert a new user to the database. However, If I run the login frame which includes the register frame inside and press register, the button that adds in the register frame does not work even the text fields are filled out.</p>

```<code>//this is Login frame class

package YASAR;

import java.awt.BorderLayout;
import java.sql.*;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class GirisEkrani extends JFrame {
    static JButton btnKullancEkle = new JButton("Kullan\u0131c\u0131 Ekle");
    public static JPanel contentPane;
    private static JTextField textField;
    private static JComboBox comboBox = new JComboBox();
    private static JButton btnBalan = new JButton("Ba\u011Flan");
    private static  JLabel lblParola = new JLabel("Parola :");
    private static JLabel lblXaampeBalanlamad = new JLabel("Xaampe Ba\u011Flan\u0131lamad\u0131");
    //private static KullaniciEkle ke=new KullaniciEkle();
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                lblXaampeBalanlamad.setVisible(false);
                try {

                    GirisEkrani frame = new GirisEkrani();
                    frame.setVisible(true);

                    try {
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/yasar","ozkan","******");

        btnKullancEkle.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.setVisible(false);
                KullaniciEkle ke=new KullaniciEkle();
                ke.setVisible(true);

            }
        });

        btnBalan.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.setVisible(false);

                deneme abc=new deneme();
                abc.setVisible(true);

            }
        });

        con.close();
                    }

        catch(SQLException e) {

            textField.setEditable(false);
            btnKullancEkle.setEnabled(false);
            comboBox.setEnabled(false);
            btnBalan.setEnabled(false);
            lblParola.setVisible(false);
            lblXaampeBalanlamad.setVisible(true);

            e.printStackTrace();
        }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * Create the frame.
     */
    public GirisEkrani() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 286, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textField = new JTextField();
        textField.setBounds(74, 129, 124, 19);
        contentPane.add(textField);
        textField.setColumns(10);

        comboBox.setBounds(74, 42, 124, 21);
        contentPane.add(comboBox);

        btnBalan.setBounds(74, 184, 124, 33);
        contentPane.add(btnBalan);

        btnKullancEkle.setBounds(74, 227, 124, 26);
        contentPane.add(btnKullancEkle);

        lblParola.setBounds(10, 132, 45, 13);
        contentPane.add(lblParola);
        lblXaampeBalanlamad.setBounds(74, 90, 162, 29);

        contentPane.add(lblXaampeBalanlamad);
    }

}
</code>```

```<code>// And this is register frame class where I add user

package YASAR;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.sql.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;

public class KullaniciEkle extends JFrame {

    public static JPanel contentPane;
    public static JTextField textField;
    public static JTextField textField_1;
    public static JTextField textField_2;
    public static JLabel lblIsim;
    public static JLabel lblSoyisim;
    public static JButton btnNewButton = new JButton("Ekle");

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    KullaniciEkle frame = new KullaniciEkle();
                    frame.setVisible(true);

                    try {
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/yasar","ozkan","******");

    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        String input="INSERT INTO kullanicilar (TC,name,surname) VALUES(?,?,?)";
            try {

                PreparedStatement ps=con.prepareStatement(input);

                ps.setInt(1, Integer.parseInt(textField.getText()));
                ps.setString(2, textField_1.getText());
                ps.setString(3, textField_2.getText());

                //ps.execute();
                if(ps.executeUpdate()>0) {
                    JOptionPane.showMessageDialog(null, "user added","user add",JOptionPane.OK_CANCEL_OPTION);
                }

            }catch(SQLException f) {
                f.printStackTrace();
            }

            finally {System.out.println("pressed");}

                frame.setVisible(false);
                new GirisEkrani().setVisible(true);

                }
    });

                    }
                        catch(SQLException e) {
                            e.printStackTrace();
                        }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public KullaniciEkle() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 285, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textField = new JTextField();
        textField.setBounds(87, 67, 96, 19);
        contentPane.add(textField);
        textField.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setBounds(87, 112, 96, 19);
        contentPane.add(textField_1);
        textField_1.setColumns(10);

        textField_2 = new JTextField();
        textField_2.setBounds(87, 160, 96, 19);
        contentPane.add(textField_2);
        textField_2.setColumns(10);
        btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 10));

        btnNewButton.setBounds(93, 232, 85, 21);
        contentPane.add(btnNewButton);

        JLabel lblTc = new JLabel("TC");
        lblTc.setFont(new Font("Tahoma", Font.PLAIN, 10));
        lblTc.setBounds(10, 70, 45, 13);
        contentPane.add(lblTc);

        lblIsim = new JLabel("\u0130sim");
        lblIsim.setFont(new Font("Tahoma", Font.PLAIN, 10));
        lblIsim.setBounds(10, 115, 45, 13);
        contentPane.add(lblIsim);

        lblSoyisim = new JLabel("Soyisim");
        lblSoyisim.setFont(new Font("Tahoma", Font.PLAIN, 10));
        lblSoyisim.setBounds(10, 163, 45, 13);
        contentPane.add(lblSoyisim);
    }

}

</code>```

答:
You need to put this code inside your Constructor.

```<code>btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        String input="INSERT INTO kullanicilar (TC,name,surname) VALUES(?,?,?)";
            try {

                PreparedStatement ps=con.prepareStatement(input);

                ps.setInt(1, Integer.parseInt(textField.getText()));
                ps.setString(2, textField_1.getText());
                ps.setString(3, textField_2.getText());

                //ps.execute();
                if(ps.executeUpdate()>0) {
                    JOptionPane.showMessageDialog(null, "user added","user add",JOptionPane.OK_CANCEL_OPTION);
                }

            }catch(SQLException f) {
                f.printStackTrace();
            }

            finally {System.out.println("pressed");}

                frame.setVisible(false);
                new GirisEkrani().setVisible(true);

                }
    });
</code>```

Finally, it will look like this,

```<code>import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.sql.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;

public class KullaniciEkle extends JFrame {

    public static JPanel contentPane;
    public static JTextField textField;
    public static JTextField textField_1;
    public static JTextField textField_2;
    public static JLabel lblIsim;
    public static JLabel lblSoyisim;
    public static JButton btnNewButton = new JButton("Ekle");

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    KullaniciEkle frame = new KullaniciEkle();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public KullaniciEkle() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 285, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textField = new JTextField();
        textField.setBounds(87, 67, 96, 19);
        contentPane.add(textField);
        textField.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setBounds(87, 112, 96, 19);
        contentPane.add(textField_1);
        textField_1.setColumns(10);

        textField_2 = new JTextField();
        textField_2.setBounds(87, 160, 96, 19);
        contentPane.add(textField_2);
        textField_2.setColumns(10);
        btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 10));

        btnNewButton.setBounds(93, 232, 85, 21);
        contentPane.add(btnNewButton);

        JLabel lblTc = new JLabel("TC");
        lblTc.setFont(new Font("Tahoma", Font.PLAIN, 10));
        lblTc.setBounds(10, 70, 45, 13);
        contentPane.add(lblTc);

        lblIsim = new JLabel("\u0130sim");
        lblIsim.setFont(new Font("Tahoma", Font.PLAIN, 10));
        lblIsim.setBounds(10, 115, 45, 13);
        contentPane.add(lblIsim);

        lblSoyisim = new JLabel("Soyisim");
        lblSoyisim.setFont(new Font("Tahoma", Font.PLAIN, 10));
        lblSoyisim.setBounds(10, 163, 45, 13);
        contentPane.add(lblSoyisim);

        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                btnNewButtonActionPerformed(e);
            }
        });

    }

    private void btnNewButtonActionPerformed(ActionEvent evt) {
        try {
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yasar", "ozkan", "******");

            String input = "INSERT INTO kullanicilar (TC,name,surname) VALUES(?,?,?)";
            try {

                PreparedStatement ps = con.prepareStatement(input);

                ps.setInt(1, Integer.parseInt(textField.getText()));
                ps.setString(2, textField_1.getText());
                ps.setString(3, textField_2.getText());

                //ps.execute();
                if (ps.executeUpdate() > 0) {
                    JOptionPane.showMessageDialog(null, "user added", "user add", JOptionPane.OK_CANCEL_OPTION);
                }

            } catch (SQLException f) {
                f.printStackTrace();
            } finally {
                System.out.println("pressed");
            }

            //Instead of frame use this keyword
            this.setVisible(false);
            new GirisEkrani().setVisible(true);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
</code>```

NOTE:- This is not the best practice to communicate with the database.

Title: How to link multiple frames in java

Body:
I created Login and Register frames separated which both connected to MySQL. If I just run the register frame, I can insert a new user to the database. However, If I run the login frame which includes the register frame inside and press register, the button that adds in the register frame does not work even the text fields are filled out.

//this is Login frame class

package YASAR;

import java.awt.BorderLayout;
import java.sql.*;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class GirisEkrani extends JFrame {
    static JButton btnKullancEkle = new JButton("Kullan\u0131c\u0131 Ekle");
    public static JPanel contentPane;
    private static JTextField textField;
    private static JComboBox comboBox = new JComboBox();
    private static JButton btnBalan = new JButton("Ba\u011Flan");
    private static  JLabel lblParola = new JLabel("Parola :");
    private static JLabel lblXaampeBalanlamad = new JLabel("Xaampe Ba\u011Flan\u0131lamad\u0131");
    //private static KullaniciEkle ke=new KullaniciEkle();
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                lblXaampeBalanlamad.setVisible(false);
                try {

                    GirisEkrani frame = new GirisEkrani();
                    frame.setVisible(true);

                    try {
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/yasar","ozkan","******");

        btnKullancEkle.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.setVisible(false);
                KullaniciEkle ke=new KullaniciEkle();
                ke.setVisible(true);

            }
        });

        btnBalan.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.setVisible(false);

                deneme abc=new deneme();
                abc.setVisible(true);

            }
        });

        con.close();
                    }

        catch(SQLException e) {

            textField.setEditable(false);
            btnKullancEkle.setEnabled(false);
            comboBox.setEnabled(false);
            btnBalan.setEnabled(false);
            lblParola.setVisible(false);
            lblXaampeBalanlamad.setVisible(true);

            e.printStackTrace();
        }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * Create the frame.
     */
    public GirisEkrani() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 286, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textField = new JTextField();
        textField.setBounds(74, 129, 124, 19);
        contentPane.add(textField);
        textField.setColumns(10);

        comboBox.setBounds(74, 42, 124, 21);
        contentPane.add(comboBox);

        btnBalan.setBounds(74, 184, 124, 33);
        contentPane.add(btnBalan);

        btnKullancEkle.setBounds(74, 227, 124, 26);
        contentPane.add(btnKullancEkle);

        lblParola.setBounds(10, 132, 45, 13);
        contentPane.add(lblParola);
        lblXaampeBalanlamad.setBounds(74, 90, 162, 29);

        contentPane.add(lblXaampeBalanlamad);
    }

}

// And this is register frame class where I add user

package YASAR;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.sql.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;

public class KullaniciEkle extends JFrame {

    public static JPanel contentPane;
    public static JTextField textField;
    public static JTextField textField_1;
    public static JTextField textField_2;
    public static JLabel lblIsim;
    public static JLabel lblSoyisim;
    public static JButton btnNewButton = new JButton("Ekle");

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    KullaniciEkle frame = new KullaniciEkle();
                    frame.setVisible(true);

                    try {
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/yasar","ozkan","******");

    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        String input="INSERT INTO kullanicilar (TC,name,surname) VALUES(?,?,?)";
            try {

                PreparedStatement ps=con.prepareStatement(input);

                ps.setInt(1, Integer.parseInt(textField.getText()));
                ps.setString(2, textField_1.getText());
                ps.setString(3, textField_2.getText());

                //ps.execute();
                if(ps.executeUpdate()>0) {
                    JOptionPane.showMessageDialog(null, "user added","user add",JOptionPane.OK_CANCEL_OPTION);
                }

            }catch(SQLException f) {
                f.printStackTrace();
            }

            finally {System.out.println("pressed");}

                frame.setVisible(false);
                new GirisEkrani().setVisible(true);

                }
    });

                    }
                        catch(SQLException e) {
                            e.printStackTrace();
                        }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public KullaniciEkle() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 285, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textField = new JTextField();
        textField.setBounds(87, 67, 96, 19);
        contentPane.add(textField);
        textField.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setBounds(87, 112, 96, 19);
        contentPane.add(textField_1);
        textField_1.setColumns(10);

        textField_2 = new JTextField();
        textField_2.setBounds(87, 160, 96, 19);
        contentPane.add(textField_2);
        textField_2.setColumns(10);
        btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 10));

        btnNewButton.setBounds(93, 232, 85, 21);
        contentPane.add(btnNewButton);

        JLabel lblTc = new JLabel("TC");
        lblTc.setFont(new Font("Tahoma", Font.PLAIN, 10));
        lblTc.setBounds(10, 70, 45, 13);
        contentPane.add(lblTc);

        lblIsim = new JLabel("\u0130sim");
        lblIsim.setFont(new Font("Tahoma", Font.PLAIN, 10));
        lblIsim.setBounds(10, 115, 45, 13);
        contentPane.add(lblIsim);

        lblSoyisim = new JLabel("Soyisim");
        lblSoyisim.setFont(new Font("Tahoma", Font.PLAIN, 10));
        lblSoyisim.setBounds(10, 163, 45, 13);
        contentPane.add(lblSoyisim);
    }

}

Body:
You need to put this code inside your Constructor.

btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        String input="INSERT INTO kullanicilar (TC,name,surname) VALUES(?,?,?)";
            try {

                PreparedStatement ps=con.prepareStatement(input);

                ps.setInt(1, Integer.parseInt(textField.getText()));
                ps.setString(2, textField_1.getText());
                ps.setString(3, textField_2.getText());

                //ps.execute();
                if(ps.executeUpdate()>0) {
                    JOptionPane.showMessageDialog(null, "user added","user add",JOptionPane.OK_CANCEL_OPTION);
                }

            }catch(SQLException f) {
                f.printStackTrace();
            }

            finally {System.out.println("pressed");}

                frame.setVisible(false);
                new GirisEkrani().setVisible(true);

                }
    });

Finally, it will look like this,

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.sql.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;

public class KullaniciEkle extends JFrame {

    public static JPanel contentPane;
    public static JTextField textField;
    public static JTextField textField_1;
    public static JTextField textField_2;
    public static JLabel lblIsim;
    public static JLabel lblSoyisim;
    public static JButton btnNewButton = new JButton("Ekle");

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    KullaniciEkle frame = new KullaniciEkle();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public KullaniciEkle() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 285, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textField = new JTextField();
        textField.setBounds(87, 67, 96, 19);
        contentPane.add(textField);
        textField.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setBounds(87, 112, 96, 19);
        contentPane.add(textField_1);
        textField_1.setColumns(10);

        textField_2 = new JTextField();
        textField_2.setBounds(87, 160, 96, 19);
        contentPane.add(textField_2);
        textField_2.setColumns(10);
        btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 10));

        btnNewButton.setBounds(93, 232, 85, 21);
        contentPane.add(btnNewButton);

        JLabel lblTc = new JLabel("TC");
        lblTc.setFont(new Font("Tahoma", Font.PLAIN, 10));
        lblTc.setBounds(10, 70, 45, 13);
        contentPane.add(lblTc);

        lblIsim = new JLabel("\u0130sim");
        lblIsim.setFont(new Font("Tahoma", Font.PLAIN, 10));
        lblIsim.setBounds(10, 115, 45, 13);
        contentPane.add(lblIsim);

        lblSoyisim = new JLabel("Soyisim");
        lblSoyisim.setFont(new Font("Tahoma", Font.PLAIN, 10));
        lblSoyisim.setBounds(10, 163, 45, 13);
        contentPane.add(lblSoyisim);

        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                btnNewButtonActionPerformed(e);
            }
        });

    }

    private void btnNewButtonActionPerformed(ActionEvent evt) {
        try {
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yasar", "ozkan", "******");

            String input = "INSERT INTO kullanicilar (TC,name,surname) VALUES(?,?,?)";
            try {

                PreparedStatement ps = con.prepareStatement(input);

                ps.setInt(1, Integer.parseInt(textField.getText()));
                ps.setString(2, textField_1.getText());
                ps.setString(3, textField_2.getText());

                //ps.execute();
                if (ps.executeUpdate() > 0) {
                    JOptionPane.showMessageDialog(null, "user added", "user add", JOptionPane.OK_CANCEL_OPTION);
                }

            } catch (SQLException f) {
                f.printStackTrace();
            } finally {
                System.out.println("pressed");
            }

            //Instead of frame use this keyword
            this.setVisible(false);
            new GirisEkrani().setVisible(true);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

NOTE:- This is not the best practice to communicate with the database.


问:
Display test parameters input values unabridged in Visual Studio
Is there a way to get Visual Studio (2017 Enterprise) to show all values of input parameters with which the test was launched?

In the output window, there are just three dots after certain length, just as in Test explorer (which I have to drag over 2 monitors to see that and the Copy All button there should be named Copy some).

Right now I see in the output and test explorer:

```<code>27/05/2019 12:55:29 Error] [xUnit.net 00:00:03.9604849]     SomeNamespace.SomeTestName(sut: SomeClass { }, someString: "spz5cf1f13d-6e3f-4f86-9a6a-5bc4cf9d0fca", foo: Foo { SomeBool = True, SomeId = 138, SomeString = "Duvodf6d90c61-f090-4f22-9e2e-37e2062bb848", SomeString = "ESSKa62ce76d-d56a-40d8-904a-fef1884ac86a", ExtensionData = null, ... }) [FAIL]
</code>```

I'd like to see all values within Foo class, not "...".

I tried the "Test" options in VS, but nothing in there influences this (including logging level).

Test input is generated by AutoFixture. Sometimes the test passes, sometimes it fails.
Also it is integration test, which contacts web service, which doesn't throw very nice exceptions and basically just tells me "Somehting is wrong".
If I invoke test in debuger enough times, I'll have example o failing input, but there should be an easier way.

答:
Apparenlty you need implement ToString in test parameters. The Foo class in question was generated DTO, some component (xUnit?) generated its string representation via reflection with limited length and that was displayed in test explorer and output window.

Once you implement proper ToString, Test Explorer is still showing abriged text, but Output window contains whole result of ToString.

Body:
Is there a way to get Visual Studio (2017 Enterprise) to show all values of input parameters with which the test was launched?

In the output window, there are just three dots after certain length, just as in Test explorer (which I have to drag over 2 monitors to see that and the Copy All button there should be named Copy some).

Right now I see in the output and test explorer:

27/05/2019 12:55:29 Error] [xUnit.net 00:00:03.9604849]     SomeNamespace.SomeTestName(sut: SomeClass { }, someString: "spz5cf1f13d-6e3f-4f86-9a6a-5bc4cf9d0fca", foo: Foo { SomeBool = True, SomeId = 138, SomeString = "Duvodf6d90c61-f090-4f22-9e2e-37e2062bb848", SomeString = "ESSKa62ce76d-d56a-40d8-904a-fef1884ac86a", ExtensionData = null, ... }) [FAIL]

I'd like to see all values within Foo class, not "...".

I tried the "Test" options in VS, but nothing in there influences this (including logging level).

Test input is generated by AutoFixture. Sometimes the test passes, sometimes it fails.
Also it is integration test, which contacts web service, which doesn't throw very nice exceptions and basically just tells me "Somehting is wrong".
If I invoke test in debuger enough times, I'll have example o failing input, but there should be an easier way.


问:
How convert Bitmap to byte array and back without quality reduction?
When I convert a picture into bytes and back, the quality deteriorates a lot. How to do it without reducing quality?

I need to save the photo in the database or send it to the server. I can consider other options to do this.

```<code>public static byte[] fromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    return stream.toByteArray();
}
public static Bitmap toBitmap(byte[] bytes) {
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
</code>```

答: It's not a good way to save the picture in the database directly. The best way is to upload pictures to the server in a directory and save the picture path in the database. Here you can find out a complete tutorial to upload the picture on the server and save its path in the MYSQL database.</p>

Body:
When I convert a picture into bytes and back, the quality deteriorates a lot. How to do it without reducing quality?

I need to save the photo in the database or send it to the server. I can consider other options to do this.

public static byte[] fromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    return stream.toByteArray();
}
public static Bitmap toBitmap(byte[] bytes) {
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}


问:
How to move image around square
I have a square image (like a board) with 10 fields each side. I am trying to move around this board, stepping into fields(like token/pawn in board game, one step is one filed). After 10 steps I have to change direction (up, left, right, down). I am trying to do any animations, change image position in every iterate in loop but it is working only once.

Example:

```<code>for (int i = 0; i < range; ++i) {
            asX = token.getX();
            asY = token.getY();
            moveLength = 2.5f;
            if (1 case) {
                token.animate().x(asX - (2.5f * token.getWidth())).y(asY);
            } else if (2 case) {
                token.animate().x(asX - (2.5f * token.getWidth())).y(asY);
            } else if (3 case) {
                token.animate().x(asX - (2.5f * token.getWidth())).y(asY);
            } else if (4 case) {
              token.animate().x(asX - (2.5f * token.getWidth())).y(asY);
            }
            position++;
            token.invalidate();
        }
</code>```

```
range is a number of moves,
1 case - move left,
2 case - move up,
3 case - move rigth,
4 case - move down
```

so for example when range=6 and pos=0(token at the starting field), token should move by 6 fields to the left(cause pos < 10 and range also < 10), next when range=8 and pos=6, token should move by 4 fields to the left and then 4 fileds up etc.
It move only by one filed, not range.
Any idea?

答:
Use ObjectAnimator class has new constructors that enable you to animate coordinates

for more please read this

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  Path path = new Path();
  path.arcTo(0f, 0f, 1000f, 1000f, 270f, -180f, true);
  ObjectAnimator animator = ObjectAnimator.ofFloat(view, View.X, View.Y, path);
  animator.setDuration(2000);
  animator.start();
} else {
  // Create animator without using curved path
}
</code>```

Title: How to move image around square

Body:
I have a square image (like a board) with 10 fields each side. I am trying to move around this board, stepping into fields(like token/pawn in board game, one step is one filed). After 10 steps I have to change direction (up, left, right, down). I am trying to do any animations, change image position in every iterate in loop but it is working only once.

Example:

for (int i = 0; i < range; ++i) {
            asX = token.getX();
            asY = token.getY();
            moveLength = 2.5f;
            if (1 case) {
                token.animate().x(asX - (2.5f * token.getWidth())).y(asY);
            } else if (2 case) {
                token.animate().x(asX - (2.5f * token.getWidth())).y(asY);
            } else if (3 case) {
                token.animate().x(asX - (2.5f * token.getWidth())).y(asY);
            } else if (4 case) {
              token.animate().x(asX - (2.5f * token.getWidth())).y(asY);
            }
            position++;
            token.invalidate();
        }

range is a number of moves,
1 case - move left,
2 case - move up,
3 case - move rigth,
4 case - move down

so for example when range=6 and pos=0(token at the starting field), token should move by 6 fields to the left(cause pos < 10 and range also < 10), next when range=8 and pos=6, token should move by 4 fields to the left and then 4 fileds up etc.
It move only by one filed, not range.
Any idea?

Body:
Use ObjectAnimator class has new constructors that enable you to animate coordinates

for more please read this

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  Path path = new Path();
  path.arcTo(0f, 0f, 1000f, 1000f, 270f, -180f, true);
  ObjectAnimator animator = ObjectAnimator.ofFloat(view, View.X, View.Y, path);
  animator.setDuration(2000);
  animator.start();
} else {
  // Create animator without using curved path
}


问:
How to sort data which mix text and number?
I have a data which will show as the table and using orderBy(lodash) to sort data but it's not working as I want.

Now, I code as
const data = orderBy(realData, ['name'], ['asc'])

Here's my data
input:
[{name: 'A1'},{name:'A2'},{name: 'A21'},{name:'B10'},{name: 'A100'},{name:'A22'},{name: 'B32'},{name:'A3'}]

The issue is 'orderBy' sort data as it text(ASCII sorting)
current output:
[{name: 'A1'},{name: 'A100'},{name:'A2'},{name: 'A21'},{name:'A22'},{name:'A3'},{name:'B10'},{name: 'B32'}]

but I would like the data output like this

[{name: 'A1'},{name:'A2'},{name:'A3'},{name: 'A21'},{name:'A22'},{name: 'A100'},{name:'B10'},{name: 'B32'}]

If anyone have any suggestion, please help.

Thank you.

答:
An easy to understand way is like this:</p>

```<code>data.sort((a, b) => {
  const listA = a.name.trim().split('');
  const listB = b.name.trim().split('');

  const categoryA = listA.splice(0, 1);
  const categoryB = listB.splice(0, 1);

  const numberA = listA.join('');
  const numberB = listB.join('');

  if (categoryA > categoryB) return 1;
  if (categoryA < categoryB) return -1;

  return numberA - numberB;
});
</code>```

Body:
An easy to understand way is like this:

data.sort((a, b) => {
  const listA = a.name.trim().split('');
  const listB = b.name.trim().split('');

  const categoryA = listA.splice(0, 1);
  const categoryB = listB.splice(0, 1);

  const numberA = listA.join('');
  const numberB = listB.join('');

  if (categoryA > categoryB) return 1;
  if (categoryA < categoryB) return -1;

  return numberA - numberB;
});


问:
How to create collapse menu using Angular Material?
In documentation of Angular Material there is cool feature. Menu with subcategory which can be expanded/collapsed.

Is it possible to create it using some component? Or I have to do it myself from scratch? Or maybe you can suggest me some package that save my time.

答:
I tried to achieve this myself with a side-nav.
Maybe it can save you some time.

The nav-items follows a simple interface:

```<code>interface NavItem {
displayName: string;
disabled?: boolean;
iconName: string;
route?: string;
children?: NavItem[];}
</code>```

And then in the component.html the main idea is to add the nav-items recursively (*ngFor).
Use mat-accordions for each category and then use another *ngFor to get the children:

```<code><mat-nav-list>
<span *ngFor="let item of menu">
  <span *ngIf="item.children && item.children.length > 0">
    <mat-accordion>
      <mat-expansion-panel>
        <mat-expansion-panel-header>
          <mat-panel-title>
            <!-- Cabeceras del submenu -->
            <div fxLayout="row" fxLayoutAlign="space-between center" >
              <mat-icon>{{item.iconName}}</mat-icon>
              {{item.displayName}}
            </div>
          </mat-panel-title>
        </mat-expansion-panel-header>
        <span *ngFor="let child of item.children">
          <mat-list-item routerLink="[child.route]">
            <!-- Entradas de cada submenú  -->
            <div fxLayout="row" fxLayoutAlign="space-between center" >
              <mat-icon>{{child.iconName}}</mat-icon>
              {{child.displayName}}
            </div>
          </mat-list-item>
        </span>
      </mat-expansion-panel>
    </mat-accordion>
  </span>
  <span *ngIf="!item.children || item.children.length === 0">
    <mat-list-item routerLink="[item.route]">
      <!-- Entradas principales -->
      <div fxLayout="row" fxLayoutAlign="space-between center">
        <mat-icon>{{item.iconName}}</mat-icon>
        {{item.displayName}}
      </div>
    </mat-list-item>
  </span>
</span>
</code>```

Have a look: https://stackblitz.com/edit/angular-side-nav-dynamic-expansive-menu

Body:
I tried to achieve this myself with a side-nav.
Maybe it can save you some time.

The nav-items follows a simple interface:

interface NavItem {
displayName: string;
disabled?: boolean;
iconName: string;
route?: string;
children?: NavItem[];}

And then in the component.html the main idea is to add the nav-items recursively (*ngFor).
Use mat-accordions for each category and then use another *ngFor to get the children:

<mat-nav-list>
<span *ngFor="let item of menu">
  <span *ngIf="item.children && item.children.length > 0">
    <mat-accordion>
      <mat-expansion-panel>
        <mat-expansion-panel-header>
          <mat-panel-title>
            <!-- Cabeceras del submenu -->
            <div fxLayout="row" fxLayoutAlign="space-between center" >
              <mat-icon>{{item.iconName}}</mat-icon>
              {{item.displayName}}
            </div>
          </mat-panel-title>
        </mat-expansion-panel-header>
        <span *ngFor="let child of item.children">
          <mat-list-item routerLink="[child.route]">
            <!-- Entradas de cada submenú  -->
            <div fxLayout="row" fxLayoutAlign="space-between center" >
              <mat-icon>{{child.iconName}}</mat-icon>
              {{child.displayName}}
            </div>
          </mat-list-item>
        </span>
      </mat-expansion-panel>
    </mat-accordion>
  </span>
  <span *ngIf="!item.children || item.children.length === 0">
    <mat-list-item routerLink="[item.route]">
      <!-- Entradas principales -->
      <div fxLayout="row" fxLayoutAlign="space-between center">
        <mat-icon>{{item.iconName}}</mat-icon>
        {{item.displayName}}
      </div>
    </mat-list-item>
  </span>
</span>

Have a look: https://stackblitz.com/edit/angular-side-nav-dynamic-expansive-menu


问:
Deep destructuring with saving values
How to destruct and save nested values?

const obj = {
    foo: {
        bar: 'Hi!'
    }
};

const { foo: { bar } } = obj;

console.log(bar); // Hi!
console.log(foo); // foo is not defined :(```

How to keep foo value?

答:
Just take foo as target, too.

const obj = {
    foo: {
        bar: 'Hi!'
    }
};

const { foo: { bar }, foo } = obj;

console.log(bar); // Hi!
console.log(foo); // foo```

Title: Deep destructuring with saving values

Body:
How to destruct and save nested values?

const obj = {
    foo: {
        bar: 'Hi!'
    }
};

const { foo: { bar } } = obj;

console.log(bar); // Hi!
console.log(foo); // foo is not defined :(

How to keep foo value?


问:
How to customise Django's default email template? (smtpd)
How to customise Django's default email template?

urls.py

```<code>path('change-password/', views.change_password, name='change-password'),
path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'),
     name='reset-password'),
path('reset-password/done/', PasswordResetDoneView.as_view(), name='password_reset_done'),
path('reset-password/confirm/<uidb64>/<token>/',
     PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
path('reset-password/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'),
</code>```

I was hoping to customise the django email template and put it as a template_name or similar in one of the correct paths above? Any help would be appreciated.

Thanks

答:
In order to change the email default template, you'll need to:

Point the template dirs' search directive to your application first, then to Django's default templates if you haven't done:

   TEMPLATES = [
       {
           'BACKEND': 'django.template.backends.django.DjangoTemplates',
           'DIRS': [os.path.join(BASE_DIR, 'templates')],
           'APP_DIRS': True,
           ...
       },
   ]

```

Make sure that you're editing the right template. It's the password_reset_email.html, you should create a template directory within your application called "registration", and then customize it the way for your likes. But don't forget to use the required fields such as URL token for validation in password reset.

So the directory and the structure should be app_dir/templates/registration/password_reset_email.html.

Body:
How to customise Django's default email template?

urls.py

path('change-password/', views.change_password, name='change-password'),
path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'),
     name='reset-password'),
path('reset-password/done/', PasswordResetDoneView.as_view(), name='password_reset_done'),
path('reset-password/confirm/<uidb64>/<token>/',
     PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
path('reset-password/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'),

I was hoping to customise the django email template and put it as a template_name or similar in one of the correct paths above? Any help would be appreciated.

Thanks

Body:
In order to change the email default template, you'll need to:

Point the template dirs' search directive to your application first, then to Django's default templates if you haven't done:

   TEMPLATES = [
       {
           'BACKEND': 'django.template.backends.django.DjangoTemplates',
           'DIRS': [os.path.join(BASE_DIR, 'templates')],
           'APP_DIRS': True,
           ...
       },
   ]

Make sure that you're editing the right template. It's the password_reset_email.html, you should create a template directory within your application called "registration", and then customize it the way for your likes. But don't forget to use the required fields such as URL token for validation in password reset.

So the directory and the structure should be app_dir/templates/registration/password_reset_email.html.


问:
Property 'intlTelInput' does not exist on type 'Window'
I am working with angular7. I need International Telephone Input (https://intl-tel-input.com/) for my website.

So i used the following comment to install the CDN.

```<code>npm uninstall ng2-tel-input --save
</code>```

After that i called the CSS and JS files in the angular.json

```<code>"styles": [
     "node_modules/intl-tel-input/build/css/intlTelInput.min.css",
      "src/styles.css"
],
"scripts": [
    "node_modules/intl-tel-input/build/js/utils.js",
    "node_modules/intl-tel-input/build/js/intlTelInput.min.js"
],
</code>```

Added the input field for the telephone number in "contactform.compenent.html"

```<code><input type="tel" class="form-control" value="" placeholder="Mobile number"
       id="telnumber-field" required>
</code>```

And Added the script for the telephone area in "app.compenent.ts"

```<code>ngOnInit(){

jQuery( document ).ready( function( $ ) {

    if(jQuery('#telnumber-field').length){
        var input = document.querySelector("#telnumber-field");
        window.intlTelInput(input, {
            preferredCountries: ['in'],
            separateDialCode: true
        });
    }

}); }
</code>```

But there is an error comes.

ERROR in src/app/app.component.ts(65,11): error TS2339: Property 'intlTelInput' does not exist on type 'Window'.

答:
At the time of typescript compilation intlTelInput object is not created on window object.change window type to any to skip property checking for window duration compilation. intlTelInput is visible once application is loaded in browser so application will work as expected.

```<code>  ngOnInit(){

   jQuery( document ).ready( function( $ ) {

    if(jQuery('#telnumber-field').length){
        var input = document.querySelector("#telnumber-field");
       (<any>window).intlTelInput(input, {
            preferredCountries: ['in'],
            separateDialCode: true
        });
    }

});
}
</code>```

Body:
I am working with angular7. I need International Telephone Input (https://intl-tel-input.com/) for my website.

So i used the following comment to install the CDN.

npm uninstall ng2-tel-input --save

After that i called the CSS and JS files in the angular.json

"styles": [
     "node_modules/intl-tel-input/build/css/intlTelInput.min.css",
      "src/styles.css"
],
"scripts": [
    "node_modules/intl-tel-input/build/js/utils.js",
    "node_modules/intl-tel-input/build/js/intlTelInput.min.js"
],

Added the input field for the telephone number in "contactform.compenent.html"

<input type="tel" class="form-control" value="" placeholder="Mobile number"
       id="telnumber-field" required>

And Added the script for the telephone area in "app.compenent.ts"

ngOnInit(){

jQuery( document ).ready( function( $ ) {

    if(jQuery('#telnumber-field').length){
        var input = document.querySelector("#telnumber-field");
        window.intlTelInput(input, {
            preferredCountries: ['in'],
            separateDialCode: true
        });
    }

}); }

But there is an error comes.

ERROR in src/app/app.component.ts(65,11): error TS2339: Property 'intlTelInput' does not exist on type 'Window'.

Body:
At the time of typescript compilation intlTelInput object is not created on window object.change window type to any to skip property checking for window duration compilation. intlTelInput is visible once application is loaded in browser so application will work as expected.

  ngOnInit(){

   jQuery( document ).ready( function( $ ) {

    if(jQuery('#telnumber-field').length){
        var input = document.querySelector("#telnumber-field");
       (<any>window).intlTelInput(input, {
            preferredCountries: ['in'],
            separateDialCode: true
        });
    }

});
}


问:
AWS Cognito - Logging end user activities for auditing
I am using Cognito for authentication. I am using the default sign-in page application for the end user to login to the application.

I need to log end-user activities related to the sign-in page for auditing purpose. Basically, I need to log when the user signed-up, signed-in, signed out and changed password. I can use triggers "Post Authentication Lambda Trigger" but forgot password and sign out events are missing. Could you please help me on how to achieve this?

答:
AWS Cognito Advanced Security Features provides this functionality. You can find more details here https://aws.amazon.com/blogs/security/how-to-use-new-advanced-security-features-for-amazon-cognito-user-pools/

Advanced Security Features


问:
PHP, javascript, ajax - communication between 2 users
Good day to all.

I need to do this:

When user X press a button user Y sees a photo. Before that user Y sees nothing.

I did this like this: I created a database on a mysql server and created a table with photos and flags. When user X presses the button I send an ajax request and change the flag to the corresponding photo. User Y also sends ajax request every 1 sec to see if anything has changed.

Sounds ok, looks ok, works... it does but to so ok. When 100000 users send 1 ajax request every 1 second the server crashes. First mysql server then apache.

So... my question is is there anyway to do this without so many ajax requests? Something like send the page with a certain "thing" that tells the browser to keep the same socket and send later the image? Something like a stream but instead of images to be html pages/images/whatever.

I know java applet would be a solution but I would need a php(for server side)+js(for client side) solution.

And yes I know that I'll probably get an "you can't" answer but it deserves a try.

答:
Because HTTP is stateless, you need to create a permanent or long-lasting socket connection between clients and server.

This is a chat application, written in PHP, AJAX and Ruby backend.

Web Chat application main page, more specifically the part about the socket server


问:
Can't validate form and refreshes page when I hit submit button django
I'm new to Django and learning some new things and I have a problem that I can't able to validate the contact form and page refreshes when I hit submit button. Can u please go through this code.

I cant able to validate contact form and I can able to validate and store values of join form but the contact form and everything are fine but I don't know where is the problem.

I'm using atom editor for Django

Here is forms.py

```<code>#forms.py

from django import forms
from django.core import validators
from index.models import *

class Contactform(forms.ModelForm):

    class Meta:
        model = Contact_Us
        exclude = ('date',)

    confirm_email = forms.EmailField()
    botcatcher = forms.CharField(required=False,
                                    widget=forms.HiddenInput,
                                    validators=[validators.MaxLengthValidator(0)])

    def clean(self):
        super(Contactform, self).clean()
        name = self.cleaned_data['fullname']
        if len(str(name)) < 4:
            raise forms.ValidationError("Name should contain more than $ letters")

class Joinusform(forms.ModelForm):

    class Meta:
        model = Join_Us
        fields = '__all__'

    confirm_email = forms.EmailField()
    botcatcher = forms.CharField(required=False,
                                    widget=forms.HiddenInput,
                                    validators=[validators.MaxLengthValidator(0)])

    def clean(self):
        super(Joinusform, self).clean()
        all_clean_data = self.cleaned_data
        email = all_clean_data['email']
        cemail = all_clean_data['confirm_email']
        phone = all_clean_data['phone']
        registration = all_clean_data['registration']
        experience = all_clean_data['experience']
        hiringreason = all_clean_data['hiringreason']
        role = all_clean_data['role']
        year = all_clean_data['year']
        if email != cemail:
            raise forms.ValidationError("MAKE SURE EMAIL MATCH!!!")

        if len(str(phone)) < 10:
            raise forms.ValidationError("Phone Number should be 10 digits!!!")

        if len(str(registration)) != 8:
            raise forms.ValidationError("Enter your correct Registration No!!!")

        if len(str(experience)) < 10:
            raise forms.ValidationError("Some Required Field is Empty and it should be filled Corectly without any Fake Information!!!")

        if len(str(hiringreason)) < 10:
            raise forms.ValidationError("Some Required Field is Empty and it should be filled Corectly without any Fake Information!!!")

        if role == 'select':
            raise forms.ValidationError("Select Your Role!!!")

        if year == 'select':
            raise forms.ValidationError("Select Which Year are you studying!!!")
</code>```

Here is views.py

```<code>#views.py

from index import forms as formlocal

def contact(request):

    contact_form = formlocal.Contactform()
    context = {'form':contact_form}

    if request.method == 'POST':
        contact_form = formlocal.Contactform(request.POST)

        if contact_form.is_valid():
            contact_form.save(commit=True)
            return redirect('/')
    return render(request,'index/contact.html',context=context)

 def joinus(request):

    form = formlocal.Joinusform()

    if request.method == 'POST':
        form = formlocal.Joinusform(request.POST)
        some_var = request.POST.getlist('role')
        if some_var[0] != 'select':

            if form.is_valid():
                form.save(commit=True)
                return redirect('/')
    return render(request,'index/joincoc.html',{'form':form})
</code>```

Here is models.py

```<code>#models.py

from django.db import models
from django.core.validators import URLValidator
from django.core.validators import MinLengthValidator
from django.utils.timezone import now
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from django.core.files.images import get_image_dimensions

class Contact_Us(models.Model):

    fullname = models.CharField(max_length=30,
                               default='',
                               validators=[MinLengthValidator(4)])
    email = models.EmailField()
    message = models.CharField(max_length=250,
                               default='',
                               blank=False)
    date = models.DateTimeField(default=now, blank=True)

    def __str__(self):
        return '{} contacting '.format(self.fullname).capitalize()

class Join_Us(models.Model):

    year_choices = [
        ('1st Year', '1st Year'),
        ('2nd Year', '2nd Year'),
        ('3rd Year', '3rd Year'),
        ('4th Year', '4th Year'),
    ]

    role_choices = [
        ('Content Writer', 'Content Writer'),
        ('Content Provider', 'Content Provider'),
        ('Marketing Manager', 'Marketing Manager'),
        ('Photo/Video Editor', 'Photo/Video Editor'),
        ('Not Mentioned', 'Not Mentioned'),
    ]

    fullname = models.CharField(max_length=30,
                               default='',
                               validators=[MinLengthValidator(4)])
    email = models.EmailField()
    registration = models.IntegerField()
    phone = models.IntegerField()
    experience = models.CharField(max_length=250,
                               default='',
                               validators=[MinLengthValidator(10)])
    hiringreason = models.CharField(max_length=250,
                               default='',
                               validators=[MinLengthValidator(10)])
    year = models.CharField(
        max_length=100,
        choices=year_choices,
    )
    role = models.CharField(
        max_length=100,
        choices=role_choices,
    )
    date = models.DateTimeField(default=now, blank=True)

    def __str__(self):
        return 'Name : {}'.format(self.fullname).capitalize()
</code>```

here is contact.html

```<code>{% include 'Utility/Title.html' %}
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="codeforcoder is a ultimate website for cse students. you can get codes,ppt,ebooks,question papers,placement question and much more.">

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,900" rel="stylesheet">

    {% include 'Utility/CSS_Links.html' %}
</head>
<body>
  <div class="container-fluid">
      {% include 'Utility/NavBar.html' %}

      <!-- Main Body Start -->
       <div class="row">

      <form method="POST" class="col xl6 offset-xl3 l6 offset-l3 m12 s12 center ">

        <h3 class="center" style="font-family: 'Source Sans Pro', sans-serif;">Contact US</h3>
            <!-- Modal Trigger -->
    <a class="waves-effect waves-light btn modal-trigger center" href="#modal1">Our Contacts</a>

    <!-- Modal Structure -->
    <div id="modal1" class="modal">
      <div class="modal-content">
        <h4>Phone No : </h4>
        <p>+91 8847240883, +91 8463048477</p>
        <h4>Mail : </h4>
        <p>reply.codeforcoder@gmail.com</p>
      </div>
      <div class="modal-footer">
        <a href="#!" class="modal-close waves-effect waves-green btn-flat">Close</a>
      </div>
    </div>

            <!-- Modal End-->
                        {{ form.non_field_errors }}
              {{ form.errors }}
         <div class="row center">
          <div class="input-field col xl12 l12  m12 s12 center">
            {{ form.fullname }}
            <label>Full Name :</label>
          </div>
       </div>
       <div class="row center">
          <div class="input-field  col xl6 l6 m6 s12 center">
            {{ form.email }}
            <label>Email :</label>
          </div>

          <div class="input-field  col xl6 l6 m6 s12 center">
             {{ form.confirm_email }}
                <label>Confirm Email :</label>
          </div>

       </div>

        <div class="row">
          <div class="input-field col xl12 l12 m12 s12 center">
            {{ form.message }}
            <label for="HiringReason">Message*</label>
          </div>
        </div>
                <div class="row">
          <div class="input-field col xl12 l12 m12 s12 center">
            {{ form.botcatcher }}
          </div>
        </div>
        {% csrf_token %}
       <button class="btn waves-effect waves-light" type="submit" name="submit">Send
      <i class="material-icons right">send</i>
    </button>
      </form>
    <!-- </div> -->

      </div>

      <!-- Main Body Start -->

      {% include 'Utility/Footer.html' %}
  </div>
  <!-- container ends here-->
  {% include 'Utility/JS_Links.html' %}
  <!--only requried js-->
  <script>
  <!-- collapse -->
    $(document).ready(function(){
      $('.collapsible').collapsible();
    });
    $(document).ready(function(){
      $('select').formSelect();
    });
    $(document).ready(function(){
      $('.modal').modal();
    });
  </script>
  <style>
    .errorlist{
      font-weight:bold;
    }
  </style>
</body>
</html>
</code>```

here is join.html

```<code>{% include 'Utility/Title.html' %}
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<meta name="description" content="codeforcoder is a ultimate website for cse students. you can get codes,ppt,ebooks,question papers,placement question and much more.">

<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,900" rel="stylesheet">

{% include 'Utility/CSS_Links.html' %}
</head>
<body>
<div class="container-fluid">
    {% include 'Utility/NavBar.html' %}

    <!-- Main Body Start -->
     <div class="row">

    <form method="POST" class="col xl6 offset-xl3 l6 offset-l3 m12 s12 center ">

        <h3 class="center" style="font-family: 'Source Sans Pro', sans-serif;">Join CodeforCoder</h3>
            <!-- Modal Trigger -->
  <a class="waves-effect waves-light btn modal-trigger center" href="#modal1">Benefits Of Joining</a>

  <!-- Modal Structure -->
  <div id="modal1" class="modal">
    <div class="modal-content">
      <h4>Modal Header</h4>
      <p>Zindigi Saphal ho jayegi</p>
    </div>
    <div class="modal-footer">
      <a href="#!" class="modal-close waves-effect waves-green btn-flat">Agree</a>
    </div>
  </div>

          <!-- Modal End-->
          {{ form.errors }}
       <div class="row center">
        <div class="input-field col xl12 l12  m12 s12 center">
          {{ form.fullname }}
          <label>Full Name :</label>
        </div>
     </div>
     <div class="row center">
       <div class="input-field  col xl6 l6 m6 s12 center">
          {{ form.registration }}
          <label>Registration No :</label>
       </div>
       <div class="input-field  col xl6 l6 m6 s12 center">
          {{ form.phone }}
          <label>Phone No :</label>
       </div>
     </div>
     <div class="row center">
        <div class="input-field  col xl6 l6 m6 s12 center">
          {{ form.email }}
          <label>Email :</label>
        </div>

        <div class="input-field  col xl6 l6 m6 s12 center">
           {{ form.confirm_email }}
              <label>Confirm Email :</label>
        </div>

     </div>

      <div class="row">
        <div class="input-field  col xl6 l6 m6 s12 center">
          {{ form.year }}
          <label>Select Your Year : </label>
        </div>

        <div class="input-field  col xl6 l6 m6 s12 center">
              {{ form.role }}
              <label>Select Your Year : </label>
        </div>
    </div>
      <div class="row">
        <div class="input-field col xl12 l12  m12 s12 center">
          {{ form.experience }}
          <label for="Experience">Any Technical Experience*</label>
        </div>
      </div>
        <div class="row">
        <div class="input-field col xl12 l12 m12 s12 center">
          {{ form.hiringreason }}
          <label for="HiringReason">Why are you working with us?*</label>
        </div>
      </div>
      <div class="row">
      <div class="input-field col xl12 l12 m12 s12 center">
        {{ form.botcatcher }}
      </div>
    </div>
      {% csrf_token %}
     <button class="btn waves-effect waves-light" type="submit" name="submit">Submit
    <i class="material-icons right">send</i>
  </button>
    </form>
  <!-- </div> -->

    </div>

    <!-- Main Body Start -->

    {% include 'Utility/Footer.html' %}
</div>
<!-- container ends here-->
{% include 'Utility/JS_Links.html' %}
<!--only requried js-->
<script>
<!-- collapse -->
  $(document).ready(function(){
    $('.collapsible').collapsible();
  });
  $(document).ready(function(){
    $('select').formSelect();
  });
  $(document).ready(function(){
    $('.modal').modal();
  });
</script>
<style>
  .errorlist{
    font-weight:bold;
  }
</style>
</body>
</html>
</code>```

答:
try to handle form error condition

try this

```<code>def contact(request):

   contact_form = formlocal.Contactform()
   context = {'form':contact_form}

   if request.method == 'POST':
      contact_form = formlocal.Contactform(request.POST)

      if contact_form.is_valid():
          contact_form.save(commit=True)
          return redirect('/')
      else:
          context = {'form':contact_form}
          return render(request,'index/contact.html',context=context)
    return render(request,'index/contact.html',context=context)
</code>```

hope it helps

refer this

Body:
I'm new to Django and learning some new things and I have a problem that I can't able to validate the contact form and page refreshes when I hit submit button. Can u please go through this code.

I cant able to validate contact form and I can able to validate and store values of join form but the contact form and everything are fine but I don't know where is the problem.

I'm using atom editor for Django

Here is forms.py

#forms.py

from django import forms
from django.core import validators
from index.models import *

class Contactform(forms.ModelForm):

    class Meta:
        model = Contact_Us
        exclude = ('date',)

    confirm_email = forms.EmailField()
    botcatcher = forms.CharField(required=False,
                                    widget=forms.HiddenInput,
                                    validators=[validators.MaxLengthValidator(0)])

    def clean(self):
        super(Contactform, self).clean()
        name = self.cleaned_data['fullname']
        if len(str(name)) < 4:
            raise forms.ValidationError("Name should contain more than $ letters")

class Joinusform(forms.ModelForm):

    class Meta:
        model = Join_Us
        fields = '__all__'

    confirm_email = forms.EmailField()
    botcatcher = forms.CharField(required=False,
                                    widget=forms.HiddenInput,
                                    validators=[validators.MaxLengthValidator(0)])

    def clean(self):
        super(Joinusform, self).clean()
        all_clean_data = self.cleaned_data
        email = all_clean_data['email']
        cemail = all_clean_data['confirm_email']
        phone = all_clean_data['phone']
        registration = all_clean_data['registration']
        experience = all_clean_data['experience']
        hiringreason = all_clean_data['hiringreason']
        role = all_clean_data['role']
        year = all_clean_data['year']
        if email != cemail:
            raise forms.ValidationError("MAKE SURE EMAIL MATCH!!!")

        if len(str(phone)) < 10:
            raise forms.ValidationError("Phone Number should be 10 digits!!!")

        if len(str(registration)) != 8:
            raise forms.ValidationError("Enter your correct Registration No!!!")

        if len(str(experience)) < 10:
            raise forms.ValidationError("Some Required Field is Empty and it should be filled Corectly without any Fake Information!!!")

        if len(str(hiringreason)) < 10:
            raise forms.ValidationError("Some Required Field is Empty and it should be filled Corectly without any Fake Information!!!")

        if role == 'select':
            raise forms.ValidationError("Select Your Role!!!")

        if year == 'select':
            raise forms.ValidationError("Select Which Year are you studying!!!")

Here is views.py

#views.py

from index import forms as formlocal

def contact(request):

    contact_form = formlocal.Contactform()
    context = {'form':contact_form}

    if request.method == 'POST':
        contact_form = formlocal.Contactform(request.POST)

        if contact_form.is_valid():
            contact_form.save(commit=True)
            return redirect('/')
    return render(request,'index/contact.html',context=context)

 def joinus(request):

    form = formlocal.Joinusform()

    if request.method == 'POST':
        form = formlocal.Joinusform(request.POST)
        some_var = request.POST.getlist('role')
        if some_var[0] != 'select':

            if form.is_valid():
                form.save(commit=True)
                return redirect('/')
    return render(request,'index/joincoc.html',{'form':form})

Here is models.py

#models.py

from django.db import models
from django.core.validators import URLValidator
from django.core.validators import MinLengthValidator
from django.utils.timezone import now
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from django.core.files.images import get_image_dimensions

class Contact_Us(models.Model):

    fullname = models.CharField(max_length=30,
                               default='',
                               validators=[MinLengthValidator(4)])
    email = models.EmailField()
    message = models.CharField(max_length=250,
                               default='',
                               blank=False)
    date = models.DateTimeField(default=now, blank=True)

    def __str__(self):
        return '{} contacting '.format(self.fullname).capitalize()

class Join_Us(models.Model):

    year_choices = [
        ('1st Year', '1st Year'),
        ('2nd Year', '2nd Year'),
        ('3rd Year', '3rd Year'),
        ('4th Year', '4th Year'),
    ]

    role_choices = [
        ('Content Writer', 'Content Writer'),
        ('Content Provider', 'Content Provider'),
        ('Marketing Manager', 'Marketing Manager'),
        ('Photo/Video Editor', 'Photo/Video Editor'),
        ('Not Mentioned', 'Not Mentioned'),
    ]

    fullname = models.CharField(max_length=30,
                               default='',
                               validators=[MinLengthValidator(4)])
    email = models.EmailField()
    registration = models.IntegerField()
    phone = models.IntegerField()
    experience = models.CharField(max_length=250,
                               default='',
                               validators=[MinLengthValidator(10)])
    hiringreason = models.CharField(max_length=250,
                               default='',
                               validators=[MinLengthValidator(10)])
    year = models.CharField(
        max_length=100,
        choices=year_choices,
    )
    role = models.CharField(
        max_length=100,
        choices=role_choices,
    )
    date = models.DateTimeField(default=now, blank=True)

    def __str__(self):
        return 'Name : {}'.format(self.fullname).capitalize()

here is contact.html

{% include 'Utility/Title.html' %}
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="codeforcoder is a ultimate website for cse students. you can get codes,ppt,ebooks,question papers,placement question and much more.">

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,900" rel="stylesheet">

    {% include 'Utility/CSS_Links.html' %}

      {% include 'Utility/NavBar.html' %}

      <form method="POST" class="col xl6 offset-xl3 l6 offset-l3 m12 s12 center ">

Contact US

    Our Contacts

Phone No :

+91 8847240883, +91 8463048477

Mail :

reply.codeforcoder@gmail.com

        Close

                        {{ form.non_field_errors }}
              {{ form.errors }}

            {{ form.fullname }}
            Full Name :

            {{ form.email }}
            Email :

             {{ form.confirm_email }}
                Confirm Email :

            {{ form.message }}
            Message*

            {{ form.botcatcher }}

        {% csrf_token %}
       <button class="btn waves-effect waves-light" type="submit" name="submit">Send
      send
    </button>
      </form>

      {% include 'Utility/Footer.html' %}

  {% include 'Utility/JS_Links.html' %}

here is join.html

{% include 'Utility/Title.html' %}
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<meta name="description" content="codeforcoder is a ultimate website for cse students. you can get codes,ppt,ebooks,question papers,placement question and much more.">

<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,900" rel="stylesheet">

{% include 'Utility/CSS_Links.html' %}

    {% include 'Utility/NavBar.html' %}

    <form method="POST" class="col xl6 offset-xl3 l6 offset-l3 m12 s12 center ">

Join CodeforCoder

  Benefits Of Joining

Modal Header

Zindigi Saphal ho jayegi

      Agree

          {{ form.errors }}

          {{ form.fullname }}
          Full Name :

          {{ form.registration }}
          Registration No :

          {{ form.phone }}
          Phone No :

          {{ form.email }}
          Email :

           {{ form.confirm_email }}
              Confirm Email :

          {{ form.year }}
          Select Your Year :

              {{ form.role }}
              Select Your Year :

          {{ form.experience }}
          Any Technical Experience*

          {{ form.hiringreason }}
          Why are you working with us?*

        {{ form.botcatcher }}

      {% csrf_token %}
     <button class="btn waves-effect waves-light" type="submit" name="submit">Submit
    send
  </button>
    </form>

    {% include 'Utility/Footer.html' %}

{% include 'Utility/JS_Links.html' %}

Body:
try to handle form error condition

try this

def contact(request):

   contact_form = formlocal.Contactform()
   context = {'form':contact_form}

   if request.method == 'POST':
      contact_form = formlocal.Contactform(request.POST)

      if contact_form.is_valid():
          contact_form.save(commit=True)
          return redirect('/')
      else:
          context = {'form':contact_form}
          return render(request,'index/contact.html',context=context)
    return render(request,'index/contact.html',context=context)

hope it helps

refer this


问:
Will backbonejs model cid be unique across multiple collection?
I want to know that will backbone model cid will unique among multiple collection.
Example: I have pageCollection and each pageCollection will contains another collection called controlCollection.

If I am creating control model, its cid will be unique among all controlCollection inside all pageCollection?

hierarchy:

```<code>pageCollection
  ->pageModel
    ->controlCollection
      ->controlModel
</code>```

答: Considering same model can be present inside multiple collections by design in backbone, it'll be unique. No other model will have same cid.

Body:
I want to know that will backbone model cid will unique among multiple collection.
Example: I have pageCollection and each pageCollection will contains another collection called controlCollection.

If I am creating control model, its cid will be unique among all controlCollection inside all pageCollection?

hierarchy:

pageCollection
  ->pageModel
    ->controlCollection
      ->controlModel


问:
it shows array outofbound exception
I want to store it in a Arraylist in the following order :

topcompany.get(i).getText(),

avg_exp.get(i).getText(),

avg_sal.get(i).getText(),

inlakhs.get(j).getText(),

circle_text.get(i).getText(),

inlakhs.get(j+1).getText()

My code:

```<code> List<WebElement> topcompany = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='a']//*[name()='text']//*[name()='tspan' and @dy='4']"));
 List<WebElement> avg_exp = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @x='245']//*[name()='tspan' and @dy='4']"));
 List<WebElement> avg_sal = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @x='295']//*[name()='tspan' and @dy='4']"));
 List<WebElement> inlakhs = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @fill='#000000']//*[name()='tspan' and @dy='3.5']"));
 List<WebElement> circle_text = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='a']//*[name()='text' and @fill='#ffffff']//*[name()='tspan' and @dy='3.5']"));

 for(int i=0;i<topcompany.size();i++) {
     for(int j=4;j<inlakhs.size();j++) {
         //main_list.add(new String[] {topcompany.get(i).getText(),avg_exp.get(i).getText(),avg_sal.get(i).getText(),inlakhs.get(j).getText(),circle_text.get(i).getText(),inlakhs.get(j+1).getText()});
     }
 }
</code>```

答:
It is very hard to understand what you are trying to achieve.

But here is a starting point : If we request for an index that is either negative, or greater than or equal to the size of the array, an ArrayIndexOutOfBoundsException is thrown.

In your case, inlakhs.get(j+1).getText() is going to throw an error when j reaches inlakhs.size() - 1 because then j will be equals to the size of the list.

You must fix this first and you will see this error disappears

Title: it shows array outofbound exception

Body:
I want to store it in a Arraylist in the following order :

topcompany.get(i).getText(),

avg_exp.get(i).getText(),

avg_sal.get(i).getText(),

inlakhs.get(j).getText(),

circle_text.get(i).getText(),

inlakhs.get(j+1).getText()

My code:

 List<WebElement> topcompany = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='a']//*[name()='text']//*[name()='tspan' and @dy='4']"));
 List<WebElement> avg_exp = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @x='245']//*[name()='tspan' and @dy='4']"));
 List<WebElement> avg_sal = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @x='295']//*[name()='tspan' and @dy='4']"));
 List<WebElement> inlakhs = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @fill='#000000']//*[name()='tspan' and @dy='3.5']"));
 List<WebElement> circle_text = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='a']//*[name()='text' and @fill='#ffffff']//*[name()='tspan' and @dy='3.5']"));

 for(int i=0;i<topcompany.size();i++) {
     for(int j=4;j<inlakhs.size();j++) {
         //main_list.add(new String[] {topcompany.get(i).getText(),avg_exp.get(i).getText(),avg_sal.get(i).getText(),inlakhs.get(j).getText(),circle_text.get(i).getText(),inlakhs.get(j+1).getText()});
     }
 }


问:
What is meaning of calling superview's viewwillappear?
```<code>-(void)viewwillAppear
{
[super viewwillAppear:animated];
}
</code>```

What does mean of calling [super viewwillAppear:animated] and what happen if we not call it?

答:
The reference clearly states

This method is called before the
  receiver’s view is about to be
  displayed onscreen and before any
  animations are configured for showing
  the view. You can override this method
  to perform custom tasks associated
  with presenting the view. For example,
  you might use this method to change
  the orientation or style of the status
  bar to coordinate with the orientation
  or style of the view being presented.
  If you override this method, you must
  call super at some point in your
  implementation.

Body:
-(void)viewwillAppear
{
[super viewwillAppear:animated];
}

What does mean of calling [super viewwillAppear:animated] and what happen if we not call it?


问:
Program in Python to show letters guessed in a hangman game not working
I have to write a code in Python where it is about playing the game hangman. Currently my code cannot replace the "_" with the guessed letters properly, where it only replaces one and doesn't show all of the guessed letters.

My code is below:

```<code>import random

word = random.choice(["bread", "clouds", "plane"])

guess = 0
correct_guess = 0
play_again = True

print(word)
name = input("Hello, what's your name? ")
print('Hello', name)
status = input('Do you wish to play hangman? Yes/No ')
hyphens = print('_ ' * (len(word)))

if status == 'No' 'no' 'N' 'n':
  exit()

while play_again is True:

  letter = input('Guess a letter: ')

  if letter in word:
    guess = guess + 1
    correct_guess = correct_guess + 1
    print('You guessed a letter correctly!')
    position = word.find(letter)
    print("The letter is in position", position + 1, "out of", len(word), "in the word. Guess Count:", guess)
    if position == 0:
      print(letter, "_ _ _ _")
    if position == 1:
      print("_", letter, "_ _ _ ")
    if position == 2:
      print("_ _", letter, "_ _ ")
    if position == 3:
      print("_ _ _", letter, "_ ")
    if position == 4:
      print("_ _ _ _", letter)
  else:
    guess = guess + 1
    print("That letter isn't in the word. Guess Count:", guess)
  if guess == 10:
    print('Bad luck. You lost.')
    play = input('Do you want to play again? ')
    if play == 'No' 'no' 'N' 'n':
      exit()
  if correct_guess == 5:
    print('Congratulations! You have guessed the word! The word was', word + '.')
    play = input('Do you want to play again? ')
    if play == 'No' 'no' 'N' 'n':
      exit()
</code>```

Your help is very much appreciated. Also, I don't know a lot about programming and I am fairly new to it.

James

答:
Cleaned it up a bit, removing duplicated code. Also that problematic condition:

```<code>if status == 'No' 'no' 'N' 'n':
</code>```

Changed it to:

```<code>if status.lower().startswith("n"):
</code>```

Also important to lower the letter input by the user. Here a full working code.

```<code>import random
import re

def start():
    status = input('Do you wish to play hangman? Yes/No ')
    if status.lower().startswith("n"):
        return True
    # Computer chooses word
    word = random.choice(["bread", "clouds", "plane"])
    # Setup game vars
    guess = []
    game_status = ["_"] * len(word)

    while True:
        print(" ".join(game_status))
        letter = input('Guess a letter: ').lower()
        if letter in guess:
            print("You already tried that one.")
            continue
        guess.append(letter)
        if letter in word:
            print('You guessed a letter correctly!')
            positions = [m.start() for m in re.finditer(letter, word)]
            for pos in positions:
                game_status[pos] = letter
        else:
            print("That letter isn't in the word.")
        if len(guess) == 10:
            print(f'Bad luck {name}. You lost. The word was: {word}.')
            return
        if "_" not in game_status:
            print(f'Congratulations {name}! You have guessed the word! The word was {word}.')
            return

# Welcome
name = input("Hello, what's your name? ")
print('Hello', name)
while True:
    stop = start()
    if stop:
        break
print("Goodbye!")
</code>```

Body:
I have to write a code in Python where it is about playing the game hangman. Currently my code cannot replace the "_" with the guessed letters properly, where it only replaces one and doesn't show all of the guessed letters.

My code is below:

import random

word = random.choice(["bread", "clouds", "plane"])

guess = 0
correct_guess = 0
play_again = True

print(word)
name = input("Hello, what's your name? ")
print('Hello', name)
status = input('Do you wish to play hangman? Yes/No ')
hyphens = print('_ ' * (len(word)))

if status == 'No' 'no' 'N' 'n':
  exit()

while play_again is True:

  letter = input('Guess a letter: ')

  if letter in word:
    guess = guess + 1
    correct_guess = correct_guess + 1
    print('You guessed a letter correctly!')
    position = word.find(letter)
    print("The letter is in position", position + 1, "out of", len(word), "in the word. Guess Count:", guess)
    if position == 0:
      print(letter, "_ _ _ _")
    if position == 1:
      print("_", letter, "_ _ _ ")
    if position == 2:
      print("_ _", letter, "_ _ ")
    if position == 3:
      print("_ _ _", letter, "_ ")
    if position == 4:
      print("_ _ _ _", letter)
  else:
    guess = guess + 1
    print("That letter isn't in the word. Guess Count:", guess)
  if guess == 10:
    print('Bad luck. You lost.')
    play = input('Do you want to play again? ')
    if play == 'No' 'no' 'N' 'n':
      exit()
  if correct_guess == 5:
    print('Congratulations! You have guessed the word! The word was', word + '.')
    play = input('Do you want to play again? ')
    if play == 'No' 'no' 'N' 'n':
      exit()

Your help is very much appreciated. Also, I don't know a lot about programming and I am fairly new to it.

James

Body:
Cleaned it up a bit, removing duplicated code. Also that problematic condition:

if status == 'No' 'no' 'N' 'n':

Changed it to:

if status.lower().startswith("n"):

Also important to lower the letter input by the user. Here a full working code.

import random
import re

def start():
    status = input('Do you wish to play hangman? Yes/No ')
    if status.lower().startswith("n"):
        return True
    # Computer chooses word
    word = random.choice(["bread", "clouds", "plane"])
    # Setup game vars
    guess = []
    game_status = ["_"] * len(word)

    while True:
        print(" ".join(game_status))
        letter = input('Guess a letter: ').lower()
        if letter in guess:
            print("You already tried that one.")
            continue
        guess.append(letter)
        if letter in word:
            print('You guessed a letter correctly!')
            positions = [m.start() for m in re.finditer(letter, word)]
            for pos in positions:
                game_status[pos] = letter
        else:
            print("That letter isn't in the word.")
        if len(guess) == 10:
            print(f'Bad luck {name}. You lost. The word was: {word}.')
            return
        if "_" not in game_status:
            print(f'Congratulations {name}! You have guessed the word! The word was {word}.')
            return

# Welcome
name = input("Hello, what's your name? ")
print('Hello', name)
while True:
    stop = start()
    if stop:
        break
print("Goodbye!")


问:
Xcode: Any way to refresh/re-run the playground?
The Playground in Xcode automatically updates as you type, but I can't figure out how to get the Playground to "re-compile".

In many cases this wouldn't matter, but if you're writing code that generates or uses random values it can be useful to run it a few times to make sure it's working. Is there any way to get the playground to reset / refresh / re-run?

Seen a few questions asking how to stop the Playground from auto-updating, but nothing for the opposite.

Easiest way to do this seems to be to just edit the code (add and remove a space), or put in some kind of a loop... Just wondering if there's a menu shortcut etc.

答:
As in Xcode version 10.2 the "Execute Playground" command in the "Editor" menu has been replaced by "Run Playground" and has a shortcut by default ⌘+ SHIFT + ENTER

The reason why it doesn't refresh when you enter the same command again, is because Playground is already running. You first need to stop the Playground by either clicking on the stop button or entering your own shortcut as I did.

To do so go in

Xcode > Preferences > Key Binding

and look for "Stop Playground".

Add the shortcut you would like to use clicking in the empty field on the right. I entered:

⌘+SHIFT +  >

In this way you can use the default shortcut to run the playground and you use the custom shortcut to stop it. Once stopped you can run it again.

Here in the menu:


问:
Stack of polymorphed classes
dear C++ professionals. I got a problem. I have a program, which has 1 abstract class base_class and 2 derived classes: sippeers and dbget. It also has 2 threads. First thread gets commands from user, second thread pocesses these commands. Both derived classes represent different commands. So, I have to create some kind of stack, where I should put user commands from first thread and get them in second thread to process. To make one stack for all commands, I got to use polymorphism. First, I tried to use std::list. But there was first problem: I can't make a list of abstract classes. Then I tried to use boost::ptr_list, but there was the second problem: classes, created in the first thread, dissappear with end of procedure, that created them. So pointers become illegal. The question: what kind of realization should I use? It looks like I must store every copy of derived class. But where?</p>

答:
First, I tried to use std::list. But there was first problem: I can't make a list of abstract classes.

You can, however, create an std::list containing pointers to the abstract base class, e.g.

```<code>std::list<base_class *> commands;
</code>```

Then I tried to use boost::ptr_list, but there was the second problem: classes, created in the first thread, dissappear with end of procedure, that created them. So pointers become illegal.

Do you mean the new commands are created on the stack of the first thread? Don't do that - the first thread doesn't know when the second thread finished handling the commands, so the first thread shouldn't define when they end. Just let the first thread allocate objects using new.

That being said, your use case sounds like a classical example of the producer-consumer problem. Consider having a look at the Wikipedia page on this for some inspiration on how to implement such a system properly (it's not too hard to get it wrong).

Title: Stack of polymorphed classes

Body:
First, I tried to use std::list. But there was first problem: I can't make a list of abstract classes.

You can, however, create an std::list containing pointers to the abstract base class, e.g.

std::list<base_class *> commands;

Then I tried to use boost::ptr_list, but there was the second problem: classes, created in the first thread, dissappear with end of procedure, that created them. So pointers become illegal.

Do you mean the new commands are created on the stack of the first thread? Don't do that - the first thread doesn't know when the second thread finished handling the commands, so the first thread shouldn't define when they end. Just let the first thread allocate objects using new.

That being said, your use case sounds like a classical example of the producer-consumer problem. Consider having a look at the Wikipedia page on this for some inspiration on how to implement such a system properly (it's not too hard to get it wrong).