问:
Creating a custom slider in Drupal 8
I am currently involved in a Drupal 8 Project but I am very new to Drupal. The aim of the project, in short, is to build a website based on a existing design and the client can update the website in Drupal (like a modifying some article, upload images to gallery, adding slides to the a slider, etc.)

I already have a static html page with me.

At this moment, I set my target to move the slider of the static page to Drupal such that the user can add, remove or update a slide. Each slide will contain a background image, a title and a description text.

After a day of research I am now able to create my own theme and create a "hard-code" front page which is exactly the same with my static html page. I am struggle to convert the slides to generic items that the users can modify in Drupal.

I am reading some articles about Modules and Views, but feeling very lost.

Can I have some directions as to what aspect of topics or what techniques I should go through to achieve the target I mentioned? Thanks!

答:
I'm currently developing a Drupal 8 module that implements a block with a slider in it. It's really easy to edit the sliders. It uses Jssor slider.

What is your timeframe on getting this working? I am willing to help you.

Download Jssor slider (the non-jQuery / non-minimized / full-width version)

Code your own slider block, inside a new custom module. Put the Jssor HTML in the part of the slider block code, that outputs the HTML for the block

Create a Slider content type, via the Drupal control panel (the content type needs to consist of multiple images, and any other slide information you want to show) - this is where the end CMS user will add and remove images / text for the slider (they won't need to change the block).

The code for your slider block, should read the images chosen in the slider content type, and output the HTML for these within the Jssor HTML. Something like:

```<code>$slider_html = '';
foreach ($full_image_urls as $full_image_url)
{
  $slide_html .= '<div><img data-u="image" src="'. $full_image_url .'" /></div>';
}
</code>```

The reason I implemented it in a block, is because blocks are easy to add to any page you like, and you can drag the order they display in.

This is a very high-level answer. If you need more detailed support, or you feel this is not clear, then I'm happy to help further. There isn't space to detail EVERY single step of implementation in an answer here, however you asked for a guide.

When my slider module is complete (it will be far easier to use than the existing jssor module that people struggle with), I'll be happy to give you an early copy.

Title: Creating a custom slider in Drupal 8

Body:
I'm currently developing a Drupal 8 module that implements a block with a slider in it. It's really easy to edit the sliders. It uses Jssor slider.

What is your timeframe on getting this working? I am willing to help you.

Download Jssor slider (the non-jQuery / non-minimized / full-width version)

Code your own slider block, inside a new custom module. Put the Jssor HTML in the part of the slider block code, that outputs the HTML for the block

Create a Slider content type, via the Drupal control panel (the content type needs to consist of multiple images, and any other slide information you want to show) - this is where the end CMS user will add and remove images / text for the slider (they won't need to change the block).

The code for your slider block, should read the images chosen in the slider content type, and output the HTML for these within the Jssor HTML. Something like:

$slider_html = '';
foreach ($full_image_urls as $full_image_url)
{
  $slide_html .= '<div><img data-u="image" src="'. $full_image_url .'" /></div>';
}

The reason I implemented it in a block, is because blocks are easy to add to any page you like, and you can drag the order they display in.

This is a very high-level answer. If you need more detailed support, or you feel this is not clear, then I'm happy to help further. There isn't space to detail EVERY single step of implementation in an answer here, however you asked for a guide.

When my slider module is complete (it will be far easier to use than the existing jssor module that people struggle with), I'll be happy to give you an early copy.


来源: stackexchange

问:
How to subclass DefaultTableModel and change its dataVector
I want to extend the DefaultTableModel and change its dataVector.
I want to make the dataVector to show only specific fields of DataHolder in the column:

```<code> public class MyTableModel extends DefaultTableModel {

    /**
     * The data vector
     */
    private Vector<DataHolder>   dataVector_;

    //overridden method to add row in the table model
    public void addRow(DataHolder rowData) {
        insertRow(getRowCount(), rowData);
    }

    public void insertRow(int row, DataHolder rowData) {
            dataVector_.insertElementAt(rowData, row);
            fireTableRowsInserted(row, row);
        }

    ...} //end of MyTableModel

   class DataHolder{
     private int age;
     private int year;
     private int month;
     private int day;
    }
</code>```

How can i display specific DataHolder fields in my jtable? My table has 3 columns for month, day, and year.

答:
You have to override the getValueAt(...) method:

```<code>@Override
public Object getValueAt(int row, int column) {
    DataHolder data = dataVector_.get(row);
    switch(column) {
        case 0: return data.month;
        case 1: return data.day;
        case 2: return data.year;
        default: return null;
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to extend the DefaultTableModel and change its dataVector.
I want to make the dataVector to show only specific fields of DataHolder in the column:

 public class MyTableModel extends DefaultTableModel {

    /**
     * The data vector
     */
    private Vector<DataHolder>   dataVector_;

    //overridden method to add row in the table model
    public void addRow(DataHolder rowData) {
        insertRow(getRowCount(), rowData);
    }

    public void insertRow(int row, DataHolder rowData) {
            dataVector_.insertElementAt(rowData, row);
            fireTableRowsInserted(row, row);
        }

    ...} //end of MyTableModel

   class DataHolder{
     private int age;
     private int year;
     private int month;
     private int day;
    }

How can i display specific DataHolder fields in my jtable? My table has 3 columns for month, day, and year.

Body:
You have to override the getValueAt(...) method:

@Override
public Object getValueAt(int row, int column) {
    DataHolder data = dataVector_.get(row);
    switch(column) {
        case 0: return data.month;
        case 1: return data.day;
        case 2: return data.year;
        default: return null;
    }


问:
Infinite Loop and Rotation of Array
so I have this list,

List: [0, 0, 1, 0, 1];

And I need made a algorithm with a for to show all the list (list[i]).

When I am in first array position, I can do list[i-2] and list[i-1], with this I can see the elements of the last position and the position before the last position.

Exemple : list[0] = 0; list[i-1] = list[4] = 1; list[i-2] = list[3] = 0; so I can go to the last position and start from there.

But when I do, list[i+1] in the last position I got a IndexError: list index out of range from the terminal.

My question is: If I was in the last positions and I want again come to  from the first one and keep doing the for loop, to see infinite times all array elements from all positions, How I can do it?
If the size of my array it is 5, and I am in second position(list[1]) in the loop and want do list[i + 11], how can I put this representing this, list[2]?

I am trying make this on python.

答: You can achieve this using the modulo operator, which returns the remainder of the division of its two operands. In this case, you would do the following: list[i%num_of_elements], where num_of_elements is a variable holding the number of elements in the list.

ContentLicense: CC BY-SA 3.0

Title: Infinite Loop and Rotation of Array


问:
Different error when I run the same tensorflow-r1.0 program twice
At the first time I run my program and I got the error:

tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value noise_z/0__mnn/bias1

But when I run it again, the error became:

tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value noise_z/1__mnn/0weight_

Please note that the variable name is different. It is very annoying to debug. I wonder why this happens and how can I fix it?

Here is the code involved with the error:

```<code>with tf.variable_scope('noise_z'):
    for noise_idx in range(num_noise):
        noise = gaussian_sampler(mu_noise, var_noise, 1)
        noise_vec = multi_layer_nn(noise, [dim_noise, 64, embedding_size], name=str(noise_idx)+'_')
        noise_vecs.append(noise_vec)

def fully_con_layer(input_, fan_in, fan_out, name, initializer=tf.orthogonal_initializer()):
    w = tf.get_variable(name+'_weight_', shape=[fan_in, fan_out], initializer=initializer)
    b = tf.get_variable('bias'+name, [fan_out], initializer=tf.random_uniform_initializer())
    return tf.nn.sigmoid(tf.matmul(input_, w)+b)

def multi_layer_nn(input_, num_unit_each_layer, name, initializer=tf.orthogonal_initializer()):
    x = input_
    num_layer = len(num_unit_each_layer)-1
    for layer in range(num_layer):
        with tf.variable_scope(name+'_'+"mnn"):
            x = fully_con_layer(x, num_unit_each_layer[layer], num_unit_each_layer[layer+1], str(layer))
    return x
</code>```

答: If you run tf.global_variables_initializer() and sess.run(init_op) before you call the function (as you say you do in your comment), the variables defined in the function will be not initialized. You have to run sess.run(init_op) after all variables are defined.

Body:
At the first time I run my program and I got the error:

tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value noise_z/0__mnn/bias1

But when I run it again, the error became:

tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value noise_z/1__mnn/0weight_

Please note that the variable name is different. It is very annoying to debug. I wonder why this happens and how can I fix it?

Here is the code involved with the error:

with tf.variable_scope('noise_z'):
    for noise_idx in range(num_noise):
        noise = gaussian_sampler(mu_noise, var_noise, 1)
        noise_vec = multi_layer_nn(noise, [dim_noise, 64, embedding_size], name=str(noise_idx)+'_')
        noise_vecs.append(noise_vec)

def fully_con_layer(input_, fan_in, fan_out, name, initializer=tf.orthogonal_initializer()):
    w = tf.get_variable(name+'_weight_', shape=[fan_in, fan_out], initializer=initializer)
    b = tf.get_variable('bias'+name, [fan_out], initializer=tf.random_uniform_initializer())
    return tf.nn.sigmoid(tf.matmul(input_, w)+b)

def multi_layer_nn(input_, num_unit_each_layer, name, initializer=tf.orthogonal_initializer()):
    x = input_
    num_layer = len(num_unit_each_layer)-1
    for layer in range(num_layer):
        with tf.variable_scope(name+'_'+"mnn"):
            x = fully_con_layer(x, num_unit_each_layer[layer], num_unit_each_layer[layer+1], str(layer))
    return x


问:
Java GUI Table adding certain rows to a watch-list
Ok I'm designing an application that will be used by many users with a JTable where the data for the table is pulled in using JDBC. And I'm thinking of adding a watch-list so the user can keep an eye on certain rows in the table in the GUI. Here is my question though because I am pulling the data from JDBC for the table will I not need to create a database MySql table for every user using the application so that 1 user can add rows to a watch-list while other users can add other rows to the watch-list and exclude the rows that others might have included in their watch-list. Because my solution is adding an extra column in the database for a value for watch-list where this is true only display these rows where this is not true don't show. But this solutions involves creating a database table for every user which is not what I want what is another way to add these rows to a watch-list.</p>

```<code>public class EmployeeSearchApp extends JFrame {
    private static  Connection connect;
    private JLabel title = new JLabel();
    private JPanel contentPane;
    private JTextField lastNameTextField;
    private JButton btnSearch;
    private JScrollPane scrollPane;
    private JTable table;
    private JButton appartmentformbutton = new JButton();
    private JButton selectbutton = new JButton();
    private JButton logoutexitbutton = new JButton();
    private JComboBox  addresscb = new JComboBox();
    private JComboBox  sexcb = new JComboBox();
    private JComboBox  agecb = new JComboBox();
    private JComboBox coursecb = new JComboBox();
    private JComboBox jobcb = new JComboBox();
    static String loginusername;
    private EmployeeDAO employeeDAO;
    List<Employee> employees = null;
    static EmployeeSearchApp searchouse = new EmployeeSearchApp(loginusername);
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    searchouse.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * Create the frame.
     */
    public EmployeeSearchApp(String loginusername) {
         this.loginusername=loginusername;
            if(loginusername!=null){
            System.out.print(loginusername);
            }
        // create the DAO
        try {
            employeeDAO = new EmployeeDAO();
        } catch (Exception exc) {
            JOptionPane.showMessageDialog(this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE);
        }
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Search for house");
        setAutoRequestFocus(false);
        setBackground(new java.awt.Color(204, 204, 255));
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBackground(new java.awt.Color(204, 204, 255));
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);
        title.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        title.setText("               Looking for Appartment");
        JPanel panel = new JPanel();
        panel.setBackground(new java.awt.Color(204, 204, 255));
        FlowLayout flowLayout = (FlowLayout) panel.getLayout();
        flowLayout.setAlignment(FlowLayout.LEFT);
        contentPane.add(panel, BorderLayout.NORTH);
        JLabel lblEnterLastName = new JLabel("Enter last name");
        panel.add(title);
        panel.add(lblEnterLastName);
        lastNameTextField = new JTextField();
        panel.add(lastNameTextField);
        lastNameTextField.setColumns(10);
        logoutexitbutton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                Component frame = null;
                int n = JOptionPane.showConfirmDialog(
                        frame,
                        "Exit to Main Screen",
                        "Exit to Main Screen",
                        JOptionPane.WARNING_MESSAGE);
                        searchouse.dispose();
                        intro  cancellogin = new intro();
                        cancellogin.setVisible(true);
            }
        });
        addresscb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Location",
                "Willow View", "Carton Drive", "Ballykeeran", "Moydrum",
                "Valley Court", "Auburn Heights", "Cypress Gardens", "Old Willow Park", "Old Willow Place",
                "Willow Park", "Wellmount Apartments", "Erris Grove, Willow Park", "Willow Green",
                "Cartontroy", "Crystal Village", "Willow Grove", "Willow Cresent",
                "Thornbury Drive", "Willow Place, Willow Park", "Willow View", "Willow Drive",
                "Small Apartments", "Other"}));
        sexcb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Sex", "Male", "Female"}));
        agecb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Age", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40"}));
        coursecb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Course", "Software Design", "Cooking", "Science" }));
        jobcb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Job", "Guard", "Teacher", "Farmer" }));
        appartmentformbutton.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        appartmentformbutton.setText("<html>Appartment<br>       Form</html>");
        logoutexitbutton.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        logoutexitbutton.setText("Log Out");
        selectbutton.setFont(new java.awt.Font("Tahoma", 1, 11));
        selectbutton.setText("Select Row");
        btnSearch = new JButton("Search");
        btnSearch.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Get last name from the text field
                // Call DAO and get employees for the last name
                // If last name is empty, then get all employees
                // Print out employees
                try {
                    String lastName = lastNameTextField.getText();
                    List<Employee> employees = null;
                    if (lastName != null && lastName.trim().length() > 0) {
                        employees = employeeDAO.searchEmployees(lastName);
                    } else {
                        employees = employeeDAO.getAllEmployees();
                    }
                    // create the model and update the "table"
                    EmployeeTableModel model = new EmployeeTableModel(employees);
                    table.setModel(model);
                    //model.removeRow(table.getSelectedRow());
                    //DefaultListModel<String> defaultListModel = (DefaultListModel<String>)EmployeeTableModel.getModel();
                    /*
                    for (Employee temp : employees) {
                        System.out.println(temp);
                    }
                    */
                } catch (Exception exc) {
                    JOptionPane.showMessageDialog(EmployeeSearchApp.this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        addresscb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                try {
                    String lastName = addresscb.getSelectedItem().toString();
                    System.out.print(lastName);
                    List<Employee> employees = null;
                    if (lastName != null && lastName.trim().length() > 0) {
                        employees = employeeDAO.searchEmployeesbyaddress(lastName);
                    } else {
                        employees = employeeDAO.getAllEmployees();
                    }
                        EmployeeTableModel model = new EmployeeTableModel(employees);
                        table.setModel(model);
                } catch (Exception exc) {
                    JOptionPane.showMessageDialog(EmployeeSearchApp.this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

//Add to arraylist where users id is equal to username only display these rows
/*Create button on form
Add selected rows equal to Arraylist
Create an arraylist step 1 where users id ="bob"
Create button display
where users id="bob"
Display Arraylist*/

        selectbutton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            /*int selectedRow = table.getSelectedRow();
            //TableRowModel tcm = table.getColumnModel();
    //      if(selectedRow != -1) {
                //table.removeColumn(table.getColumnModel().getSelectedColumn());
                table.getSelectedRow();
                //got selected row
                //database select Apartment get name and id
                //System.out.print(loginusername + ","+loginpassword);
                table.convertRowIndexToModel(table.getSelectedRow());
                System.out.print(selectedRow);
                try {
                    // get the selected row
                    int row = table.getSelectedRow();
                    // make sure a row is selected
                    if (row < 0) {
                        JOptionPane.showMessageDialog(EmployeeSearchApp.this,
                                "You must select an employee", "Error", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    JTextField releaseYearField = new JTextField();
                    //int decision = JOptionPane.showConfirmDialog(null, fields , "Create Dialog" , JOptionPane.OK_CANCEL_OPTION);
                    // prompt the user
                    int response = JOptionPane.showConfirmDialog(
                            EmployeeSearchApp.this, "Are you sure this is the appartment you want to choose, Please take note of phone number and address", "Confirm",
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                    if (response != JOptionPane.YES_OPTION) {
                        return;
                    }
                    // get the current employee
                    Employee tempEmployee = (Employee) table.getValueAt(row, EmployeeTableModel.OBJECT_COL);
                    //((DefaultTableModel)table.getModel()).removeRow(table.getSelectedRow());
                    // delete the employee
                    employeeDAO.deleteEmployee(tempEmployee.getacc_id());
                    employeeDAO.updateEmployee(tempEmployee.getacc_id(), loginusername );
                    // refresh GUI
System.out.print(tempEmployee.getaddress());
                    // show success message
                    JOptionPane.showMessageDialog(EmployeeSearchApp.this,
                            "Appartment confirmed request."+
                            "\n\nAddress: " + tempEmployee.getaddress()
                            + "\nHouse number: " + tempEmployee.gethouse_num()
                            + "\nLandlords Name: " + tempEmployee.getLandlords_first_Name()
                            + " " + tempEmployee.getLandlords_Surname()
                            + "\nLandlords phone number: " + tempEmployee.getMobile_Num(), "Error",
                            JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception exc) {
                    JOptionPane.showMessageDialog(EmployeeSearchApp.this,
                            "Error deleting employee: " + exc.getMessage(), "Error",
                            JOptionPane.ERROR_MESSAGE);
                }

*/
                 table.convertRowIndexToModel(table.getSelectedRow());
            }});
        panel.add(btnSearch);
        panel.add(appartmentformbutton);
        panel.add(selectbutton);
        panel.add(logoutexitbutton);
        panel.add(addresscb);
        panel.add(sexcb);
        panel.add(agecb );
        panel.add(coursecb);
        panel.add(jobcb);
        scrollPane = new JScrollPane();
        contentPane.add(scrollPane, BorderLayout.SOUTH);
        table = new JTable();
        scrollPane.setViewportView(table);
    }
}
</code>```

答:
Start by creating a new table (wish list)

In this table, have the following columns

user key

row key

(optional) primary key (you could use the user key and row as a composite key instead if you wished)

For example

```<code>+----------+---------+-------------+
| user key | row key | primary key |
+----------+---------+-------------+
</code>```

The user key would be linked back to the user table via a foreign key reference

The row key would be linked back to the data table view a foreign key reference.

This way you could query the data table and filter it using the current user

```<code>select * from data where rowKey in (select rowKey from wishList where data.rowKey = wishList.data and userKey = ?)
</code>```

(nb untested, but that's the gist)

to get the rows the user is interested in

You can also set up the referential integrity in such away that when a row is deleted from the data table, it will be removed from the wish list table and you could do the same thing for the user table

Body:
Ok I'm designing an application that will be used by many users with a JTable where the data for the table is pulled in using JDBC. And I'm thinking of adding a watch-list so the user can keep an eye on certain rows in the table in the GUI. Here is my question though because I am pulling the data from JDBC for the table will I not need to create a database MySql table for every user using the application so that 1 user can add rows to a watch-list while other users can add other rows to the watch-list and exclude the rows that others might have included in their watch-list. Because my solution is adding an extra column in the database for a value for watch-list where this is true only display these rows where this is not true don't show. But this solutions involves creating a database table for every user which is not what I want what is another way to add these rows to a watch-list.

public class EmployeeSearchApp extends JFrame {
    private static  Connection connect;
    private JLabel title = new JLabel();
    private JPanel contentPane;
    private JTextField lastNameTextField;
    private JButton btnSearch;
    private JScrollPane scrollPane;
    private JTable table;
    private JButton appartmentformbutton = new JButton();
    private JButton selectbutton = new JButton();
    private JButton logoutexitbutton = new JButton();
    private JComboBox  addresscb = new JComboBox();
    private JComboBox  sexcb = new JComboBox();
    private JComboBox  agecb = new JComboBox();
    private JComboBox coursecb = new JComboBox();
    private JComboBox jobcb = new JComboBox();
    static String loginusername;
    private EmployeeDAO employeeDAO;
    List<Employee> employees = null;
    static EmployeeSearchApp searchouse = new EmployeeSearchApp(loginusername);
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    searchouse.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * Create the frame.
     */
    public EmployeeSearchApp(String loginusername) {
         this.loginusername=loginusername;
            if(loginusername!=null){
            System.out.print(loginusername);
            }
        // create the DAO
        try {
            employeeDAO = new EmployeeDAO();
        } catch (Exception exc) {
            JOptionPane.showMessageDialog(this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE);
        }
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Search for house");
        setAutoRequestFocus(false);
        setBackground(new java.awt.Color(204, 204, 255));
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBackground(new java.awt.Color(204, 204, 255));
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);
        title.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        title.setText("               Looking for Appartment");
        JPanel panel = new JPanel();
        panel.setBackground(new java.awt.Color(204, 204, 255));
        FlowLayout flowLayout = (FlowLayout) panel.getLayout();
        flowLayout.setAlignment(FlowLayout.LEFT);
        contentPane.add(panel, BorderLayout.NORTH);
        JLabel lblEnterLastName = new JLabel("Enter last name");
        panel.add(title);
        panel.add(lblEnterLastName);
        lastNameTextField = new JTextField();
        panel.add(lastNameTextField);
        lastNameTextField.setColumns(10);
        logoutexitbutton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                Component frame = null;
                int n = JOptionPane.showConfirmDialog(
                        frame,
                        "Exit to Main Screen",
                        "Exit to Main Screen",
                        JOptionPane.WARNING_MESSAGE);
                        searchouse.dispose();
                        intro  cancellogin = new intro();
                        cancellogin.setVisible(true);
            }
        });
        addresscb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Location",
                "Willow View", "Carton Drive", "Ballykeeran", "Moydrum",
                "Valley Court", "Auburn Heights", "Cypress Gardens", "Old Willow Park", "Old Willow Place",
                "Willow Park", "Wellmount Apartments", "Erris Grove, Willow Park", "Willow Green",
                "Cartontroy", "Crystal Village", "Willow Grove", "Willow Cresent",
                "Thornbury Drive", "Willow Place, Willow Park", "Willow View", "Willow Drive",
                "Small Apartments", "Other"}));
        sexcb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Sex", "Male", "Female"}));
        agecb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Age", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40"}));
        coursecb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Course", "Software Design", "Cooking", "Science" }));
        jobcb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Job", "Guard", "Teacher", "Farmer" }));
        appartmentformbutton.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        appartmentformbutton.setText("Appartment
       Form");
        logoutexitbutton.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        logoutexitbutton.setText("Log Out");
        selectbutton.setFont(new java.awt.Font("Tahoma", 1, 11));
        selectbutton.setText("Select Row");
        btnSearch = new JButton("Search");
        btnSearch.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Get last name from the text field
                // Call DAO and get employees for the last name
                // If last name is empty, then get all employees
                // Print out employees
                try {
                    String lastName = lastNameTextField.getText();
                    List<Employee> employees = null;
                    if (lastName != null && lastName.trim().length() > 0) {
                        employees = employeeDAO.searchEmployees(lastName);
                    } else {
                        employees = employeeDAO.getAllEmployees();
                    }
                    // create the model and update the "table"
                    EmployeeTableModel model = new EmployeeTableModel(employees);
                    table.setModel(model);
                    //model.removeRow(table.getSelectedRow());
                    //DefaultListModel<String> defaultListModel = (DefaultListModel<String>)EmployeeTableModel.getModel();
                    /*
                    for (Employee temp : employees) {
                        System.out.println(temp);
                    }
                    */
                } catch (Exception exc) {
                    JOptionPane.showMessageDialog(EmployeeSearchApp.this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        addresscb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                try {
                    String lastName = addresscb.getSelectedItem().toString();
                    System.out.print(lastName);
                    List<Employee> employees = null;
                    if (lastName != null && lastName.trim().length() > 0) {
                        employees = employeeDAO.searchEmployeesbyaddress(lastName);
                    } else {
                        employees = employeeDAO.getAllEmployees();
                    }
                        EmployeeTableModel model = new EmployeeTableModel(employees);
                        table.setModel(model);
                } catch (Exception exc) {
                    JOptionPane.showMessageDialog(EmployeeSearchApp.this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

//Add to arraylist where users id is equal to username only display these rows
/*Create button on form
Add selected rows equal to Arraylist
Create an arraylist step 1 where users id ="bob"
Create button display
where users id="bob"
Display Arraylist*/

        selectbutton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            /*int selectedRow = table.getSelectedRow();
            //TableRowModel tcm = table.getColumnModel();
    //      if(selectedRow != -1) {
                //table.removeColumn(table.getColumnModel().getSelectedColumn());
                table.getSelectedRow();
                //got selected row
                //database select Apartment get name and id
                //System.out.print(loginusername + ","+loginpassword);
                table.convertRowIndexToModel(table.getSelectedRow());
                System.out.print(selectedRow);
                try {
                    // get the selected row
                    int row = table.getSelectedRow();
                    // make sure a row is selected
                    if (row < 0) {
                        JOptionPane.showMessageDialog(EmployeeSearchApp.this,
                                "You must select an employee", "Error", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    JTextField releaseYearField = new JTextField();
                    //int decision = JOptionPane.showConfirmDialog(null, fields , "Create Dialog" , JOptionPane.OK_CANCEL_OPTION);
                    // prompt the user
                    int response = JOptionPane.showConfirmDialog(
                            EmployeeSearchApp.this, "Are you sure this is the appartment you want to choose, Please take note of phone number and address", "Confirm",
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                    if (response != JOptionPane.YES_OPTION) {
                        return;
                    }
                    // get the current employee
                    Employee tempEmployee = (Employee) table.getValueAt(row, EmployeeTableModel.OBJECT_COL);
                    //((DefaultTableModel)table.getModel()).removeRow(table.getSelectedRow());
                    // delete the employee
                    employeeDAO.deleteEmployee(tempEmployee.getacc_id());
                    employeeDAO.updateEmployee(tempEmployee.getacc_id(), loginusername );
                    // refresh GUI
System.out.print(tempEmployee.getaddress());
                    // show success message
                    JOptionPane.showMessageDialog(EmployeeSearchApp.this,
                            "Appartment confirmed request."+
                            "\n\nAddress: " + tempEmployee.getaddress()
                            + "\nHouse number: " + tempEmployee.gethouse_num()
                            + "\nLandlords Name: " + tempEmployee.getLandlords_first_Name()
                            + " " + tempEmployee.getLandlords_Surname()
                            + "\nLandlords phone number: " + tempEmployee.getMobile_Num(), "Error",
                            JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception exc) {
                    JOptionPane.showMessageDialog(EmployeeSearchApp.this,
                            "Error deleting employee: " + exc.getMessage(), "Error",
                            JOptionPane.ERROR_MESSAGE);
                }

*/
                 table.convertRowIndexToModel(table.getSelectedRow());
            }});
        panel.add(btnSearch);
        panel.add(appartmentformbutton);
        panel.add(selectbutton);
        panel.add(logoutexitbutton);
        panel.add(addresscb);
        panel.add(sexcb);
        panel.add(agecb );
        panel.add(coursecb);
        panel.add(jobcb);
        scrollPane = new JScrollPane();
        contentPane.add(scrollPane, BorderLayout.SOUTH);
        table = new JTable();
        scrollPane.setViewportView(table);
    }
}

Body:
Start by creating a new table (wish list)

In this table, have the following columns

user key

row key

(optional) primary key (you could use the user key and row as a composite key instead if you wished)

For example

+----------+---------+-------------+
| user key | row key | primary key |
+----------+---------+-------------+

The user key would be linked back to the user table via a foreign key reference

The row key would be linked back to the data table view a foreign key reference.

This way you could query the data table and filter it using the current user

select * from data where rowKey in (select rowKey from wishList where data.rowKey = wishList.data and userKey = ?)

(nb untested, but that's the gist)

to get the rows the user is interested in

You can also set up the referential integrity in such away that when a row is deleted from the data table, it will be removed from the wish list table and you could do the same thing for the user table


问:
How to calculate regression between 2 columns in dataframe
I'm learning how to do regression in R, and I decided to try and regress GOOG to AAPL.

Here's what I did

```<code>getSymbols("AAPL", from="2011-01-01", to="2013-01-01")
getSymbols("GOOG", from="2011-01-01", to="2013-01-01")
lmdata=data.frame(Cl(AAPL),Cl(GOOG))
res=lm(lmdata)

plot(lmdata, main="Linear regression between GOOG and AAPL")
abline(res)
</code>```

The result looks like this

Obviously, some different regression was computed, and I'm suspecting that the software computed regression of AAPL closing price to it's date

```<code>> head(lmdata)
           AAPL.Close GOOG.Close
2011-01-03     329.57   604.3510
2011-01-04     331.29   602.1210
2011-01-05     334.00   609.0711
2011-01-06     333.73   613.5011
2011-01-07     336.12   616.4411
2011-01-10     342.45   614.2110
</code>```

How do I compute regression between AAPL and GOOG?

答:
For lm you need to specify the formula and data in the call:

```<code>res=lm(GOOG.Close ~ AAPL.Close, data=lmdata)
</code>```

Then the model and plot will be correct.

Body:
I'm learning how to do regression in R, and I decided to try and regress GOOG to AAPL.

Here's what I did

getSymbols("AAPL", from="2011-01-01", to="2013-01-01")
getSymbols("GOOG", from="2011-01-01", to="2013-01-01")
lmdata=data.frame(Cl(AAPL),Cl(GOOG))
res=lm(lmdata)

plot(lmdata, main="Linear regression between GOOG and AAPL")
abline(res)

The result looks like this

Obviously, some different regression was computed, and I'm suspecting that the software computed regression of AAPL closing price to it's date

> head(lmdata)
           AAPL.Close GOOG.Close
2011-01-03     329.57   604.3510
2011-01-04     331.29   602.1210
2011-01-05     334.00   609.0711
2011-01-06     333.73   613.5011
2011-01-07     336.12   616.4411
2011-01-10     342.45   614.2110

How do I compute regression between AAPL and GOOG?

Body:
For lm you need to specify the formula and data in the call:

res=lm(GOOG.Close ~ AAPL.Close, data=lmdata)

Then the model and plot will be correct.


问:
How can i click and drag a gameobject with the mouse?
Created new script

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class mouseDrag : MonoBehaviour
{
    float distance = 10;

        void OnMouseDrag()
        {
            Vector3 mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
            Vector3 objPosition = Camera.main.ScreenToWorldPoint(mousePosition);

            transform.position = objPosition;
        }
    }
</code>```

Then in another script in the Start function i'm creating 4 cubes and add the mouseDrag to each cube. But when running and clicking and dragging nothing happen. I'm not getting any errors or exceptions.

```<code>void Start()
    {
        lp = gameObjectToRaise.transform.localPosition;
        ls = gameObjectToRaise.transform.localScale;

        List<GameObject> cubes = new List<GameObject>();

        GameObject cube = Cube.CreatePrimitive(Cube.CubePivotPoint.UPLEFT);
        GameObject cube1 = Cube.CreatePrimitive(Cube.CubePivotPoint.UPRIGHT);
        GameObject cube2 = Cube.CreatePrimitive(Cube.CubePivotPoint.BACKUP);
        GameObject cube3 = Cube.CreatePrimitive(Cube.CubePivotPoint.UPRIGHT);

        cubes.Add(cube);
        cubes.Add(cube1);
        cubes.Add(cube2);
        cubes.Add(cube3);

        cube.GetComponentInChildren<Renderer>().material.color = Color.blue;
        cube1.GetComponentInChildren<Renderer>().material.color = Color.red;
        cube2.GetComponentInChildren<Renderer>().material.color = Color.green;
        cube3.GetComponentInChildren<Renderer>().material.color = Color.yellow;

        cube.transform.position = new Vector3(lp.x, lp.y, lp.z - 0.5f);
        cube1.transform.position = new Vector3(lp.x, lp.y, lp.z);
        cube2.transform.position = new Vector3(lp.x, lp.y, lp.z + 5);
        cube3.transform.position = new Vector3(lp.x + 5, lp.y, lp.z);

        cube1.transform.Rotate(0, 90, 0);
        cube3.transform.Rotate(0, 90, 0);

        StartCoroutine(scaleCube(cube.transform));
        StartCoroutine(scaleCube(cube1.transform));
        StartCoroutine(scaleCube(cube2.transform));
        StartCoroutine(scaleCube(cube3.transform));

        foreach (GameObject go in cubes)
        {
            go.AddComponent<mouseDrag>();
        }
    }

    IEnumerator scaleCube(Transform trans)
    {
        while (raiseAmount < raiseTotal)
        {
            raiseAmount += 1f;
            trans.localScale += new Vector3(speed * Time.deltaTime, speed * Time.deltaTime, 0);
            yield return null;
        }
    }
}
</code>```

答:
I just tried now with a single cube gameobject i added for testing it
  and it's working fine. But when i'm using the cubes using the CUBE
  class helper it's not working.

In this case, the mouseDrag script should be attached to the child cube(not the CubeHolder object).After that, you should be moving the parent of the cube which is "CubeHolder".

If you ever move the child cube, you will break the pivot point.

Simply change

```<code>transform.position = objPosition;
</code>```

to

```<code>transform.parent.position = objPosition;
</code>```

then attach the mouseDrag script to the child cube not the "CubeHolder".

Maybe the problem is that it's attaching the script to the
  parentObject "CubeHolder" and not to the created cubes ?

Yes. OnMouseDrag will only be called if attached to an Object with a Collider and the child cube is the only object with the Collider. The parent object is only there to be used as a pivot point feature.

NOTE:

You should not use OnMouseDrag for this. You should be dragging the cube/Object with the new UI event. There are many of the callback functions listed in this answer.

The script below is something you should be using. Attach the CubeDrag  sctipt to the child cube then change everything that says transform.position to transform.parent.position.

```<code>using UnityEngine;
using UnityEngine.EventSystems;
public class CubeDrag: MonoBehaviour, IPointerDownHandler, IDragHandler, IEndDragHandler
{
    Camera mainCamera;
    float zAxis = 0;
    Vector3 clickOffset = Vector3.zero;

    // Use this for initialization
    void Start()
    {
        addEventSystem();
        zAxis = transform.position.z;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        Vector3 tempPos = eventData.position;
        tempPos.z = Vector3.Distance(transform.position, Camera.main.transform.position);
        clickOffset = transform.position - mainCamera.ScreenToWorldPoint(tempPos);
        Debug.Log("Mouse Down");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 tempPos = eventData.position;
        tempPos.z = Vector3.Distance(transform.position, Camera.main.transform.position);
        Vector3 tempVec = mainCamera.ScreenToWorldPoint(tempPos) + clickOffset;
        tempVec.z = zAxis;

        transform.position = tempVec;
        Debug.Log("Dragging Cube");
    }

    public void OnEndDrag(PointerEventData eventData)
    {

    }

    void addEventSystem()
    {
        mainCamera = Camera.main;
        if (mainCamera.GetComponent<PhysicsRaycaster>() == null)
            mainCamera.gameObject.AddComponent<PhysicsRaycaster>();

        EventSystem eveSys = GameObject.FindObjectOfType(typeof(EventSystem)) as EventSystem;
        if (eveSys == null)
        {
            GameObject tempObj = new GameObject("EventSystem");
            eveSys = tempObj.AddComponent<EventSystem>();
        }

        StandaloneInputModule stdIM = GameObject.FindObjectOfType(typeof(StandaloneInputModule)) as StandaloneInputModule;
        if (stdIM == null)
            stdIM = eveSys.gameObject.AddComponent<StandaloneInputModule>();
    }
}
</code>```

Body:
Created new script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class mouseDrag : MonoBehaviour
{
    float distance = 10;

        void OnMouseDrag()
        {
            Vector3 mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
            Vector3 objPosition = Camera.main.ScreenToWorldPoint(mousePosition);

            transform.position = objPosition;
        }
    }

Then in another script in the Start function i'm creating 4 cubes and add the mouseDrag to each cube. But when running and clicking and dragging nothing happen. I'm not getting any errors or exceptions.

void Start()
    {
        lp = gameObjectToRaise.transform.localPosition;
        ls = gameObjectToRaise.transform.localScale;

        List<GameObject> cubes = new List<GameObject>();

        GameObject cube = Cube.CreatePrimitive(Cube.CubePivotPoint.UPLEFT);
        GameObject cube1 = Cube.CreatePrimitive(Cube.CubePivotPoint.UPRIGHT);
        GameObject cube2 = Cube.CreatePrimitive(Cube.CubePivotPoint.BACKUP);
        GameObject cube3 = Cube.CreatePrimitive(Cube.CubePivotPoint.UPRIGHT);

        cubes.Add(cube);
        cubes.Add(cube1);
        cubes.Add(cube2);
        cubes.Add(cube3);

        cube.GetComponentInChildren<Renderer>().material.color = Color.blue;
        cube1.GetComponentInChildren<Renderer>().material.color = Color.red;
        cube2.GetComponentInChildren<Renderer>().material.color = Color.green;
        cube3.GetComponentInChildren<Renderer>().material.color = Color.yellow;

        cube.transform.position = new Vector3(lp.x, lp.y, lp.z - 0.5f);
        cube1.transform.position = new Vector3(lp.x, lp.y, lp.z);
        cube2.transform.position = new Vector3(lp.x, lp.y, lp.z + 5);
        cube3.transform.position = new Vector3(lp.x + 5, lp.y, lp.z);

        cube1.transform.Rotate(0, 90, 0);
        cube3.transform.Rotate(0, 90, 0);

        StartCoroutine(scaleCube(cube.transform));
        StartCoroutine(scaleCube(cube1.transform));
        StartCoroutine(scaleCube(cube2.transform));
        StartCoroutine(scaleCube(cube3.transform));

        foreach (GameObject go in cubes)
        {
            go.AddComponent<mouseDrag>();
        }
    }

    IEnumerator scaleCube(Transform trans)
    {
        while (raiseAmount < raiseTotal)
        {
            raiseAmount += 1f;
            trans.localScale += new Vector3(speed * Time.deltaTime, speed * Time.deltaTime, 0);
            yield return null;
        }
    }
}

Body:
I just tried now with a single cube gameobject i added for testing it
  and it's working fine. But when i'm using the cubes using the CUBE
  class helper it's not working.

In this case, the mouseDrag script should be attached to the child cube(not the CubeHolder object).After that, you should be moving the parent of the cube which is "CubeHolder".

If you ever move the child cube, you will break the pivot point.

Simply change

transform.position = objPosition;

to

transform.parent.position = objPosition;

then attach the mouseDrag script to the child cube not the "CubeHolder".

Maybe the problem is that it's attaching the script to the
  parentObject "CubeHolder" and not to the created cubes ?

Yes. OnMouseDrag will only be called if attached to an Object with a Collider and the child cube is the only object with the Collider. The parent object is only there to be used as a pivot point feature.

NOTE:

You should not use OnMouseDrag for this. You should be dragging the cube/Object with the new UI event. There are many of the callback functions listed in this answer.

The script below is something you should be using. Attach the CubeDrag  sctipt to the child cube then change everything that says transform.position to transform.parent.position.

using UnityEngine;
using UnityEngine.EventSystems;
public class CubeDrag: MonoBehaviour, IPointerDownHandler, IDragHandler, IEndDragHandler
{
    Camera mainCamera;
    float zAxis = 0;
    Vector3 clickOffset = Vector3.zero;

    // Use this for initialization
    void Start()
    {
        addEventSystem();
        zAxis = transform.position.z;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        Vector3 tempPos = eventData.position;
        tempPos.z = Vector3.Distance(transform.position, Camera.main.transform.position);
        clickOffset = transform.position - mainCamera.ScreenToWorldPoint(tempPos);
        Debug.Log("Mouse Down");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 tempPos = eventData.position;
        tempPos.z = Vector3.Distance(transform.position, Camera.main.transform.position);
        Vector3 tempVec = mainCamera.ScreenToWorldPoint(tempPos) + clickOffset;
        tempVec.z = zAxis;

        transform.position = tempVec;
        Debug.Log("Dragging Cube");
    }

    public void OnEndDrag(PointerEventData eventData)
    {

    }

    void addEventSystem()
    {
        mainCamera = Camera.main;
        if (mainCamera.GetComponent<PhysicsRaycaster>() == null)
            mainCamera.gameObject.AddComponent<PhysicsRaycaster>();

        EventSystem eveSys = GameObject.FindObjectOfType(typeof(EventSystem)) as EventSystem;
        if (eveSys == null)
        {
            GameObject tempObj = new GameObject("EventSystem");
            eveSys = tempObj.AddComponent<EventSystem>();
        }

        StandaloneInputModule stdIM = GameObject.FindObjectOfType(typeof(StandaloneInputModule)) as StandaloneInputModule;
        if (stdIM == null)
            stdIM = eveSys.gameObject.AddComponent<StandaloneInputModule>();
    }
}


答:
Using the lead function from the dplyr package,

you can do:

```<code>library(dplyr)
df$Difference=df[,2]-lead(df[,2],1)
df$Difference[(2*df[,1]-lead(df[,1],1))<2]=0
# The multiplication by 2 is to differentiate between 1 followed by 0 and 0 followed by -1
</code>```

Title: How do I take differences of two rows based on conditional statement?

Body:
I'm having a lot of trouble with this really easy problem. Below is a sample of my data:

            EUR.20MA.1 EUR.LAST.2
2013-11-04          1     1.3514
2013-11-05         -1     1.3474
2013-11-06          1     1.3513
2013-11-07          0     1.3419
2013-11-08         -1     1.3367
2013-11-11          1     1.3407

Basically whenever the signal changes from 1 to 0, or 1 to -1, I want to take the difference of that row with the subsequent row. Hence, output would look like:

         EUR.20MA.1 EUR.LAST.2  Difference
11/4/2013   1       1.3514      0.004
11/5/2013  -1       1.3474      0
11/6/2013   1       1.3513      0.0094
11/7/2013   0       1.3419      0
11/8/2013  -1       1.3367      0
11/11/2013  1       1.3407      0
11/12/2013  1       1.3436      0
11/13/2013  1       1.3487      0.0026
11/14/2013 -1       1.3461      0

Dput below:

structure(list(EUR.20MA.1 = c(1, -1, 1, 0, -1, 1, 1, 1, -1, 1
), EUR.LAST.2 = c(1.3514, 1.3474, 1.3513, 1.3419, 1.3367, 1.3407,
1.3436, 1.3487, 1.3461, 1.3496)), .Names = c("EUR.20MA.1", "EUR.LAST.2"
), row.names = c("2013-11-04", "2013-11-05", "2013-11-06", "2013-11-07",
"2013-11-08", "2013-11-11", "2013-11-12", "2013-11-13", "2013-11-14",
"2013-11-15"), class = "data.frame")

Body:
Using the lead function from the dplyr package,

you can do:

library(dplyr)
df$Difference=df[,2]-lead(df[,2],1)
df$Difference[(2*df[,1]-lead(df[,1],1))<2]=0
# The multiplication by 2 is to differentiate between 1 followed by 0 and 0 followed by -1


问:
C++ dynamic array of dynamic strings
I know how to create a dynamic array of strings in C++:

```<code>string* array = new string[10];
</code>```

But how do I create a dynamic array of dynamic strings in C++? I mean a dynamic array that holds string* objects. And how do I initialize each one of the dynamic strings?

答:
Simple example :) </p>

```<code>#include <iostream>
using namespace std;

int main() {
    int n, m;
    cin>>n;
    cin>>m;
    string** array = new string*[n];

    for(int i = 0; i<n; i++)
    {
        array[i] = new string[m];
    }

    for(int i = 0; i<n; i++)
    for(int j = 0; j<n; j++)
    cin>>array[i][j];

    for(int i = 0; i<n; i++)
    for(int j = 0; j<n; j++)
    cout<<array[i][j]<<endl;

    return 0;
}
</code>```

Title: C++ dynamic array of dynamic strings

Body:
I know how to create a dynamic array of strings in C++:

string* array = new string[10];

But how do I create a dynamic array of dynamic strings in C++? I mean a dynamic array that holds string* objects. And how do I initialize each one of the dynamic strings?

Body:
Simple example :)

#include <iostream>
using namespace std;

int main() {
    int n, m;
    cin>>n;
    cin>>m;
    string** array = new string*[n];

    for(int i = 0; i<n; i++)
    {
        array[i] = new string[m];
    }

    for(int i = 0; i<n; i++)
    for(int j = 0; j<n; j++)
    cin>>array[i][j];

    for(int i = 0; i<n; i++)
    for(int j = 0; j<n; j++)
    cout<<array[i][j]<<endl;

    return 0;
}


问:
Is it possible to read/edit shared preferences in native code?
I have an Android app that includes a C library using NDK to execute some some code. Within the C library I would like to update the applications shared preferences. My question... is it possible to read/edit shared preferences in native code?</p>

答:
You can do anything you want in native code. It's just cumbersome - you need the JNIEnv object to first find the class ID, then the method ID, if you have any non-primitive types, you need to create those too. But then you just call the method, and you're done.

JNI Docs - look for FindClass, GetMethodId, CallVoidMethod, etc.


问:
3 models many-to-many sync in Laravel 5.4
I have 3 models with the relations many-to-many:

Module

```<code>public function permissionTypes()
{
    return $this->belongsToMany(PermissionType::class, 'permissions')->withPivot('role_id');
}

public function roles()
{
    return $this->belongsToMany(Role::class, 'permissions')->withPivot('permission_type_id');
}
</code>```

Role

```<code>public function permissionTypes()
{
    return $this->belongsToMany(PermissionType::class, 'permissions')->withPivot('module_id');
}

public function modules()
{
    return $this->belongsToMany(Module::class, 'permissions')->withPivot('permission_type_id');
}
</code>```

PermissionType

```<code>public function roles()
{
    return $this->belongsToMany(Role::class, 'permissions')->withPivot('module_id');
}

public function modules()
{
    return $this->belongsToMany(Module::class, 'permissions')->withPivot('role_id');
}
</code>```

tables description:

modules

```<code>id
title
status
</code>```

roles

```<code>id
title
</code>```

permission_types

```<code>id
title
</code>```

pivot table permissions

```<code>id
role_id
module_id
permission_type_id
</code>```

My synchronization looks like:

```<code>//array of ids from request to synchronization
$permissions = $request['permissions'];

//role by id from request
$role = Role::findOrFail((int)$roleId);

//module by id from request
$module = Module::findOrFail((int)$moduleId);

//synchronization
$pivotData = array_fill(0, count($permissions), ['role_id' => $role->id]);
$syncData  = array_combine($permissions, $pivotData);
$module->permissionTypes()->sync($syncData);
</code>```

When trying to make the synchronization, have an error

QueryException in Connection.php line 647:
  SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'permissions' (SQL: select permissions.*, permissions.role_id as pivot_role_id, permissions.permission_id as pivot_permission_id from permissions inner join permissions on permissions.id = permissions.permission_id where permissions.role_id = 1)

Thanks

答:
IMHO you are trying to design a triple many to many that does not exists in Laravel. The solution, usually is to give the pivot table (in your case permissions) a Model (Permission in below code) for defining hasManyThrough relations.

If I understood well your table structure I will design the following relationships:

Module

```<code>public function permissions()
{
    return $this->hasMany(Permission::class);
}
public function roles()
{
    return $this->hasManyThrough(Role::class, Permission::class);
}
public function permissionTypes()
{
    return $this->hasManyThrough(PermissionType::class, Permission::class);
}
</code>```

Role

```<code>public function permissions()
{
    return $this->hasMany(Permission::class);
}
public function permissionTypes()
{
   return $this->hasManyThrough(PermissionType::class, Permission::class);
}
public function modules()
{
    return $this->hasManyThrough(Module::class, Permission::class);
}
</code>```

PermissionType

```<code>public function permissions()
{
    return $this->hasMany(Permission::class);
}
public function modules()
{
    return $this->hasManyThrough(Module::class, Permission::class);
}
public function roles()
{
   return $this->hasManyThrough(Role::class, Permission::class);
}
</code>```

Permission

```<code>public function permissionType()
{
    return $this->belongsTo(PermissionType::class);
}
public function role()
{
    return $this->belongsTo(Role::class);
}
public function module()
{
    return $this->belongsTo(Module::class);
}
</code>```

Tell me if it could work for you.

Body:
I have 3 models with the relations many-to-many:

Module

public function permissionTypes()
{
    return $this->belongsToMany(PermissionType::class, 'permissions')->withPivot('role_id');
}

public function roles()
{
    return $this->belongsToMany(Role::class, 'permissions')->withPivot('permission_type_id');
}

Role

public function permissionTypes()
{
    return $this->belongsToMany(PermissionType::class, 'permissions')->withPivot('module_id');
}

public function modules()
{
    return $this->belongsToMany(Module::class, 'permissions')->withPivot('permission_type_id');
}

PermissionType

public function roles()
{
    return $this->belongsToMany(Role::class, 'permissions')->withPivot('module_id');
}

public function modules()
{
    return $this->belongsToMany(Module::class, 'permissions')->withPivot('role_id');
}

tables description:

modules

id
title
status

roles

id
title

permission_types

id
title

pivot table permissions

id
role_id
module_id
permission_type_id

My synchronization looks like:

//array of ids from request to synchronization
$permissions = $request['permissions'];

//role by id from request
$role = Role::findOrFail((int)$roleId);

//module by id from request
$module = Module::findOrFail((int)$moduleId);

//synchronization
$pivotData = array_fill(0, count($permissions), ['role_id' => $role->id]);
$syncData  = array_combine($permissions, $pivotData);
$module->permissionTypes()->sync($syncData);

When trying to make the synchronization, have an error

QueryException in Connection.php line 647:
  SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'permissions' (SQL: select permissions.*, permissions.role_id as pivot_role_id, permissions.permission_id as pivot_permission_id from permissions inner join permissions on permissions.id = permissions.permission_id where permissions.role_id = 1)

Thanks

Body:
IMHO you are trying to design a triple many to many that does not exists in Laravel. The solution, usually is to give the pivot table (in your case permissions) a Model (Permission in below code) for defining hasManyThrough relations.

If I understood well your table structure I will design the following relationships:

Module

public function permissions()
{
    return $this->hasMany(Permission::class);
}
public function roles()
{
    return $this->hasManyThrough(Role::class, Permission::class);
}
public function permissionTypes()
{
    return $this->hasManyThrough(PermissionType::class, Permission::class);
}

Role

public function permissions()
{
    return $this->hasMany(Permission::class);
}
public function permissionTypes()
{
   return $this->hasManyThrough(PermissionType::class, Permission::class);
}
public function modules()
{
    return $this->hasManyThrough(Module::class, Permission::class);
}

PermissionType

public function permissions()
{
    return $this->hasMany(Permission::class);
}
public function modules()
{
    return $this->hasManyThrough(Module::class, Permission::class);
}
public function roles()
{
   return $this->hasManyThrough(Role::class, Permission::class);
}

Permission

public function permissionType()
{
    return $this->belongsTo(PermissionType::class);
}
public function role()
{
    return $this->belongsTo(Role::class);
}
public function module()
{
    return $this->belongsTo(Module::class);
}

Tell me if it could work for you.


问:
Visual studio 2017 and the cl.exe error
I am trying to run the following command in Windows:

```<code>pip install flask-sqlalchemy mysql-python
</code>```

But I get the following error:

```<code>cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG / MD -Dversion_info=(1,2,5,'final',1)
-D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" "-Ic:\users\mrnoname\anaconda3\include" "-Ic:
\users\mrnoname\anaconda3\include" /Tc_mysql.c /Fobuild\temp.win-amd64-3.5\Release/
_mysql.obj /Z1

error: command 'cl.exe' failed: No such file or directory
</code>```

I looked up cl.exe error and found a thread on SO.

Visual studio doesn't have cl.exe

Visual Studio 2015 doesn't install C++ by default. You have to rerun
  the setup, select Modify and then check Programming Language -> C++

But for Visual Studio 2017, I don't see such an option. There is no "Programming Language" option to select C++.

I tried installing most of the C++ options (skipping only ones like designed specifically for gaming or other things irrelevant to me) but this didn't solve it.

Does anyone have suggestions for how to correct this for Visual Studio Community 2017?

答: Did you miss this option in the Visual Studio 2017 Setup?

Title: Visual studio 2017 and the cl.exe error

Body:
I am trying to run the following command in Windows:

pip install flask-sqlalchemy mysql-python

But I get the following error:

cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG / MD -Dversion_info=(1,2,5,'final',1)
-D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" "-Ic:\users\mrnoname\anaconda3\include" "-Ic:
\users\mrnoname\anaconda3\include" /Tc_mysql.c /Fobuild\temp.win-amd64-3.5\Release/
_mysql.obj /Z1

error: command 'cl.exe' failed: No such file or directory

I looked up cl.exe error and found a thread on SO.

Visual studio doesn't have cl.exe

Visual Studio 2015 doesn't install C++ by default. You have to rerun
  the setup, select Modify and then check Programming Language -> C++

But for Visual Studio 2017, I don't see such an option. There is no "Programming Language" option to select C++.

I tried installing most of the C++ options (skipping only ones like designed specifically for gaming or other things irrelevant to me) but this didn't solve it.

Does anyone have suggestions for how to correct this for Visual Studio Community 2017?


问:
What is .first attribute of FileManager urls?
In order to cache images downloaded from the internet to the user's iPhone I have implemented the following code:

```<code>let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent(info.dbName + ".png")
try data!.write(to: fileURL, options: .atomic)
print("Saved img \(info.dbName)")
</code>```

I'm starting to understand core data in iOS a little more now but I'm having a hard time figuring out what the .first! refers to in the first line above.

Can anybody please help me understand this better so I'm sure that the way I'm caching images is correct and safe?

答:
That function returns an Array of URLs: https://developer.apple.com/reference/foundation/filemanager/1407726-urls

The first! call then gets the first element: https://developer.apple.com/reference/swift/array/1689165-first

As the first function returns an Optional, the ! force unwraps it.

Body:
In order to cache images downloaded from the internet to the user's iPhone I have implemented the following code:

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent(info.dbName + ".png")
try data!.write(to: fileURL, options: .atomic)
print("Saved img \(info.dbName)")

I'm starting to understand core data in iOS a little more now but I'm having a hard time figuring out what the .first! refers to in the first line above.

Can anybody please help me understand this better so I'm sure that the way I'm caching images is correct and safe?


答:
I believe your asking about rotating arrays, if this isn't what you meant, just comment.</p>

```<code>def rotateLeft(li):
    return li[1:] + [li[0]]

def rotateRight(li):
    return [li[len(li)-1]] + li[:len(li)-1]

li = [1,2,3,4,5]

print (rotateLeft(li))
print (rotateRight(li))
</code>```

Title: Infinite Loop and Rotation of Array

Body:
so I have this list,

List: [0, 0, 1, 0, 1];

And I need made a algorithm with a for to show all the list (list[i]).

When I am in first array position, I can do list[i-2] and list[i-1], with this I can see the elements of the last position and the position before the last position.

Exemple : list[0] = 0; list[i-1] = list[4] = 1; list[i-2] = list[3] = 0; so I can go to the last position and start from there.

But when I do, list[i+1] in the last position I got a IndexError: list index out of range from the terminal.

My question is: If I was in the last positions and I want again come to  from the first one and keep doing the for loop, to see infinite times all array elements from all positions, How I can do it?
If the size of my array it is 5, and I am in second position(list[1]) in the loop and want do list[i + 11], how can I put this representing this, list[2]?

I am trying make this on python.

Body:
I believe your asking about rotating arrays, if this isn't what you meant, just comment.

def rotateLeft(li):
    return li[1:] + [li[0]]

def rotateRight(li):
    return [li[len(li)-1]] + li[:len(li)-1]

li = [1,2,3,4,5]

print (rotateLeft(li))
print (rotateRight(li))


问:
Where can I find the source code for the gmail, facebook, and twitter apps for android? Are they even open source?
There are some components I need to use from these three 'supposedly' open source apps for android.

I looked at the source code for android, but I can't seem to find the gmail app; I can only find the email app.

I looked at the source code for the official facebook sdk for android, but there is no source code for the actual facebook app; there only is the source for the sdk, not the app.

And as for the twitter app, I can't even find the source code repository despite a million articles on the web saying that the twitter for android is open source.

Does anyone know where?

答:
Romain Guy from Google states that Gmail is not open source here. The Twitter app was announced to become open source in the future ref. I'm more than sure that Facebook is not open source.

A simple Google search and even a simple Stack Overflow search would've gotten you what you were looking for.


问:
Calling base class template constructor in C++
I have a template base class which has a constructor for conversion from any other template instantiation of that class, like this:

```<code>template <class T>
class FooBase
{
public:

    FooBase()
    {
    }

    template <class U>
    FooBase(const FooBase<U>& other)
    {
        std::cout << "FooBase<U>" << std::endl;
    }
};
</code>```

Notice how there is no copy constructor defined.

I then have a derived template class which does have a copy constructor, as well as the constructor used for conversion:

```<code>template <class T>
class Foo : public FooBase<T>
{
public:

    Foo()
    {
    }

    Foo(const Foo& other) :
        FooBase<T>(other)
    {
    }

    template <class U>
    Foo(const Foo<U>& other) :
        FooBase<T>(other)
    {
    }
};
</code>```

Because FooBase doesn't have a copy constructor, this results in FooBase<T>(other) making a call to the compiler-generated copy constructor. Which means if I run this:

```<code>int main()
{
    Foo<int> a;
    Foo<int> b(a);

    return 0;
}
</code>```

The output is nothing, when it should be FooBase.

Of course, I could try to solve the issue by creating a copy constructor in FooBase and using delegating constructors:

```<code>    FooBase(const FooBase& other)
        : FooBase<T>(other)
    {
    }
</code>```

But unfortunately that doesn't work, and it would result in a recursive call as the compiler helpfully points out:

```<code>warning C4717: 'FooBase<int>::FooBase<int>': recursive on all control paths, function will cause runtime stack overflow
</code>```

So the only solution would be to duplicate the logic into both constructors.

Is there any way around this that doesn't involve code duplication or a separate initialization function?

答:
You could have a third, private constructor that both the copy constructor and the constructor template delegate to and which contains the actual work:</p>

```<code>template <typename T> class FooBase
{
    struct Tag{};

    template <typename U>  // May have U = T
    FooBase(Tag, const FooBase<U> & rhs)
    {
        // actual implementation
    }

public:
    FooBase(const FooBase & rhs) : FooBase(Tag(), rhs) {}

    template <typename U>  // Never selects U = T
    FooBase(const FooBase<U> & rhs) : FooBase(Tag(), rhs) {}
};
</code>```

Body:
I have a template base class which has a constructor for conversion from any other template instantiation of that class, like this:

template <class T>
class FooBase
{
public:

    FooBase()
    {
    }

    template <class U>
    FooBase(const FooBase& other)
    {
        std::cout << "FooBase" << std::endl;
    }
};

Notice how there is no copy constructor defined.

I then have a derived template class which does have a copy constructor, as well as the constructor used for conversion:

template <class T>
class Foo : public FooBase<T>
{
public:

    Foo()
    {
    }

    Foo(const Foo& other) :
        FooBase<T>(other)
    {
    }

    template <class U>
    Foo(const Foo& other) :
        FooBase<T>(other)
    {
    }
};

Because FooBase doesn't have a copy constructor, this results in FooBase<T>(other) making a call to the compiler-generated copy constructor. Which means if I run this:

int main()
{
    Foo<int> a;
    Foo<int> b(a);

    return 0;
}

The output is nothing, when it should be FooBase.

Of course, I could try to solve the issue by creating a copy constructor in FooBase and using delegating constructors:

    FooBase(const FooBase& other)
        : FooBase<T>(other)
    {
    }

But unfortunately that doesn't work, and it would result in a recursive call as the compiler helpfully points out:

warning C4717: 'FooBase<int>::FooBase<int>': recursive on all control paths, function will cause runtime stack overflow

So the only solution would be to duplicate the logic into both constructors.

Is there any way around this that doesn't involve code duplication or a separate initialization function?

Body:
You could have a third, private constructor that both the copy constructor and the constructor template delegate to and which contains the actual work:

template <typename T> class FooBase
{
    struct Tag{};

    template <typename U>  // May have U = T
    FooBase(Tag, const FooBase<U> & rhs)
    {
        // actual implementation
    }

public:
    FooBase(const FooBase & rhs) : FooBase(Tag(), rhs) {}

    template <typename U>  // Never selects U = T
    FooBase(const FooBase<U> & rhs) : FooBase(Tag(), rhs) {}
};


问:
How to change regedit registry from command line?
I'm using "D:\users" profilePath for my Domain users. When I change my "systemdrive" with new windows image, Domain users creates new profile like "D:\Users\old.DNS".

I want to use old profilepath but I couldn't find any method to tell windows "use existing profile". Because of that I need to change profile path from regedit!

I tried to write something but I don't know how can I modify the registry only changes "dnsname".

Because username is different for every machine and also DNSname can be different for different companies.

I'm taking user sid with

```<code>set sid=wmic useraccount where name='%username%' get sid

%sid%
</code>```

Then I need to take username and remove .DNS from it, but I don't know how can I do that.
Can i write someting like "delete after "." "point" in batch?

答:
I found my self and this script needs admin privileges.</p>

```<code>::get usersid first
for /F "tokens=2" %%i in ('whoami /user /fo table /nh') do set usersid=%%i

::get userpath
for /F "tokens=3" %%i in ('reg QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%usersid%" /v "ProfileImagePath"') do set oldpath=%%i

::delete after "."
for /f "tokens=1 delims=." %%a in ('echo %oldpath%') do set newpath=%%a

::update the reg with new path
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%usersid%" /v "ProfileImagePath" /t REG_EXPAND_SZ /d "%newpath%" /f

echo EVERYTHING OKAY MATE!
pause
</code>```

Body:
I'm using "D:\users" profilePath for my Domain users. When I change my "systemdrive" with new windows image, Domain users creates new profile like "D:\Users\old.DNS".

I want to use old profilepath but I couldn't find any method to tell windows "use existing profile". Because of that I need to change profile path from regedit!

I tried to write something but I don't know how can I modify the registry only changes "dnsname".

Because username is different for every machine and also DNSname can be different for different companies.

I'm taking user sid with

set sid=wmic useraccount where name='%username%' get sid

%sid%

Then I need to take username and remove .DNS from it, but I don't know how can I do that.
Can i write someting like "delete after "." "point" in batch?

Body:
I found my self and this script needs admin privileges.

::get usersid first
for /F "tokens=2" %%i in ('whoami /user /fo table /nh') do set usersid=%%i

::get userpath
for /F "tokens=3" %%i in ('reg QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%usersid%" /v "ProfileImagePath"') do set oldpath=%%i

::delete after "."
for /f "tokens=1 delims=." %%a in ('echo %oldpath%') do set newpath=%%a

::update the reg with new path
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%usersid%" /v "ProfileImagePath" /t REG_EXPAND_SZ /d "%newpath%" /f

echo EVERYTHING OKAY MATE!
pause


问:
How to count Firebase child items that match a certain criteria
For each user account I'm trying to count how many events they have today.

My data is structured as follows:

```<code>accounts -
{
 "-KaxcGWx1-a8s7dhsjhsd" : {
 "name" : "Bill",
 "events" : [ {
  "event" : "-KdHscYor4mA--ubIHBj"
 }, {
  "event" : "-KdKsJBdHimgPPQQ6bcA"
 } ],
 },
 "-KaxcGWx1-rA2anjKI4h" : {
 "name" : "Bob",
 "username" : "Bob"
 "events" : [ {
  "event" : "-KdHscYor4mA--ubIHBj"
 }]
 }
}

events -
{
 "-KdHscYor4mA--ubIHBj" : {
   "dateCreated" : "Fri Feb 17 2017 23:37:32 GMT+0000 (GMT)",
   "eventDate" : "2017-04-01",
   "name" : "Event 1",
},
 "-KdKsJBdHimgPPQQ6bcA" : {
   "dateCreated" : "Fri Feb 17 2017 23:37:32 GMT+0000 (GMT)",
   "eventDate" : "2017-04-01",
   "name" : "Event 2",
 }
 }
</code>```

So given that both events are for today. I would expect to Bill to have two and Bob to have one.

The code I have tried is:

```<code>var todayDate = '2017-04-01';
var ref = firebase.database().ref('accounts/');
ref.once('value', function (snapshot) {
    //Foreach user account
    var eventCount = 0;
    snapshot.forEach(function (account) {
        var ref = firebase.database().ref('accounts/' + account.key);
        ref.child('events').once('value', function (eventSnapshot) {
            //Foreach event
            eventSnapshot.forEach(function (child) {
                firebase.database().ref('events/' + child.val().event).once('value', function (event) {
                        if (eventDate === todayDate) {
                            console.log(account.val().name, 'has an event today -', event.val().name);
                            eventCount++;
                        }
                });
            });
        });
        console.log(account.val().name, 'total events -', eventCount);
    });
});
</code>```

However, the result I'm getting in the console is:

```<code>Bill total events - 0
Bob total events - 0
Bill has an event today Event 1
Bill has an event today Event 2
Bob has an event today Event 2
</code>```

答:
The problem is with the general structure of your code. You're deeply nesting calls to ref.once('value') and expecting them all to execute synchronously.  However, once() is asynchronous.  That function always returns immediately - it does not wait for the snapshot.  Sometime later, whenever the data is available, your callback is called with the snapshot.  This means your foreach loops are iterating each child of the snapshot and finishing before any of your snapshot callbacks are called.  And that results in your counts being 0.

You're going to need to completely restructure your code in an event-driven asynchronous fashion rather than the procedural synchronous way you have it now.

Body:
For each user account I'm trying to count how many events they have today.

My data is structured as follows:

accounts -
{
 "-KaxcGWx1-a8s7dhsjhsd" : {
 "name" : "Bill",
 "events" : [ {
  "event" : "-KdHscYor4mA--ubIHBj"
 }, {
  "event" : "-KdKsJBdHimgPPQQ6bcA"
 } ],
 },
 "-KaxcGWx1-rA2anjKI4h" : {
 "name" : "Bob",
 "username" : "Bob"
 "events" : [ {
  "event" : "-KdHscYor4mA--ubIHBj"
 }]
 }
}

events -
{
 "-KdHscYor4mA--ubIHBj" : {
   "dateCreated" : "Fri Feb 17 2017 23:37:32 GMT+0000 (GMT)",
   "eventDate" : "2017-04-01",
   "name" : "Event 1",
},
 "-KdKsJBdHimgPPQQ6bcA" : {
   "dateCreated" : "Fri Feb 17 2017 23:37:32 GMT+0000 (GMT)",
   "eventDate" : "2017-04-01",
   "name" : "Event 2",
 }
 }

So given that both events are for today. I would expect to Bill to have two and Bob to have one.

The code I have tried is:

var todayDate = '2017-04-01';
var ref = firebase.database().ref('accounts/');
ref.once('value', function (snapshot) {
    //Foreach user account
    var eventCount = 0;
    snapshot.forEach(function (account) {
        var ref = firebase.database().ref('accounts/' + account.key);
        ref.child('events').once('value', function (eventSnapshot) {
            //Foreach event
            eventSnapshot.forEach(function (child) {
                firebase.database().ref('events/' + child.val().event).once('value', function (event) {
                        if (eventDate === todayDate) {
                            console.log(account.val().name, 'has an event today -', event.val().name);
                            eventCount++;
                        }
                });
            });
        });
        console.log(account.val().name, 'total events -', eventCount);
    });
});

However, the result I'm getting in the console is:

Bill total events - 0
Bob total events - 0
Bill has an event today Event 1
Bill has an event today Event 2
Bob has an event today Event 2


问:
Queue is not adding object properly
I am having some issues, like in the title, with adding objects to a queue in java. I am trying to write some code that simulates a toll booth, cars, and a queue. Below is the code.

```<code>    //Below is creating and naming objects and variables
    int numberOfCars, numberOfTollbooths;
    double tollboothTotalServiceTime = 0, tollboothAverageServiceTime = 0;
    Scanner keyboard = new Scanner(System.in);
    ExpRandom random = new ExpRandom(13);
    Queue<Car> carQueue = new LinkedList<Car>();

    //Asks the user how many cars need to be created for this simulation
    System.out.print("How many cars do you want to simulate? ");
    numberOfCars = Integer.parseInt(keyboard.next());

    for(int i = 1; i <= numberOfCars; i++)
    {
        carQueue.add(new Car(i, Increasing.increasingNumber()/10));
        System.out.println("Car queue: [" + carQueue.poll() + "]");
    }
</code>```

Output:

```<code>#1 arrived at time 1.
Car queue: [#1]
#2 arrived at time 2.
Car queue: [#2]
#3 arrived at time 4.
Car queue: [#3]
#4 arrived at time 18.
Car queue: [#4]
#5 arrived at time 33.
Car queue: [#5]
#6 arrived at time 38.
Car queue: [#6]
#7 arrived at time 42.
Car queue: [#7]
#8 arrived at time 47.
Car queue: [#8]
#9 arrived at time 48.
Car queue: [#9]
#10 arrived at time 52.
Car queue: [#10]
#11 arrived at time 53.
Car queue: [#11]
#12 arrived at time 58.
Car queue: [#12]
</code>```

how can i see the whole carQueue once all the cars are added? something like Car queue: [1,2,3,4...]

答:
poll removes the head of the queue, use peek instead.

```<code>System.out.println("Car queue: [" + carQueue.peek() + "]");
</code>```

Title: Queue is not adding object properly

Body:
I am having some issues, like in the title, with adding objects to a queue in java. I am trying to write some code that simulates a toll booth, cars, and a queue. Below is the code.

    //Below is creating and naming objects and variables
    int numberOfCars, numberOfTollbooths;
    double tollboothTotalServiceTime = 0, tollboothAverageServiceTime = 0;
    Scanner keyboard = new Scanner(System.in);
    ExpRandom random = new ExpRandom(13);
    Queue<Car> carQueue = new LinkedList<Car>();

    //Asks the user how many cars need to be created for this simulation
    System.out.print("How many cars do you want to simulate? ");
    numberOfCars = Integer.parseInt(keyboard.next());

    for(int i = 1; i <= numberOfCars; i++)
    {
        carQueue.add(new Car(i, Increasing.increasingNumber()/10));
        System.out.println("Car queue: [" + carQueue.poll() + "]");
    }

Output:

#1 arrived at time 1.
Car queue: [#1]
#2 arrived at time 2.
Car queue: [#2]
#3 arrived at time 4.
Car queue: [#3]
#4 arrived at time 18.
Car queue: [#4]
#5 arrived at time 33.
Car queue: [#5]
#6 arrived at time 38.
Car queue: [#6]
#7 arrived at time 42.
Car queue: [#7]
#8 arrived at time 47.
Car queue: [#8]
#9 arrived at time 48.
Car queue: [#9]
#10 arrived at time 52.
Car queue: [#10]
#11 arrived at time 53.
Car queue: [#11]
#12 arrived at time 58.
Car queue: [#12]

how can i see the whole carQueue once all the cars are added? something like Car queue: [1,2,3,4...]

Body:
poll removes the head of the queue, use peek instead.

System.out.println("Car queue: [" + carQueue.peek() + "]");


问:
Adobe's Packager for iPhone
Can Adobe's Packager for iPhone be used for building applications from Flash Builder for Adobe AIR apps? Or is it that only Flash CS5 can be used for iphone apps? I want to deploy AIR apps built for the PC to ipad/iphone. Is that possible in any way?</p>

答: You could use an ant task into Flash Builder to manual compile you ipa using the instruction provided by Greg</p>

Title: Adobe's Packager for iPhone


问:
Ajax Form doesn't remain on page
Been beating my mind at this but its now time for me to ask for help (ask i got work tomorrow and dont want to be on this all night)

My form is inside a modal and this is my script

```<code>$(function() {
    $("#applyForm").on('submit' , function(e) {
        $.ajax({
            type: 'POST',
            url: $("#applyForm").attr("action"),
            data: $('#applyForm').serialize(),
            success: function(data){
              alert('successfully submitted')},
            error: function(data){
              alert('something went wrong')
          }

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

It all works, It fires up the script and submits to the backend with a success message but as soon as you close the popup sucess message it redirects to the action "apply-now" page.

How can i prevent this without it breaking the submit, As i've tried return false and preventDefault.

Heres the form

```<code><form action="/apply-now/" enctype="multipart/form-data" id="applyForm" method="post" name="applyForm" class="form">
<input name="is_data_submitted" type="hidden" value="1">
<input name="listing_id" type="hidden" value="{$listing_id}">

MY FORM DATA

<button type="submit" id="submit" class="btn btn-warning">Apply now</button>
</code>```

Any help would really be appreciated !

Thanks

J

答:
You're not preventing the default form submission behavior. To fix up, add the following immediately before your Ajax call:

```<code>e.preventDefault();
</code>```

Extra tip: to ensure the form only gets submitted once per "submit" click, stop the propagation of the click event from bubbling up through the DOM.

Immediately following the preventDefault, put this:

```<code>e.stopPropagation();
</code>```

Title: Ajax Form doesn't remain on page

Body:
Been beating my mind at this but its now time for me to ask for help (ask i got work tomorrow and dont want to be on this all night)

My form is inside a modal and this is my script

$(function() {
    $("#applyForm").on('submit' , function(e) {
        $.ajax({
            type: 'POST',
            url: $("#applyForm").attr("action"),
            data: $('#applyForm').serialize(),
            success: function(data){
              alert('successfully submitted')},
            error: function(data){
              alert('something went wrong')
          }

     });
});
});

It all works, It fires up the script and submits to the backend with a success message but as soon as you close the popup sucess message it redirects to the action "apply-now" page.

How can i prevent this without it breaking the submit, As i've tried return false and preventDefault.

Heres the form

<form action="/apply-now/" enctype="multipart/form-data" id="applyForm" method="post" name="applyForm" class="form">
<input name="is_data_submitted" type="hidden" value="1">
<input name="listing_id" type="hidden" value="{$listing_id}">

MY FORM DATA

<button type="submit" id="submit" class="btn btn-warning">Apply now</button>

Any help would really be appreciated !

Thanks

J

Body:
You're not preventing the default form submission behavior. To fix up, add the following immediately before your Ajax call:

e.preventDefault();

Extra tip: to ensure the form only gets submitted once per "submit" click, stop the propagation of the click event from bubbling up through the DOM.

Immediately following the preventDefault, put this:

e.stopPropagation();


问:
Returning an element from list
I'm trying to return an individual from the list that has fitness greater than or equal to 90. To do so I have to sort the list, but I think there is a better way.. how can I do this withought sorting. Like at the instant when the if condition becomes true print that perticular individual from the list.</p>

```<code>    if any(individual.fitness >= 90 for individual in individuals):
        print('Threshold met!')
        individuals = sorted(
            individuals, key=lambda individual: individual.fitness, reverse=True)
        return individuals[0]
</code>```

答:
Here you are :) :</p>

```<code>for individual in individuals:
    if individual.fitness >= 90:
        print('Threshold met!')
        return individual
return None
</code>```

Title: Returning an element from list

Body:
I'm trying to return an individual from the list that has fitness greater than or equal to 90. To do so I have to sort the list, but I think there is a better way.. how can I do this withought sorting. Like at the instant when the if condition becomes true print that perticular individual from the list.

    if any(individual.fitness >= 90 for individual in individuals):
        print('Threshold met!')
        individuals = sorted(
            individuals, key=lambda individual: individual.fitness, reverse=True)
        return individuals[0]

Body:
Here you are :) :

for individual in individuals:
    if individual.fitness >= 90:
        print('Threshold met!')
        return individual
return None


问:
Python: Importing urllib.quote
I would like to use urllib.quote(). But python (python3) is not finding the module.
Suppose, I have this line of code:

```<code>print(urllib.quote("châteu", safe=''))
</code>```

How do I import urllib.quote?

import urllib or
import urllib.quote both give

```<code>AttributeError: 'module' object has no attribute 'quote'
</code>```

What confuses me is that urllib.request is accessible via import urllib.request

答:
If you need to handle both Python 2.x and 3.x you can catch the exception and load the alternative.

```<code>try:
    from urllib import quote  # Python 2.X
except ImportError:
    from urllib.parse import quote  # Python 3+
</code>```

You could also use the python compatibility wrapper six to handle this.

```<code>from six.moves.urllib.parse import quote
</code>```

Title: Python: Importing urllib.quote

Body:
I would like to use urllib.quote(). But python (python3) is not finding the module.
Suppose, I have this line of code:

print(urllib.quote("châteu", safe=''))

How do I import urllib.quote?

import urllib or
import urllib.quote both give

AttributeError: 'module' object has no attribute 'quote'

What confuses me is that urllib.request is accessible via import urllib.request

Body:
If you need to handle both Python 2.x and 3.x you can catch the exception and load the alternative.

try:
    from urllib import quote  # Python 2.X
except ImportError:
    from urllib.parse import quote  # Python 3+

You could also use the python compatibility wrapper six to handle this.

from six.moves.urllib.parse import quote


问:
Ngrx Store, Effects, Http Ajax Polling Setup on Angular 2
I'm creating an Ngrx Angular 2 app and was trying to get my http calls to continue polling after a time interval. I have seen the use of the interval() function, but in case of Ngrx, when service calls are done inside @Effect(), it gives an error. Please advise:

```<code>@Injectable()
export class TasksEffects {
constructor(
    private actions$: Actions,
    private TS: TaskService
){}

@Effect()
onLoadTasksLoadTasks$: Observable<Action> = this.actions$.ofType(tasksActions.ActionTypes.LOAD_TASKS)
    .switchMap(() => {
        return this.TS.index()
            .map((res) => new tasksActions.LoadTasksSuccessAction(res.json()))
            .catch(err => of(new tasksActions.LoadTasksFailAction(err)));
    });
</code>```

I want to run the switchMap function every ten seconds. This does not work.

```<code>    @Effect()
onLoadTasksLoadTasks$: Observable<Action> = this.actions$.ofType(tasksActions.ActionTypes.LOAD_TASKS)
    .switchMap(() => {
        return this.TS.index()
            .map((res) => new tasksActions.LoadTasksSuccessAction(res.json()))
            .catch(err => of(new tasksActions.LoadTasksFailAction(err)));
    }).interval(10000);
</code>```

The type error is:

答:
As stated in the other answer, interval is a static function, so it does not exist on the Observable prototype - which is why your error is effected.

Instead, you should be able to achieve what you want using timer.

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/timer';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';

@Effect()
onLoadTasksLoadTasks$: Observable<Action> = this.actions$
  .ofType(tasksActions.ActionTypes.LOAD_TASKS)
  .switchMap(() => Observable
    .timer(0, 10000)
    .switchMap(() => this.TS.index()
      .map((res) => new tasksActions.LoadTasksSuccessAction(res.json()))
      .catch(err => Observable.of(new tasksActions.LoadTasksFailAction(err)))
    )
  );
```

With timer, it's possible to specify an initial delay and here it's set to zero so that the timer fires immediately. After that, it will fire every ten seconds, but if another LOAD_TASKS action is received, the switchMap will see it unsubscribed and a new timer created, etc.

Body:
I'm creating an Ngrx Angular 2 app and was trying to get my http calls to continue polling after a time interval. I have seen the use of the interval() function, but in case of Ngrx, when service calls are done inside @Effect(), it gives an error. Please advise:

@Injectable()
export class TasksEffects {
constructor(
    private actions$: Actions,
    private TS: TaskService
){}

@Effect()
onLoadTasksLoadTasks$: Observable<Action> = this.actions$.ofType(tasksActions.ActionTypes.LOAD_TASKS)
    .switchMap(() => {
        return this.TS.index()
            .map((res) => new tasksActions.LoadTasksSuccessAction(res.json()))
            .catch(err => of(new tasksActions.LoadTasksFailAction(err)));
    });

I want to run the switchMap function every ten seconds. This does not work.

    @Effect()
onLoadTasksLoadTasks$: Observable<Action> = this.actions$.ofType(tasksActions.ActionTypes.LOAD_TASKS)
    .switchMap(() => {
        return this.TS.index()
            .map((res) => new tasksActions.LoadTasksSuccessAction(res.json()))
            .catch(err => of(new tasksActions.LoadTasksFailAction(err)));
    }).interval(10000);

The type error is:

Body:
As stated in the other answer, interval is a static function, so it does not exist on the Observable prototype - which is why your error is effected.

Instead, you should be able to achieve what you want using timer.

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/timer';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';

@Effect()
onLoadTasksLoadTasks$: Observable<Action> = this.actions$
  .ofType(tasksActions.ActionTypes.LOAD_TASKS)
  .switchMap(() => Observable
    .timer(0, 10000)
    .switchMap(() => this.TS.index()
      .map((res) => new tasksActions.LoadTasksSuccessAction(res.json()))
      .catch(err => Observable.of(new tasksActions.LoadTasksFailAction(err)))
    )
  );

With timer, it's possible to specify an initial delay and here it's set to zero so that the timer fires immediately. After that, it will fire every ten seconds, but if another LOAD_TASKS action is received, the switchMap will see it unsubscribed and a new timer created, etc.