问:
How to create modal box using html, css and jquery?
How to create modal box using html, css and jquery?
    </p>

```<code><button id="myBtn">Open Modal</button>
</code>```

<p>
    </p>

```<code>  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">×</span>
    <p>Some text in the Modal..</p>
  </div>

</div>
</code>```

答:
For creating a modal, it often takes more than just HTML, you often have to use Javascript. I have created a very minor one for you to aid you understanding.

The CSS is there to style the button and hide elements show they do not show, the Javascript activates the actual function of the modal. All you would have to do from here is edit the HTML to whatever you want it to say.

var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 15% auto; /* 15% from the top and centered */
    padding: 20px;
    border: 1px solid #888;
    width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}</code>```

<button id="myBtn">Open Modal</button>

    ×

Some text in the Modal..

```

Body:
How to create modal box using html, css and jquery?

<button id="myBtn">Open Modal</button>

    ×

Some text in the Modal..

Body:
For creating a modal, it often takes more than just HTML, you often have to use Javascript. I have created a very minor one for you to aid you understanding.

The CSS is there to style the button and hide elements show they do not show, the Javascript activates the actual function of the modal. All you would have to do from here is edit the HTML to whatever you want it to say.

var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 15% auto; /* 15% from the top and centered */
    padding: 20px;
    border: 1px solid #888;
    width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}

<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal..</p>
  </div>

</div>


来源: stackexchange

问:
Why an object is invisible?
I have a class. In this class I declare a a private variable private Agent agent;. In my class I have

```<code>private Thread controller = new Thread() {
...
}
</code>```

Within the above private thread I call getParameter which is a private method of the considered class. Within the getParameter I call one of the methods of the agent. As a result I get a NullPointerException. So, I conclude that agent is not visible from the getParameter.

Why is that? Can it be that the reason of that is that the getParameter is within the private Thread? And, if it is the case, how the described problem can be resolved?

ADDED

I realized that I need to be more specific. My code is organized like that:

```<code>public class GameWindow {
   ...
   private Agent agent;
   ...
   private Thread controller = new Thread() {
        public void run() {
           ...
           Agent agent = new Agent();
           ...
           parameter = getParameter();
        }
  }
  ...
  private String getParameter() {
     ...
     agent.someMethod();
     ...
  }
}
</code>```

ADDED 2
In the GameWindow I have:

```<code>public void startWindow() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            controller.start();
        }
    });
}
</code>```

答:
Ditto Roman, but let me add one clarifying point.

If you do not have visibility to an object, you will get an error message when you try to compile. A null pointer exception is a RUNTIME error, not a compile-time error. You will never, ever get a null pointer exception for a visibility problem, for the simple reason that you will not be able to run the program if you have visibility problems, because the compile will have failed.

A null pointer exception means that you have not assigned an actual instance of the object to a variable. That could mean you never created an instance at all, or it could mean that you have one declaration hiding another, like here.

ContentLicense: CC BY-SA 2.5

Title: Why an object is invisible?

Body:
I have a class. In this class I declare a a private variable private Agent agent;. In my class I have

private Thread controller = new Thread() {
...
}

Within the above private thread I call getParameter which is a private method of the considered class. Within the getParameter I call one of the methods of the agent. As a result I get a NullPointerException. So, I conclude that agent is not visible from the getParameter.

Why is that? Can it be that the reason of that is that the getParameter is within the private Thread? And, if it is the case, how the described problem can be resolved?

ADDED

I realized that I need to be more specific. My code is organized like that:

public class GameWindow {
   ...
   private Agent agent;
   ...
   private Thread controller = new Thread() {
        public void run() {
           ...
           Agent agent = new Agent();
           ...
           parameter = getParameter();
        }
  }
  ...
  private String getParameter() {
     ...
     agent.someMethod();
     ...
  }
}

ADDED 2
In the GameWindow I have:

public void startWindow() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            controller.start();
        }
    });
}


问:
Drag'n drop files from the OS to Java application (Swing)
Let me start by saying that I have been reading the drag'n drop tutorial and similar questions asked on SO, but unfortunately I have only gotten more confused about this matter. What I want to achieve is relatively simple so I am surprised that it got me in so much trouble already. I am writing a small utility application which will consolidate a bunch of result files (custom defined xml-type) into a large tab-separated text file. Most of the functionality is already coded, however I wanted to make a decent GUI for it.

What I want is to be able to drag'n drop files into a component (for instance JTextArea) in a nice and gracious way (read: not full paths, but instead a small icon and name). I would like to be able to supply a JFileChooser to browse for files as well. I will then parse the files sequentially to produce the matrix I want.

What I have learned so far is that the framework is already there however any additional functionality needs to be custom built. I have created a test GUI in Netbeans and tried to drag a bunch of files onto a JTextArea, but they appear as file paths, and admittedly it looks very ugly.

I would really appreciate any tips and guidance on how to solve (or clarify) this problem in a neat way. Note that I do intend to use the software on multiple different OS (Mac,Win and Linux).

EDIT: the code I have so far is based on one of the examples from Sun tutorials and is as follows

```<code>import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.*;

public class ConsolidatorDemo extends JPanel implements ActionListener {
    private static final long serialVersionUID = -4487732343062917781L;
    JFileChooser fc;
    JButton clear;
    JTextArea dropZone, console;
    JSplitPane childSplitPane, parentSplitPane;
    PrintStream ps;

  public ConsolidatorDemo() {
    super(new BorderLayout());

    fc = new JFileChooser();;
    fc.setMultiSelectionEnabled(true);
    fc.setDragEnabled(true);
    fc.setControlButtonsAreShown(false);
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

    JPanel fcPanel = new JPanel(new BorderLayout());
    fcPanel.add(fc, BorderLayout.CENTER);

    clear = new JButton("Clear All");
    clear.addActionListener(this);
    JPanel buttonPanel = new JPanel(new BorderLayout());
    buttonPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    buttonPanel.add(clear, BorderLayout.LINE_END);

    JPanel leftUpperPanel = new JPanel(new BorderLayout());
    leftUpperPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    leftUpperPanel.add(fcPanel, BorderLayout.CENTER);
    leftUpperPanel.add(buttonPanel, BorderLayout.PAGE_END);

    JScrollPane leftLowerPanel = new javax.swing.JScrollPane();
    leftLowerPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    dropZone = new JTextArea();
    dropZone.setColumns(20);
    dropZone.setLineWrap(true);
    dropZone.setRows(5);
    dropZone.setDragEnabled(true);
    dropZone.setDropMode(javax.swing.DropMode.INSERT);
    dropZone.setBorder(new TitledBorder("Selected files/folders"));
    leftLowerPanel.setViewportView(dropZone);

    childSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
            leftUpperPanel, leftLowerPanel);
    childSplitPane.setDividerLocation(400);
    childSplitPane.setPreferredSize(new Dimension(480, 650));

    console = new JTextArea();
    console.setColumns(40);
    console.setLineWrap(true);
    console.setBorder(new TitledBorder("Console"));

    parentSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                    childSplitPane, console);
    parentSplitPane.setDividerLocation(480);
    parentSplitPane.setPreferredSize(new Dimension(800, 650));

    add(parentSplitPane, BorderLayout.CENTER);

}

public void setDefaultButton() {
    getRootPane().setDefaultButton(clear);
}

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == clear) {
        dropZone.setText("");

    }
}

/**
 * Create the GUI and show it. For thread safety,
 * this method should be invoked from the
 * event-dispatching thread.
 */
private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    try {
      //UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaBlackStarLookAndFeel");
        for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    }catch (Exception e){
      e.printStackTrace();
    }

    //Create and set up the window.
    JFrame frame = new JFrame("Consolidator!");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    //Create and set up the menu bar and content pane.
    ConsolidatorDemo demo = new ConsolidatorDemo();
    demo.setOpaque(true); //content panes must be opaque
    frame.setContentPane(demo);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
    demo.setDefaultButton();
}

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}
</code>```

答:
Here is the code without console and extra button </p>

```<code>import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.PrintStream;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileSystemView;

public class ConsolidatorDemo extends JPanel implements ActionListener {
    private static final long serialVersionUID = -4487732343062917781L;
    // JFileChooser fc;
    JButton clear,compare;
    JTextArea fc;

    JList dropZone;
    DefaultListModel listModel;
    JSplitPane childSplitPane, parentSplitPane;
    PrintStream ps;

    public ConsolidatorDemo() {
        super(new BorderLayout());

        /* fc = new JFileChooser();;
    fc.setMultiSelectionEnabled(true);
    fc.setDragEnabled(true);
    fc.setControlButtonsAreShown(false);
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);*/
        fc= new JTextArea();
        fc.setText("Rules:\n1. drop old html first.\n2. drop new html.\n3. drop output folder.\n4. click compare button.\n5. Check output in the output.txt file.\nEnd");

        fc.setEditable(false);
        JPanel fcPanel = new JPanel(new BorderLayout());

        fcPanel.add(fc, BorderLayout.CENTER);

        compare = new JButton("Compare");
        compare.addActionListener(this);
        JPanel buttonPanel1 = new JPanel(new BorderLayout());
        buttonPanel1.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
        buttonPanel1.add(compare, BorderLayout.LINE_END);

        clear = new JButton("Clear All");
        clear.addActionListener(this);
        JPanel buttonPanel = new JPanel(new BorderLayout());
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
        buttonPanel.add(clear, BorderLayout.LINE_END);

        JPanel leftUpperPanel = new JPanel(new BorderLayout());
        leftUpperPanel.setBorder(BorderFactory.createEmptyBorder(3,3,3,3));
        leftUpperPanel.add(fcPanel, BorderLayout.CENTER);
        leftUpperPanel.add(buttonPanel1, BorderLayout.LINE_END);
        leftUpperPanel.add(buttonPanel, BorderLayout.PAGE_END);

        JScrollPane leftLowerPanel = new javax.swing.JScrollPane();
        leftLowerPanel.setBorder(BorderFactory.createEmptyBorder(3,3,3,3));

        listModel = new DefaultListModel();
        dropZone = new JList(listModel);
        dropZone.setCellRenderer(new FileCellRenderer());
        dropZone.setTransferHandler(new ListTransferHandler(dropZone));
        dropZone.setDragEnabled(true);
        dropZone.setDropMode(javax.swing.DropMode.INSERT);
        dropZone.setBorder(new TitledBorder("Drag and drop files here"));
        leftLowerPanel.setViewportView(new JScrollPane(dropZone));

        childSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, leftLowerPanel,leftUpperPanel);
        childSplitPane.setDividerLocation(200);//400
        childSplitPane.setPreferredSize(new Dimension(300, 400));//480, 650

        /*console = new JTextArea();
    console.setColumns(40);
    console.setLineWrap(true);
    console.setBorder(new TitledBorder("Console"));

    parentSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                    childSplitPane, console);
    parentSplitPane.setDividerLocation(480);
    parentSplitPane.setPreferredSize(new Dimension(800, 650));*/

        add(childSplitPane, BorderLayout.CENTER);

    }

    public void setDefaultButton() {
        getRootPane().setDefaultButton(clear);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == clear) {
            listModel.clear();
        }else if (e.getSource() == compare) {
            //our function
        }
    }

    /**
     * Create the GUI and show it. For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);
        try {
            //UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaBlackStarLookAndFeel");
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        //Create and set up the window.
        JFrame frame = new JFrame("Bill of materials Comparer");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        //Create and set up the menu bar and content pane.
        ConsolidatorDemo demo = new ConsolidatorDemo();
        demo.setOpaque(true); //content panes must be opaque
        frame.setContentPane(demo);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
        demo.setDefaultButton();
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

class FileCellRenderer extends DefaultListCellRenderer {

    public Component getListCellRendererComponent(JList list,Object value,int index,boolean isSelected,boolean cellHasFocus) {

        Component c = super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);

        if (c instanceof JLabel && value instanceof File) {
            JLabel l = (JLabel)c;
            File f = (File)value;
            l.setIcon(FileSystemView.getFileSystemView().getSystemIcon(f));
            l.setText(f.getName());
            //l.setText(f.getAbsolutePath());
            l.setToolTipText(f.getAbsolutePath());
        }

        return c;
    }
}

class ListTransferHandler extends TransferHandler {

    private JList list;

    ListTransferHandler(JList list) {
        this.list = list;
    }

    @Override
    public boolean canImport(TransferHandler.TransferSupport info) {
        // we only import FileList
        if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            return false;
        }
        return true;
    }

    @Override
    public boolean importData(TransferHandler.TransferSupport info) {
        if (!info.isDrop()) {
            return false;
        }

        // Check for FileList flavor
        if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            displayDropLocation("List doesn't accept a drop of this type.");
            return false;
        }

        // Get the fileList that is being dropped.
        Transferable t = info.getTransferable();
        List<File> data;
        try {
            data = (List<File>)t.getTransferData(DataFlavor.javaFileListFlavor);
        }
        catch (Exception e) { return false; }
        DefaultListModel model = (DefaultListModel) list.getModel();
        for (Object file : data) {
            model.addElement((File)file);
        }
        return true;
    }

    private void displayDropLocation(String string) {
        System.out.println(string);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Let me start by saying that I have been reading the drag'n drop tutorial and similar questions asked on SO, but unfortunately I have only gotten more confused about this matter. What I want to achieve is relatively simple so I am surprised that it got me in so much trouble already. I am writing a small utility application which will consolidate a bunch of result files (custom defined xml-type) into a large tab-separated text file. Most of the functionality is already coded, however I wanted to make a decent GUI for it.

What I want is to be able to drag'n drop files into a component (for instance JTextArea) in a nice and gracious way (read: not full paths, but instead a small icon and name). I would like to be able to supply a JFileChooser to browse for files as well. I will then parse the files sequentially to produce the matrix I want.

What I have learned so far is that the framework is already there however any additional functionality needs to be custom built. I have created a test GUI in Netbeans and tried to drag a bunch of files onto a JTextArea, but they appear as file paths, and admittedly it looks very ugly.

I would really appreciate any tips and guidance on how to solve (or clarify) this problem in a neat way. Note that I do intend to use the software on multiple different OS (Mac,Win and Linux).

EDIT: the code I have so far is based on one of the examples from Sun tutorials and is as follows

import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.*;

public class ConsolidatorDemo extends JPanel implements ActionListener {
    private static final long serialVersionUID = -4487732343062917781L;
    JFileChooser fc;
    JButton clear;
    JTextArea dropZone, console;
    JSplitPane childSplitPane, parentSplitPane;
    PrintStream ps;

  public ConsolidatorDemo() {
    super(new BorderLayout());

    fc = new JFileChooser();;
    fc.setMultiSelectionEnabled(true);
    fc.setDragEnabled(true);
    fc.setControlButtonsAreShown(false);
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

    JPanel fcPanel = new JPanel(new BorderLayout());
    fcPanel.add(fc, BorderLayout.CENTER);

    clear = new JButton("Clear All");
    clear.addActionListener(this);
    JPanel buttonPanel = new JPanel(new BorderLayout());
    buttonPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    buttonPanel.add(clear, BorderLayout.LINE_END);

    JPanel leftUpperPanel = new JPanel(new BorderLayout());
    leftUpperPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    leftUpperPanel.add(fcPanel, BorderLayout.CENTER);
    leftUpperPanel.add(buttonPanel, BorderLayout.PAGE_END);

    JScrollPane leftLowerPanel = new javax.swing.JScrollPane();
    leftLowerPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    dropZone = new JTextArea();
    dropZone.setColumns(20);
    dropZone.setLineWrap(true);
    dropZone.setRows(5);
    dropZone.setDragEnabled(true);
    dropZone.setDropMode(javax.swing.DropMode.INSERT);
    dropZone.setBorder(new TitledBorder("Selected files/folders"));
    leftLowerPanel.setViewportView(dropZone);

    childSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
            leftUpperPanel, leftLowerPanel);
    childSplitPane.setDividerLocation(400);
    childSplitPane.setPreferredSize(new Dimension(480, 650));

    console = new JTextArea();
    console.setColumns(40);
    console.setLineWrap(true);
    console.setBorder(new TitledBorder("Console"));

    parentSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                    childSplitPane, console);
    parentSplitPane.setDividerLocation(480);
    parentSplitPane.setPreferredSize(new Dimension(800, 650));

    add(parentSplitPane, BorderLayout.CENTER);

}

public void setDefaultButton() {
    getRootPane().setDefaultButton(clear);
}

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == clear) {
        dropZone.setText("");

    }
}

/**
 * Create the GUI and show it. For thread safety,
 * this method should be invoked from the
 * event-dispatching thread.
 */
private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    try {
      //UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaBlackStarLookAndFeel");
        for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    }catch (Exception e){
      e.printStackTrace();
    }

    //Create and set up the window.
    JFrame frame = new JFrame("Consolidator!");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    //Create and set up the menu bar and content pane.
    ConsolidatorDemo demo = new ConsolidatorDemo();
    demo.setOpaque(true); //content panes must be opaque
    frame.setContentPane(demo);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
    demo.setDefaultButton();
}

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

Body:
Here is the code without console and extra button

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.PrintStream;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileSystemView;

public class ConsolidatorDemo extends JPanel implements ActionListener {
    private static final long serialVersionUID = -4487732343062917781L;
    // JFileChooser fc;
    JButton clear,compare;
    JTextArea fc;

    JList dropZone;
    DefaultListModel listModel;
    JSplitPane childSplitPane, parentSplitPane;
    PrintStream ps;

    public ConsolidatorDemo() {
        super(new BorderLayout());

        /* fc = new JFileChooser();;
    fc.setMultiSelectionEnabled(true);
    fc.setDragEnabled(true);
    fc.setControlButtonsAreShown(false);
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);*/
        fc= new JTextArea();
        fc.setText("Rules:\n1. drop old html first.\n2. drop new html.\n3. drop output folder.\n4. click compare button.\n5. Check output in the output.txt file.\nEnd");

        fc.setEditable(false);
        JPanel fcPanel = new JPanel(new BorderLayout());

        fcPanel.add(fc, BorderLayout.CENTER);

        compare = new JButton("Compare");
        compare.addActionListener(this);
        JPanel buttonPanel1 = new JPanel(new BorderLayout());
        buttonPanel1.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
        buttonPanel1.add(compare, BorderLayout.LINE_END);

        clear = new JButton("Clear All");
        clear.addActionListener(this);
        JPanel buttonPanel = new JPanel(new BorderLayout());
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
        buttonPanel.add(clear, BorderLayout.LINE_END);

        JPanel leftUpperPanel = new JPanel(new BorderLayout());
        leftUpperPanel.setBorder(BorderFactory.createEmptyBorder(3,3,3,3));
        leftUpperPanel.add(fcPanel, BorderLayout.CENTER);
        leftUpperPanel.add(buttonPanel1, BorderLayout.LINE_END);
        leftUpperPanel.add(buttonPanel, BorderLayout.PAGE_END);

        JScrollPane leftLowerPanel = new javax.swing.JScrollPane();
        leftLowerPanel.setBorder(BorderFactory.createEmptyBorder(3,3,3,3));

        listModel = new DefaultListModel();
        dropZone = new JList(listModel);
        dropZone.setCellRenderer(new FileCellRenderer());
        dropZone.setTransferHandler(new ListTransferHandler(dropZone));
        dropZone.setDragEnabled(true);
        dropZone.setDropMode(javax.swing.DropMode.INSERT);
        dropZone.setBorder(new TitledBorder("Drag and drop files here"));
        leftLowerPanel.setViewportView(new JScrollPane(dropZone));

        childSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, leftLowerPanel,leftUpperPanel);
        childSplitPane.setDividerLocation(200);//400
        childSplitPane.setPreferredSize(new Dimension(300, 400));//480, 650

        /*console = new JTextArea();
    console.setColumns(40);
    console.setLineWrap(true);
    console.setBorder(new TitledBorder("Console"));

    parentSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                    childSplitPane, console);
    parentSplitPane.setDividerLocation(480);
    parentSplitPane.setPreferredSize(new Dimension(800, 650));*/

        add(childSplitPane, BorderLayout.CENTER);

    }

    public void setDefaultButton() {
        getRootPane().setDefaultButton(clear);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == clear) {
            listModel.clear();
        }else if (e.getSource() == compare) {
            //our function
        }
    }

    /**
     * Create the GUI and show it. For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);
        try {
            //UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaBlackStarLookAndFeel");
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        //Create and set up the window.
        JFrame frame = new JFrame("Bill of materials Comparer");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        //Create and set up the menu bar and content pane.
        ConsolidatorDemo demo = new ConsolidatorDemo();
        demo.setOpaque(true); //content panes must be opaque
        frame.setContentPane(demo);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
        demo.setDefaultButton();
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

class FileCellRenderer extends DefaultListCellRenderer {

    public Component getListCellRendererComponent(JList list,Object value,int index,boolean isSelected,boolean cellHasFocus) {

        Component c = super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);

        if (c instanceof JLabel && value instanceof File) {
            JLabel l = (JLabel)c;
            File f = (File)value;
            l.setIcon(FileSystemView.getFileSystemView().getSystemIcon(f));
            l.setText(f.getName());
            //l.setText(f.getAbsolutePath());
            l.setToolTipText(f.getAbsolutePath());
        }

        return c;
    }
}

class ListTransferHandler extends TransferHandler {

    private JList list;

    ListTransferHandler(JList list) {
        this.list = list;
    }

    @Override
    public boolean canImport(TransferHandler.TransferSupport info) {
        // we only import FileList
        if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            return false;
        }
        return true;
    }

    @Override
    public boolean importData(TransferHandler.TransferSupport info) {
        if (!info.isDrop()) {
            return false;
        }

        // Check for FileList flavor
        if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            displayDropLocation("List doesn't accept a drop of this type.");
            return false;
        }

        // Get the fileList that is being dropped.
        Transferable t = info.getTransferable();
        List<File> data;
        try {
            data = (List<File>)t.getTransferData(DataFlavor.javaFileListFlavor);
        }
        catch (Exception e) { return false; }
        DefaultListModel model = (DefaultListModel) list.getModel();
        for (Object file : data) {
            model.addElement((File)file);
        }
        return true;
    }

    private void displayDropLocation(String string) {
        System.out.println(string);
    }
}


问:
Cannot add into an already initialized array
```<code>document.getElementById('form').addEventListener('submit', saveItem);
function saveItem(e){
var items= document.getElementById('items').value;
var date= document.getElementById('date').value;
var price= document.getElementById('price').value;
var expense= {
    items: items,
    date: date,
    price: price
}

if(localStorage.getItem('bill')==null){
var bill=[];
 bill.push(expense);
 localStorage.setItem('bill', JSON.stringify(expense));

} else{

var bill = JSON.parse(localStorage.getItem('bill'));

bill.push(expense);
localStorage.setItem('bill', JSON.stringify(expense));
console.log(bill);

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

there is no error if

```<code>if(localStorage.getItem('bill')==null)
</code>```

but there comes error at else as

```<code> Uncaught TypeError: Cannot read property 'push' of undefined
  at HTMLFormElement.saveItem
</code>```

the data is stored when the local storage is empty but cannot add data if it is not.

答:
Your expense is a object, you need to save the bill inside the local storage.</p>

```<code>if(localStorage.getItem('bill')==null){
 var bill=[];
 bill.push(expense);
 localStorage.setItem('bill', JSON.stringify(bill));
}
</code>```

Body:
document.getElementById('form').addEventListener('submit', saveItem);
function saveItem(e){
var items= document.getElementById('items').value;
var date= document.getElementById('date').value;
var price= document.getElementById('price').value;
var expense= {
    items: items,
    date: date,
    price: price
}

if(localStorage.getItem('bill')==null){
var bill=[];
 bill.push(expense);
 localStorage.setItem('bill', JSON.stringify(expense));

} else{

var bill = JSON.parse(localStorage.getItem('bill'));

bill.push(expense);
localStorage.setItem('bill', JSON.stringify(expense));
console.log(bill);

}
e.preventDefault();
}

there is no error if

if(localStorage.getItem('bill')==null)

but there comes error at else as

 Uncaught TypeError: Cannot read property 'push' of undefined
  at HTMLFormElement.saveItem

the data is stored when the local storage is empty but cannot add data if it is not.

Body:
Your expense is a object, you need to save the bill inside the local storage.

if(localStorage.getItem('bill')==null){
 var bill=[];
 bill.push(expense);
 localStorage.setItem('bill', JSON.stringify(bill));
}


问:
MVVM Hierarchical Navigation tutorial StackOverFlow exception
I'm trying to reproduce a MVVM tutorial for WPF but applying it to UWP. But I've done everything in the tutorial I believe right the exact same code shown at the tutorial.

But when I ran the code I kept getting a StackOverflowException which is caused because the MainPageView keeps initializing again and again, until the exception is thrown.

The thing is I'm kinda knew at MVVM and I wish to master it, so can somebody please explain me why am I getting this?

I'll leave the code of each one of my classes and views.

This is my MainPageView.Xaml:

```<code><Page
x:Class="MVVMHierarchiesDemo.MainPageView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MVVMHierarchiesDemo"
xmlns:views="using:MVVMHierarchiesDemo.Views"
xmlns:viewmodel="using:MVVMHierarchiesDemo.ViewModel"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<!--Anytime the current view model is set to an instance of a CustomerListViewModel,
it will render out a CustomerListView with the ViewModel is hooked up. It’s an order ViewModel,
it'll render out OrderView and so on.

We now need a ViewModel that has a CurrentViewModel property and some logic and commanding
to be able to switch the current reference of ViewModel inside the property.-->
<Page.DataContext>
    <local:MainPageView/>
</Page.DataContext>

<Page.Resources>
    <DataTemplate x:Key="CustomerTemplate" x:DataType="viewmodel:CustomerListViewModel">
        <views:CustomerListView/>
    </DataTemplate>

    <DataTemplate x:Key="OrderTemplate" x:DataType="viewmodel:OrderViewModel">
        <views:OrderView/>
    </DataTemplate>
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <Grid x:Name="NavBar"
          Grid.Row="0">
        <Button Content="Customers"
                Command="{Binding NavCommand}"
                CommandParameter="customers"
                Grid.Column="0"
                Grid.Row="0"/>

        <Button Content="Orders"
                Command="{Binding NavCommand}"
                CommandParameter="orders"
                Grid.Column="2"
                Grid.Row="0"/>
    </Grid>

    <Grid x:Name="MainContent"
          Grid.Row="1">
        <ContentControl Content="{Binding CurrentViewModel}"/>
    </Grid>
</Grid>
</Page>
</code>```

This is my code-behind MainPageView.xaml.cs - here is where the StackoverflowException is thrown in the constructor it keeps calling it.

```<code>using Windows.UI.Xaml.Controls;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace MVVMHierarchiesDemo
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPageView : Page
    {
        public MainPageView()
        {
            this.InitializeComponent();
        }
    }
}
</code>```

This is my BindableBase.cs as the tutorial shows:

```<code>using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace MVVMHierarchiesDemo
{
    /*The main idea behind this class is to encapsulate the INotifyPropertyChanged implementation
     * and provide helper methods to the derived class so that they can easily trigger the appropriate notifications.
     * Following is the implementation of BindableBase class.*/
    public class BindableBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        protected virtual void SetProperty<T>(ref T member, T val, [CallerMemberName]string propertyName = null)
        {
            if (object.Equals(member, val))
                return;

            member = val;
            OnPropertyChanged(propertyName);
        }
    }
}
</code>```

This is MyCommand.cs or better known as the relay command pattern:

```<code>using System;
using System.Windows.Input;

namespace MVVMHierarchiesDemo
{
    /* Now it's time to actually start doing some view switching using our CurrentViewModel property.
     * We just need some way to drive the setting of this property. And we're going to make it so that
     * the end user can command going to the customer list or to the order view. First add a new class
     * in your project which will implement the ICommand interface. Following is the implementation of
     * ICommand interface.*/
    public class MyCommand<T> : ICommand
    {
        Action<T> _TargetExecuteMethod;
        Func<T, bool> _TargetCanExecuteMethod;

        public MyCommand(Action<T> targetExecuteMethod)
        {
            _TargetExecuteMethod = targetExecuteMethod;
        }

        public MyCommand(Action<T> targetExecuteMethod, Func<T,bool> targetCanExecuteMethod)
        {
            _TargetExecuteMethod = targetExecuteMethod;
            _TargetCanExecuteMethod = targetCanExecuteMethod;
        }

        public event EventHandler CanExecuteChanged = delegate { };

        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged?.Invoke(this, EventArgs.Empty);
        }

        bool ICommand.CanExecute(object parameter)
        {
            if (_TargetCanExecuteMethod != null)
            {
                T tparam = (T)parameter;
                return _TargetCanExecuteMethod(tparam);
            }

            if (_TargetExecuteMethod != null)
                return true;

            return false;
        }

        void ICommand.Execute(object parameter)
        {
            if(_TargetExecuteMethod!=null)
            {
                T tparam = (T)parameter;
                _TargetExecuteMethod(tparam);
            }
        }
    }
}
</code>```

This is my usercontrol for OrdersView.xaml:

```<code><UserControl
    x:Class="MVVMHierarchiesDemo.Views.OrderView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MVVMHierarchiesDemo.Views"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400">

    <Grid>
        <TextBlock Text="Order View"/>
    </Grid>
</UserControl>
</code>```

This is my user control CustomerListView.xaml:

```<code><UserControl
    x:Class="MVVMHierarchiesDemo.Views.CustomerListView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MVVMHierarchiesDemo.Views"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400">

    <Grid>
        <TextBlock Text="Customer List View"/>
    </Grid>
</UserControl>
</code>```

This is my OrderViewModel:

```<code>namespace MVVMHierarchiesDemo.ViewModel
{
    /*Derive all of your ViewModels from BindableBase class.*/
    public class OrderViewModel : BindableBase
    {
    }
}
</code>```

This is my CustomerViewModel:

```<code>namespace MVVMHierarchiesDemo.ViewModel
{
    /*Derive all of your ViewModels from BindableBase class.*/
    public class CustomerListViewModel : BindableBase
    {
    }
}
</code>```

Finally this is my MainPageViewModel:

```<code>namespace MVVMHierarchiesDemo.ViewModel
{
    /*Derive all of your ViewModels from BindableBase class.*/
    public class MainPageViewModel : BindableBase
    {
        public MainPageViewModel()
        {
            NavCommand = new MyCommand<string>(OnNavigation);
        }

        private CustomerListViewModel _customerListViewModel = new CustomerListViewModel();

        private OrderViewModel _orderViewModel = new OrderViewModel();

        private BindableBase _currentViewModel;

        public BindableBase CurrentViewModel
        {
            get
            {
                return _currentViewModel;
            }

            set
            {
                SetProperty(ref _currentViewModel, value);
            }
        }

        public MyCommand<string> NavCommand { get; private set; }

        private void OnNavigation(string destination)
        {
            switch (destination)
            {
                case "orders":
                    {
                        CurrentViewModel = _orderViewModel;
                        break;
                    }
                case "customers":
                default:
                    CurrentViewModel = _customerListViewModel;
                    break;
            }
        }
    }
}
</code>```

and lastly I think the MainPageView is the one causing the infinite looping but I don't understand why?

If somebody could be so kind to tell me what I am doing wrong on UWP?

Also I could use MVVM Light or MVVMCross I'm not interested on those solutions I want to learn MVVM by hand and later on i might check those frameworks.

答:
It's because in your MainPageView.xaml you have this:

```<code><Page.DataContext>
    <local:MainPageView/>
</Page.DataContext>
</code>```

So every MainPageview creates a nested MainPageView as its DataContext. These are created until you blow the stack.

I think you meant to put a MainPageViewModel in here.

Body:
I'm trying to reproduce a MVVM tutorial for WPF but applying it to UWP. But I've done everything in the tutorial I believe right the exact same code shown at the tutorial.

But when I ran the code I kept getting a StackOverflowException which is caused because the MainPageView keeps initializing again and again, until the exception is thrown.

The thing is I'm kinda knew at MVVM and I wish to master it, so can somebody please explain me why am I getting this?

I'll leave the code of each one of my classes and views.

This is my MainPageView.Xaml:

<Page
x:Class="MVVMHierarchiesDemo.MainPageView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MVVMHierarchiesDemo"
xmlns:views="using:MVVMHierarchiesDemo.Views"
xmlns:viewmodel="using:MVVMHierarchiesDemo.ViewModel"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Page.DataContext>
    <local:MainPageView/>
</Page.DataContext>

<Page.Resources>
    <DataTemplate x:Key="CustomerTemplate" x:DataType="viewmodel:CustomerListViewModel">
        <views:CustomerListView/>
    </DataTemplate>

    <DataTemplate x:Key="OrderTemplate" x:DataType="viewmodel:OrderViewModel">
        <views:OrderView/>
    </DataTemplate>
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <Grid x:Name="NavBar"
          Grid.Row="0">
        <Button Content="Customers"
                Command="{Binding NavCommand}"
                CommandParameter="customers"
                Grid.Column="0"
                Grid.Row="0"/>

        <Button Content="Orders"
                Command="{Binding NavCommand}"
                CommandParameter="orders"
                Grid.Column="2"
                Grid.Row="0"/>
    </Grid>

    <Grid x:Name="MainContent"
          Grid.Row="1">
        <ContentControl Content="{Binding CurrentViewModel}"/>
    </Grid>
</Grid>
</Page>

This is my code-behind MainPageView.xaml.cs - here is where the StackoverflowException is thrown in the constructor it keeps calling it.

using Windows.UI.Xaml.Controls;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace MVVMHierarchiesDemo
{
    ///
    /// An empty page that can be used on its own or navigated to within a Frame.
    ///
    public sealed partial class MainPageView : Page
    {
        public MainPageView()
        {
            this.InitializeComponent();
        }
    }
}

This is my BindableBase.cs as the tutorial shows:

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace MVVMHierarchiesDemo
{
    /*The main idea behind this class is to encapsulate the INotifyPropertyChanged implementation
     * and provide helper methods to the derived class so that they can easily trigger the appropriate notifications.
     * Following is the implementation of BindableBase class.*/
    public class BindableBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        protected virtual void SetProperty<T>(ref T member, T val, [CallerMemberName]string propertyName = null)
        {
            if (object.Equals(member, val))
                return;

            member = val;
            OnPropertyChanged(propertyName);
        }
    }
}

This is MyCommand.cs or better known as the relay command pattern:

using System;
using System.Windows.Input;

namespace MVVMHierarchiesDemo
{
    /* Now it's time to actually start doing some view switching using our CurrentViewModel property.
     * We just need some way to drive the setting of this property. And we're going to make it so that
     * the end user can command going to the customer list or to the order view. First add a new class
     * in your project which will implement the ICommand interface. Following is the implementation of
     * ICommand interface.*/
    public class MyCommand<T> : ICommand
    {
        Action<T> _TargetExecuteMethod;
        Func<T, bool> _TargetCanExecuteMethod;

        public MyCommand(Action<T> targetExecuteMethod)
        {
            _TargetExecuteMethod = targetExecuteMethod;
        }

        public MyCommand(Action<T> targetExecuteMethod, Func<T,bool> targetCanExecuteMethod)
        {
            _TargetExecuteMethod = targetExecuteMethod;
            _TargetCanExecuteMethod = targetCanExecuteMethod;
        }

        public event EventHandler CanExecuteChanged = delegate { };

        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged?.Invoke(this, EventArgs.Empty);
        }

        bool ICommand.CanExecute(object parameter)
        {
            if (_TargetCanExecuteMethod != null)
            {
                T tparam = (T)parameter;
                return _TargetCanExecuteMethod(tparam);
            }

            if (_TargetExecuteMethod != null)
                return true;

            return false;
        }

        void ICommand.Execute(object parameter)
        {
            if(_TargetExecuteMethod!=null)
            {
                T tparam = (T)parameter;
                _TargetExecuteMethod(tparam);
            }
        }
    }
}

This is my usercontrol for OrdersView.xaml:

<UserControl
    x:Class="MVVMHierarchiesDemo.Views.OrderView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MVVMHierarchiesDemo.Views"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400">

    <Grid>
        <TextBlock Text="Order View"/>
    </Grid>
</UserControl>

This is my user control CustomerListView.xaml:

<UserControl
    x:Class="MVVMHierarchiesDemo.Views.CustomerListView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MVVMHierarchiesDemo.Views"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400">

    <Grid>
        <TextBlock Text="Customer List View"/>
    </Grid>
</UserControl>

This is my OrderViewModel:

namespace MVVMHierarchiesDemo.ViewModel
{
    /*Derive all of your ViewModels from BindableBase class.*/
    public class OrderViewModel : BindableBase
    {
    }
}

This is my CustomerViewModel:

namespace MVVMHierarchiesDemo.ViewModel
{
    /*Derive all of your ViewModels from BindableBase class.*/
    public class CustomerListViewModel : BindableBase
    {
    }
}

Finally this is my MainPageViewModel:

namespace MVVMHierarchiesDemo.ViewModel
{
    /*Derive all of your ViewModels from BindableBase class.*/
    public class MainPageViewModel : BindableBase
    {
        public MainPageViewModel()
        {
            NavCommand = new MyCommand<string>(OnNavigation);
        }

        private CustomerListViewModel _customerListViewModel = new CustomerListViewModel();

        private OrderViewModel _orderViewModel = new OrderViewModel();

        private BindableBase _currentViewModel;

        public BindableBase CurrentViewModel
        {
            get
            {
                return _currentViewModel;
            }

            set
            {
                SetProperty(ref _currentViewModel, value);
            }
        }

        public MyCommand<string> NavCommand { get; private set; }

        private void OnNavigation(string destination)
        {
            switch (destination)
            {
                case "orders":
                    {
                        CurrentViewModel = _orderViewModel;
                        break;
                    }
                case "customers":
                default:
                    CurrentViewModel = _customerListViewModel;
                    break;
            }
        }
    }
}

and lastly I think the MainPageView is the one causing the infinite looping but I don't understand why?

If somebody could be so kind to tell me what I am doing wrong on UWP?

Also I could use MVVM Light or MVVMCross I'm not interested on those solutions I want to learn MVVM by hand and later on i might check those frameworks.

Body:
It's because in your MainPageView.xaml you have this:

<Page.DataContext>
    <local:MainPageView/>
</Page.DataContext>

So every MainPageview creates a nested MainPageView as its DataContext. These are created until you blow the stack.

I think you meant to put a MainPageViewModel in here.


问:
QTreeView Item Hover/Selected background color based on current color
In my project I have several QTreeView widgets displaying data. The background color of the items in the QTreeView changes depending on the data's type and association with other items.

Here is how those background colors are set:

```<code>QColor warning;
warning.setRgb(255, 86, 86);
model->itemFromIndex(index)->setData(warning, Qt::BackgroundRole);
</code>```

This works, but I also want to have different background colors when an item is selected/hovered. I opted to use a stylesheet.

```<code>QTreeView::item:selected{background-color: #bedcf0;} //light blue
QTreeView::item:hover:selected{background-color: #94c8ea;} //darker blue
QTreeView::item:hover:!selected{background-color: #e6e6e6;} //gray
</code>```

This provides the look I want, but only for items that have a white default background. If an item has a custom background color (set via Qt::BackgroundRole) then these hover and selected colors completely override the current background color.

What I want to happen is have every item darken a set amount when hovered/selected, based on the current background color. This is tough because QStandardItem::setProperty() doesn't exist.

Thanks for your time!

答:
So I have an answer. Maybe you can tell me if it's ok for you and/or we can talk about it.

I created a custom QTreeView and QStandardItem, overwritemouseMoveEvent(QMouseEvent *event) and set setMouseTracking(true); of my tree.

I got the item under the mouse with: static_cast<QStandardItemModel*>(model())->itemFromIndex(indexAt(event->pos()))

With that I can get with item is hovered. Then in my custom item I have a function hovered() and normal(). When the item is hovered, the method hovered is called. When the mouse move, it put the item back to normal and rehovered it if it's still on it.
The code:

HoveredTreeView.cpp:

```<code>#include "HoverTreeView.h"

#include <QDebug>
#include <QMouseEvent>
#include <QStandardItemModel>

HoverTreeView::HoverTreeView(QWidget *parent)
    : QTreeView(parent)
{
    setMouseTracking(true);
}

void HoverTreeView::mouseMoveEvent(QMouseEvent *event)
{
    while (!_hoveredItems.empty())
    {
       HoverStandardItem* oldItem = _hoveredItems.pop();
       oldItem->normal();
    }
    auto *item = static_cast<QStandardItemModel*>(model())->itemFromIndex(indexAt(event->pos()));
    HoverStandardItem* realItem = static_cast<HoverStandardItem*>(item);
    if (item) {
        realItem->hovered();
        _hoveredItems.push(realItem);
    }
}
</code>```

HoveredTreeView.h:

```<code>#ifndef HOVERTREEVIEW_H
#define HOVERTREEVIEW_H

#include <QStack>
#include <QTreeView>
#include "HoverStandardItem.h"

class HoverTreeView : public QTreeView
{
public:
    HoverTreeView(QWidget *parent = nullptr);

public slots:
    void    mouseMoveEvent(QMouseEvent *event);
    QStack<HoverStandardItem*> _hoveredItems;
};

#endif // HOVERTREEVIEW_H
</code>```

HoveredStandardItem.cpp:

```<code>#include "HoverStandardItem.h"

HoverStandardItem::HoverStandardItem(QColor const& backgroundColor, const QString &text)
    : QStandardItem(text)
    , _backgroundColor(backgroundColor)
{
    setData(backgroundColor, Qt::BackgroundColorRole);
}

void HoverStandardItem::hovered()
{
    QColor hoveredColor(_backgroundColor);
    unsigned int darker = 20;
    hoveredColor.setRgb(hoveredColor.red() - darker, hoveredColor.green() - darker, hoveredColor.blue() - darker);
    setData(hoveredColor, Qt::BackgroundColorRole);
}

void HoverStandardItem::normal()
{
    setData(_backgroundColor, Qt::BackgroundColorRole);
}
</code>```

HoveredStandardItem.h:

```<code>#ifndef HOVERSTANDARDITEM_H
#define HOVERSTANDARDITEM_H

#include <QStandardItem>

class HoverStandardItem : public QStandardItem
{
public:
    HoverStandardItem(const QColor &backgroundColor, QString const& text = "");
    void hovered();
    void normal();
private:
    QColor  _backgroundColor;
};

#endif // HOVERSTANDARDITEM_H
</code>```

I tested it in a MainWindow. Here the constructor:

```<code>MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QStandardItemModel *model = new QStandardItemModel(this);
    QColor warning[3] = {
    {QColor(255, 86, 86)},
        {QColor(86, 255, 86)},
        {QColor(86, 86, 255)}
    };
    for (int j = 0 ; j < 3 ; ++j) {
        QStandardItem *parentItem = model->invisibleRootItem();
        for (int i = 0; i < 4; ++i) {
            QStandardItem *item = new HoverStandardItem(warning[j], QString("item %0 %1").arg(j).arg(i));
            parentItem->appendRow(item);
            parentItem = item;
        }
    }
    ui->treeView->setModel(model);

}
</code>```

Body:
In my project I have several QTreeView widgets displaying data. The background color of the items in the QTreeView changes depending on the data's type and association with other items.

Here is how those background colors are set:

QColor warning;
warning.setRgb(255, 86, 86);
model->itemFromIndex(index)->setData(warning, Qt::BackgroundRole);

This works, but I also want to have different background colors when an item is selected/hovered. I opted to use a stylesheet.

QTreeView::item:selected{background-color: #bedcf0;} //light blue
QTreeView::item:hover:selected{background-color: #94c8ea;} //darker blue
QTreeView::item:hover:!selected{background-color: #e6e6e6;} //gray

This provides the look I want, but only for items that have a white default background. If an item has a custom background color (set via Qt::BackgroundRole) then these hover and selected colors completely override the current background color.

What I want to happen is have every item darken a set amount when hovered/selected, based on the current background color. This is tough because QStandardItem::setProperty() doesn't exist.

Thanks for your time!

Body:
So I have an answer. Maybe you can tell me if it's ok for you and/or we can talk about it.

I created a custom QTreeView and QStandardItem, overwritemouseMoveEvent(QMouseEvent *event) and set setMouseTracking(true); of my tree.

I got the item under the mouse with: static_cast<QStandardItemModel*>(model())->itemFromIndex(indexAt(event->pos()))

With that I can get with item is hovered. Then in my custom item I have a function hovered() and normal(). When the item is hovered, the method hovered is called. When the mouse move, it put the item back to normal and rehovered it if it's still on it.
The code:

HoveredTreeView.cpp:

#include "HoverTreeView.h"

#include <QDebug>
#include <QMouseEvent>
#include <QStandardItemModel>

HoverTreeView::HoverTreeView(QWidget *parent)
    : QTreeView(parent)
{
    setMouseTracking(true);
}

void HoverTreeView::mouseMoveEvent(QMouseEvent *event)
{
    while (!_hoveredItems.empty())
    {
       HoverStandardItem* oldItem = _hoveredItems.pop();
       oldItem->normal();
    }
    auto *item = static_cast<QStandardItemModel*>(model())->itemFromIndex(indexAt(event->pos()));
    HoverStandardItem* realItem = static_cast<HoverStandardItem*>(item);
    if (item) {
        realItem->hovered();
        _hoveredItems.push(realItem);
    }
}

HoveredTreeView.h:

#ifndef HOVERTREEVIEW_H
#define HOVERTREEVIEW_H

#include <QStack>
#include <QTreeView>
#include "HoverStandardItem.h"

class HoverTreeView : public QTreeView
{
public:
    HoverTreeView(QWidget *parent = nullptr);

public slots:
    void    mouseMoveEvent(QMouseEvent *event);
    QStack<HoverStandardItem*> _hoveredItems;
};

#endif // HOVERTREEVIEW_H

HoveredStandardItem.cpp:

#include "HoverStandardItem.h"

HoverStandardItem::HoverStandardItem(QColor const& backgroundColor, const QString &text)
    : QStandardItem(text)
    , _backgroundColor(backgroundColor)
{
    setData(backgroundColor, Qt::BackgroundColorRole);
}

void HoverStandardItem::hovered()
{
    QColor hoveredColor(_backgroundColor);
    unsigned int darker = 20;
    hoveredColor.setRgb(hoveredColor.red() - darker, hoveredColor.green() - darker, hoveredColor.blue() - darker);
    setData(hoveredColor, Qt::BackgroundColorRole);
}

void HoverStandardItem::normal()
{
    setData(_backgroundColor, Qt::BackgroundColorRole);
}

HoveredStandardItem.h:

#ifndef HOVERSTANDARDITEM_H
#define HOVERSTANDARDITEM_H

#include <QStandardItem>

class HoverStandardItem : public QStandardItem
{
public:
    HoverStandardItem(const QColor &backgroundColor, QString const& text = "");
    void hovered();
    void normal();
private:
    QColor  _backgroundColor;
};

#endif // HOVERSTANDARDITEM_H

I tested it in a MainWindow. Here the constructor:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QStandardItemModel *model = new QStandardItemModel(this);
    QColor warning[3] = {
    {QColor(255, 86, 86)},
        {QColor(86, 255, 86)},
        {QColor(86, 86, 255)}
    };
    for (int j = 0 ; j < 3 ; ++j) {
        QStandardItem *parentItem = model->invisibleRootItem();
        for (int i = 0; i < 4; ++i) {
            QStandardItem *item = new HoverStandardItem(warning[j], QString("item %0 %1").arg(j).arg(i));
            parentItem->appendRow(item);
            parentItem = item;
        }
    }
    ui->treeView->setModel(model);

}


问:
How to use kube-proxy to forward https serivce in k8s?
As we know ,kube-proxy is used to proxy serive that could be accessed from external network via apiserver, does kube-proxy support to proxy https service in k8s  or any other solution so that we could access it via apiserver ?</p>

答:
You need to expose your https pods via a service of type Nodeport, then you can access the https via the defined port on any node in the cluster (master or worker) because kube-proxy will forward the requests to your pods that are part of the service. NodePorts can be in the range of 30000-32767 by default.

Example configuration for an https service and deployment with nginx:

```<code>apiVersion: v1
kind: Service
metadata:
  annotations:
    service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"
  name: nginx
  labels:
    app: nginx
spec:
  type: NodePort
  ports:
  - port: 443
    name: nginx
    targetPort: 443
    nodePort: 32756
  selector:
    app: nginx
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: nginxdeployment
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 443
</code>```

Body:
You need to expose your https pods via a service of type Nodeport, then you can access the https via the defined port on any node in the cluster (master or worker) because kube-proxy will forward the requests to your pods that are part of the service. NodePorts can be in the range of 30000-32767 by default.

Example configuration for an https service and deployment with nginx:

apiVersion: v1
kind: Service
metadata:
  annotations:
    service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"
  name: nginx
  labels:
    app: nginx
spec:
  type: NodePort
  ports:
  - port: 443
    name: nginx
    targetPort: 443
    nodePort: 32756
  selector:
    app: nginx
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: nginxdeployment
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 443


问:
Javascript Array to MySQL "In" list of values
I have an array where each element corresponds to an alphanumeric string, lets say :

userIds : ['Ab526', 'shvx23', '23636dsd']

I want to convert it into such a format so that I can pass this list of strings to IN clause of mySQL query as something like :

Select * from Users where userIds in '(...)';

I tried using array.join() and many other methods, suggested somewhere or the other but all in vain.

var userIds = ['Ab526', 'shvx23', '23636dsd']
var ids    = userIds.join(',');
var query  = 'Select * from Users where userIds in (' + ids + ')';
console.log(query);```

which results in :

Select * from Users where userIds in ('Ab526, shvx23, 23636dsd');

If anyone could suggest a solution as how can I achieve what I want to, it would be of great help.

答:
You could map the quoted values and join later.

var userIds = ['Ab526', 'shvx23', '2363\'6dsd'],
    result = userIds.map(function (a) { return "'" + a.replace("'", "''") + "'"; }).join();

console.log(result);```

ContentLicense: CC BY-SA 4.0

Body:
I have an array where each element corresponds to an alphanumeric string, lets say :

userIds : ['Ab526', 'shvx23', '23636dsd']

I want to convert it into such a format so that I can pass this list of strings to IN clause of mySQL query as something like :

Select * from Users where userIds in '(...)';

I tried using array.join() and many other methods, suggested somewhere or the other but all in vain.

var userIds = ['Ab526', 'shvx23', '23636dsd']
var ids    = userIds.join(',');
var query  = 'Select * from Users where userIds in (' + ids + ')';
console.log(query);

which results in :

Select * from Users where userIds in ('Ab526, shvx23, 23636dsd');

If anyone could suggest a solution as how can I achieve what I want to, it would be of great help.


问:
how can i load some content from another html file my main html?
I want to add specific content from another HTML page into my main HTML. I am trying using .load by jquery it is work but run just in firefox, I want some method that works in other browsers like chrome.
I have two HTML I want to insert div with id=2 from second html into first HTML to div with id=ok? could you please help me?
main HTML:

```<code><html>
<head>
    <title></title>
</head>
<body>
<div id="ok"></div>
</body>
</html>
</code>```

second html:

```<code><html>
<head>
    <title></title>
</head>
<body>
<div id="1">one</div>
<div id="2">two</div>
<div id="3">three</div>

</body>
</html>
</code>```

答:
You can use an ajax call to load the file as text.Then Append the obtained content into required div with jquery wrapper around it.

```<code>$.ajax({url: "second.html", success: function(result){
        $("#ok").append($(result));
    }});
</code>```

And of course it should be in document ready event

Body:
I want to add specific content from another HTML page into my main HTML. I am trying using .load by jquery it is work but run just in firefox, I want some method that works in other browsers like chrome.
I have two HTML I want to insert div with id=2 from second html into first HTML to div with id=ok? could you please help me?
main HTML:

    <title></title>

second html:

    <title></title>

one

two

three

Body:
You can use an ajax call to load the file as text.Then Append the obtained content into required div with jquery wrapper around it.

$.ajax({url: "second.html", success: function(result){
        $("#ok").append($(result));
    }});

And of course it should be in document ready event


问:
Android IllegalStateException: attempt to use Inflater after calling end
Here is my Stacktrace:

```<code><StackTrace>java.lang.IllegalStateException: attempt to use Inflater after calling end
    at java.util.zip.Inflater.checkOpen(Inflater.java:332)
    at java.util.zip.Inflater.setInput(Inflater.java:312)
    at com.android.okhttp.okio.InflaterSource.refill(InflaterSource.java:106)
    at com.android.okhttp.okio.InflaterSource.read(InflaterSource.java:62)
    at com.android.okhttp.okio.GzipSource.read(GzipSource.java:80)
    at com.android.okhttp.okio.RealBufferedSource$1.read(RealBufferedSource.java:374)
    at java.io.InputStream.read(InputStream.java:162)
    at com.myProgram.services.DownloadService.onHandleIntent(DownloadService.java:58)
    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:158)
    at android.os.HandlerThread.run(HandlerThread.java:61)
</StackTrace>
</code>```

and here is the code from DownloadService:

```<code> InputStream input = connection.getInputStream();
 byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            Bundle resultData = new Bundle();
            resultData.putInt("progress" ,(int) (total * 100 / fileLength));
            receiver.send(U_PROGRESS, resultData);
            output.write(data, 0, count);
        }
</code>```

58 line is:

```<code>while ((count = input.read(data)) != -1) {
</code>```

This error occurs in random cases. Download service is used to download new version of the app.

答:
Note that you cannot close the downloading InputStream from a different thread than your download service (i.e. the one which is calling InputStream.read).

Do you have another thread that by any chance is trying to close the stream using InputStream.close() api? such a behavior will cause this kind of runtime exception. On more recent versions of OkHttp, a somewhat similar exception will be produced from the closing thread. See below for a reference: https://github.com/square/okhttp/issues/1842

Body:
Here is my Stacktrace:

<StackTrace>java.lang.IllegalStateException: attempt to use Inflater after calling end
    at java.util.zip.Inflater.checkOpen(Inflater.java:332)
    at java.util.zip.Inflater.setInput(Inflater.java:312)
    at com.android.okhttp.okio.InflaterSource.refill(InflaterSource.java:106)
    at com.android.okhttp.okio.InflaterSource.read(InflaterSource.java:62)
    at com.android.okhttp.okio.GzipSource.read(GzipSource.java:80)
    at com.android.okhttp.okio.RealBufferedSource$1.read(RealBufferedSource.java:374)
    at java.io.InputStream.read(InputStream.java:162)
    at com.myProgram.services.DownloadService.onHandleIntent(DownloadService.java:58)
    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:158)
    at android.os.HandlerThread.run(HandlerThread.java:61)
</StackTrace>

and here is the code from DownloadService:

 InputStream input = connection.getInputStream();
 byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            Bundle resultData = new Bundle();
            resultData.putInt("progress" ,(int) (total * 100 / fileLength));
            receiver.send(U_PROGRESS, resultData);
            output.write(data, 0, count);
        }

58 line is:

while ((count = input.read(data)) != -1) {

This error occurs in random cases. Download service is used to download new version of the app.


问:
Correctly convert String array to String and back in java
I have a following code:

```<code>String[] stringArray = new String[] { "One,", "Two", "Three" };
System.out.println(Arrays.toString(stringArray));
</code>```

which produces the following string:

```<code>[One,, Two, Three]
</code>```

Right now It is impossible to convert this string back into the same String[] with 3 elements because of two consecutive commas ,,

How to correctly make this conversion ?

UPDATED

```<code>Arrays.toString(stringArray)
</code>```

is just a particular case and I'm not limited to use only this approach. I need to implement approach where conversion from String[] to String and back from String to String[] will be idempotent operation.

答:
Convert it to a format intended for this, like JSON.  Using Jackson it would be something like this:

```<code> ObjectMapper objectMapper = new ObjectMapper();

 String out = objectMapper.writeValueAsString(Arrays.asList(array));
</code>```

And back:

```<code> List<String> strings = (List<String>) objectMapper.readValue(out, List.class);

 String[] array2 = strings.toArray();
</code>```

Body:
I have a following code:

String[] stringArray = new String[] { "One,", "Two", "Three" };
System.out.println(Arrays.toString(stringArray));

which produces the following string:

[One,, Two, Three]

Right now It is impossible to convert this string back into the same String[] with 3 elements because of two consecutive commas ,,

How to correctly make this conversion ?

UPDATED

Arrays.toString(stringArray)

is just a particular case and I'm not limited to use only this approach. I need to implement approach where conversion from String[] to String and back from String to String[] will be idempotent operation.

Body:
Convert it to a format intended for this, like JSON.  Using Jackson it would be something like this:

 ObjectMapper objectMapper = new ObjectMapper();

 String out = objectMapper.writeValueAsString(Arrays.asList(array));

And back:

 List<String> strings = (List<String>) objectMapper.readValue(out, List.class);

 String[] array2 = strings.toArray();


问:
Conversion failed when converting the varchar value 'SAT' to data type int
I have a table ConsoleGames wherein all columns are of type varchar(50). When I try to create a new table console_games by amending existing datatypes by using the query:

```<code>CREATE TABLE console_games
(
    game_rank integer,
    game_name varchar(1200),
    platform_name varchar(1200),
    game_year integer,
    genre varchar(200),
    publisher varchar(1200),
    na_sales float,
    eu_sales float,
    jp_sales float,
    other_sales float
)

INSERT INTO console_games
    SELECT *
    FROM [dbo].[RAWConsoleGames]
</code>```

I get the following error message:

Msg 245, Level 16, State 1, Line 17

  Conversion failed when converting the varchar value 'SAT' to data type int.

When I look into the data in the table the value 'SAT' is in a column for which I am not changing the datatype. 'SAT' value exists in the Platform column which is of varchar type and I am not trying to change the type to int.

Any help will be appreciated.

Thanks

答:
You should always define the list of columns you're inserting into, and you should also always define the list of columns you're selecting from. Furthermore, I'd recommend to explicitly do any type conversions instead of leaving that up to SQL Server - if you do it yourself, you know when and what you're doing.

So I'd write that statement like this:

```<code>-- **DEFINE** the list of columns you're inserting into
INSERT INTO console_games (rank, name, Platform, year, genre, publisher,
                           sales, eu_sales, jp_sales, other_sales)
    -- **DEFINE** the list of columns you're selecting, and any conversions
    SELECT
        game_rank, game_name, platform_name,
        CAST(game_year AS VARCHAR(50)), genre,
        publisher,
        CAST(na_sales AS VARCHAR(50)),
        CAST(eu_sales AS VARCHAR(50)),
        CAST(jp_sales AS VARCHAR(50)),
        CAST(other_sales AS VARCHAR(50))
    FROM
        [dbo].[RAWConsoleGames]
</code>```

Body:
I have a table ConsoleGames wherein all columns are of type varchar(50). When I try to create a new table console_games by amending existing datatypes by using the query:

CREATE TABLE console_games
(
    game_rank integer,
    game_name varchar(1200),
    platform_name varchar(1200),
    game_year integer,
    genre varchar(200),
    publisher varchar(1200),
    na_sales float,
    eu_sales float,
    jp_sales float,
    other_sales float
)

INSERT INTO console_games
    SELECT *
    FROM [dbo].[RAWConsoleGames]

I get the following error message:

Msg 245, Level 16, State 1, Line 17

  Conversion failed when converting the varchar value 'SAT' to data type int.

When I look into the data in the table the value 'SAT' is in a column for which I am not changing the datatype. 'SAT' value exists in the Platform column which is of varchar type and I am not trying to change the type to int.

Any help will be appreciated.

Thanks

Body:
You should always define the list of columns you're inserting into, and you should also always define the list of columns you're selecting from. Furthermore, I'd recommend to explicitly do any type conversions instead of leaving that up to SQL Server - if you do it yourself, you know when and what you're doing.

So I'd write that statement like this:

-- **DEFINE** the list of columns you're inserting into
INSERT INTO console_games (rank, name, Platform, year, genre, publisher,
                           sales, eu_sales, jp_sales, other_sales)
    -- **DEFINE** the list of columns you're selecting, and any conversions
    SELECT
        game_rank, game_name, platform_name,
        CAST(game_year AS VARCHAR(50)), genre,
        publisher,
        CAST(na_sales AS VARCHAR(50)),
        CAST(eu_sales AS VARCHAR(50)),
        CAST(jp_sales AS VARCHAR(50)),
        CAST(other_sales AS VARCHAR(50))
    FROM
        [dbo].[RAWConsoleGames]


问:
Get specific data out of php object
Using https://github.com/ddeboer/imap, in combination with an office365 account, I need to retrieve the email address that sent the email.

To retrieve, I use:

```<code>$message->getFrom()
</code>```

But the result is:

```<code>Ddeboer\Imap\Message\EmailAddress Object
(
    [mailbox:Ddeboer\Imap\Message\EmailAddress:private] => my
    [hostname:Ddeboer\Imap\Message\EmailAddress:private] => email.com
    [name:Ddeboer\Imap\Message\EmailAddress:private] => Full Name
    [address:Ddeboer\Imap\Message\EmailAddress:private] => my@email.com
)
</code>```

How do I retrieve only the last part in this object (I need my@email.com)

答:
```<code>$message->getFrom()->getAddress()
</code>```

Source.

Title: Get specific data out of php object

Body:
Using https://github.com/ddeboer/imap, in combination with an office365 account, I need to retrieve the email address that sent the email.

To retrieve, I use:

$message->getFrom()

But the result is:

Ddeboer\Imap\Message\EmailAddress Object
(
    [mailbox:Ddeboer\Imap\Message\EmailAddress:private] => my
    [hostname:Ddeboer\Imap\Message\EmailAddress:private] => email.com
    [name:Ddeboer\Imap\Message\EmailAddress:private] => Full Name
    [address:Ddeboer\Imap\Message\EmailAddress:private] => my@email.com
)

How do I retrieve only the last part in this object (I need my@email.com)

Body:
$message->getFrom()->getAddress()

Source.


问:
How to get file contents by inode in Bash?
How can I retrieve file contents in Bash by knowing only the inode of the file?</p>

答:
Get inode with ext2/ext3/ext4 filesystem:

```<code>inode=262552
device=/dev/sda1
sudo debugfs -R "ncheck $inode" $device 2>/dev/null
</code>```

Output (example):

```
Inode   Pathname
262552  /var/log/syslog
```

To show content of file:

```<code>sudo debugfs -R "ncheck $inode" $device 2>/dev/null | awk '/[1-9]/ {print $2}' | xargs cat
</code>```

Body:
Get inode with ext2/ext3/ext4 filesystem:

inode=262552
device=/dev/sda1
sudo debugfs -R "ncheck $inode" $device 2>/dev/null

Output (example):

Inode   Pathname
262552  /var/log/syslog

To show content of file:

sudo debugfs -R "ncheck $inode" $device 2>/dev/null | awk '/[1-9]/ {print $2}' | xargs cat


问:
Searching if a list exists in my python dictionary and append to the associated key
I am pretty new to python and any help will be greatly appreciated. I need to search through a dictionary to confirm if a list exists, if it does, I need to append it as an additional value to the associated key. Here is what I have written:

```<code>    _, p = scipy.stats.ks_2samp(k[i],buffer[j])
    if p > alpha:
        for key, value in cluster.iteritems():
            if value == buffer[j]:
                cluster[key].append(i)
</code>```

But is get this error"ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()".

Can someone help me please. The cluster in the code is a dictionary whose values are lists.

答:
The expression value == buffer[j] returns an array of Booleans. You should not use in an if statement like that. As the error-message suggests you can use one of

```<code>if (value == buffer[j]).all() ## true if all elements are equal
if (value == buffer[j]).any() ## true if any of the elements are equal
</code>```

to avoid this error.

Hope this helps.

Body:
I am pretty new to python and any help will be greatly appreciated. I need to search through a dictionary to confirm if a list exists, if it does, I need to append it as an additional value to the associated key. Here is what I have written:

    _, p = scipy.stats.ks_2samp(k[i],buffer[j])
    if p > alpha:
        for key, value in cluster.iteritems():
            if value == buffer[j]:
                cluster[key].append(i)

But is get this error"ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()".

Can someone help me please. The cluster in the code is a dictionary whose values are lists.

Body:
The expression value == buffer[j] returns an array of Booleans. You should not use in an if statement like that. As the error-message suggests you can use one of

if (value == buffer[j]).all() ## true if all elements are equal
if (value == buffer[j]).any() ## true if any of the elements are equal

to avoid this error.

Hope this helps.


问:
asp.net Textbox Textmode Number, allow numbers only
I would just like to know if there is a way in ASP.NET to allow only numbers in textboxes with textmode="number"

when I use this:

```<code><asp:TextBox runat="server" TextMode="Number" ID="TextBoxDuration" Width="250"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="TextBoxDuration" runat="server" ErrorMessage="Dieses Feld darf nicht leer sein" /><br />
<asp:RegularExpressionValidator runat="server" ControlToValidate="TextBoxDuration" validationexpression="((\d+)((\.\d{1})?))$" ErrorMessage="Nur Zahlen" />
</code>```

users can still input the char e and +, -

I don't like to use normal Textbox with the same Regularexpressionvalidator (which actually would work)

example:

答:
Adding Type="number" will work.</p>

```<code><asp:TextBox ID="txtQty"  type="number" runat="server"></asp:TextBox>
</code>```

Body:
I would just like to know if there is a way in ASP.NET to allow only numbers in textboxes with textmode="number"

when I use this:

<asp:TextBox runat="server" TextMode="Number" ID="TextBoxDuration" Width="250"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="TextBoxDuration" runat="server" ErrorMessage="Dieses Feld darf nicht leer sein" />

<asp:RegularExpressionValidator runat="server" ControlToValidate="TextBoxDuration" validationexpression="((\d+)((\.\d{1})?))$" ErrorMessage="Nur Zahlen" />

users can still input the char e and +, -

I don't like to use normal Textbox with the same Regularexpressionvalidator (which actually would work)

example:

Body:
Adding Type="number" will work.

<asp:TextBox ID="txtQty"  type="number" runat="server"></asp:TextBox>


问:
How to create custom wildcard domain with Microsoft's domain (azurewebsites.net)
I refer follwing link :-

https://learn.microsoft.com/en-us/azure/app-service-web/web-sites-custom-domain-name#a

but When I am going to create custom domain it show following error.

No CNAME were found. Please add a CNAME record pointing to dev-demo.azurewebsites.net.

Please help me

Thanks.

答:
According to the error message, what you need to do is set up a CNAME record to pointing to your Azure app's default domain for your domain registered at your domain registrar's own management tool (e.g. Azure DNS, GoDaddy, etc.).

If you registered your domain name with GoDaddy, please follow the steps blow.

Log in to your GoDaddy account.

Click on your account icon, then navigate to Manage My Domains.

Select the domain you want to manage, under the Action section, click on the Manage DNS button:

At the Records section, click Add and select CNAME from the drop-down list.

Complete the fields, then click Save button.

Now, go back to the Azure portal, and validate your hostname again.


问:
sql like matches to different characters
There is Unicode character [¹] - Superscript One (in Latin-1 Supplement block):

```<code>SELECT NCHAR(0x00b9) --returns ¹
</code>```

But trying to find out is that symbols exist in column next query returns rows which contain digit one (0x0031):

```<code>SELECT [Name] FROM [Company] WHERE [Name] like '%'+nchar(0x00b9)+'%'
</code>```

Update: I am using MSSQL

答:
It's because your database has a Case INsensitive Collation:

```<code>SELECT DATABASEPROPERTYEX (DB_NAME(DB_ID()), 'COLLATION') -- = Latin1_General_CI_AS

SELECT [Name] AS [WHERE_Collation caseINsensitive]
FROM   ( VALUES  ('¹')
              ,  ('1') ) AS Company (Name)
WHERE [Name] LIKE '%'+nchar(0x00b9)+'%'
;
</code>```

Result:

WHERE_Collation caseINsensitive

¹

1

```<code>SELECT [Name] AS [Collation caseSensitive]
FROM   ( VALUES  ('¹')
              ,  ('1') ) AS Company (Name)
WHERE [Name] LIKE '%'+nchar(0x00b9)+'%' COLLATE Latin1_General_CS_AS
;
</code>```

Result

WHERE_Collation caseSensitive

¹

Body:
There is Unicode character [¹] - Superscript One (in Latin-1 Supplement block):

SELECT NCHAR(0x00b9) --returns ¹

But trying to find out is that symbols exist in column next query returns rows which contain digit one (0x0031):

SELECT [Name] FROM [Company] WHERE [Name] like '%'+nchar(0x00b9)+'%'

Update: I am using MSSQL

Body:
It's because your database has a Case INsensitive Collation:

SELECT DATABASEPROPERTYEX (DB_NAME(DB_ID()), 'COLLATION') -- = Latin1_General_CI_AS

SELECT [Name] AS [WHERE_Collation caseINsensitive]
FROM   ( VALUES  ('¹')
              ,  ('1') ) AS Company (Name)
WHERE [Name] LIKE '%'+nchar(0x00b9)+'%'
;

Result:

WHERE_Collation caseINsensitive

¹

1

SELECT [Name] AS [Collation caseSensitive]
FROM   ( VALUES  ('¹')
              ,  ('1') ) AS Company (Name)
WHERE [Name] LIKE '%'+nchar(0x00b9)+'%' COLLATE Latin1_General_CS_AS
;

Result

WHERE_Collation caseSensitive

¹


问:
angular 2 observable json error
```<code>import { Injectable } from '@angular/core';
import { Http,Response } from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class CommentService{
private _url :string ="https://jsonplaceholder.typicode.com/posts"
   constructor(private _http:Http){}
  // method to fetch CommentS from a api service
 getComments(){

 return this._http.get(this._url)
        .map((response:Response)=> response.json())
        .catch(this._errorHandler);

  }

  _errorHandler(error:Response){
       console.error(error);
     return Observable.throw(error ||"Server Error");

 }

}
</code>```

the above code works great with this url https://jsonplaceholder.typicode.com/posts

but does not work with this url http://ergast.com/api/f1/2016/driverStandings.json

any ideas ...TIA

答:
Aravind is on the right track here, but MRData case sensitive, and mapping is a bit off. The correct way to map the response here would be:

```<code>return this._http.get(this._url)
    .map((response:Response)=> response.json().MRData)
    .catch(this._errorHandler);
}
</code>```

Your component:

```<code>getData() {
  this.service.getData()
    .subscribe(data => {
      this.data = data;
    });
}
</code>```

Then you can access data, e.g like:

```<code><div>
  <b>Series:</b> {{data?.series}}<br>
  <a><b>Url:</b> {{data?.url}}</a>
</div>
</code>```

Then you seem to have a lot of nested objects in your response, so this might help you: Access / process (nested) objects, arrays or JSON

Here's a demo with mock JSON, but I did try that url you provided and the data was received fine. So replicating the plunker should work fine in your app :)

DEMO

Title: angular 2 observable json error

Body:
import { Injectable } from '@angular/core';
import { Http,Response } from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class CommentService{
private _url :string ="https://jsonplaceholder.typicode.com/posts"
   constructor(private _http:Http){}
  // method to fetch CommentS from a api service
 getComments(){

 return this._http.get(this._url)
        .map((response:Response)=> response.json())
        .catch(this._errorHandler);

  }

  _errorHandler(error:Response){
       console.error(error);
     return Observable.throw(error ||"Server Error");

 }

}

the above code works great with this url https://jsonplaceholder.typicode.com/posts

but does not work with this url http://ergast.com/api/f1/2016/driverStandings.json

any ideas ...TIA

Body:
Aravind is on the right track here, but MRData case sensitive, and mapping is a bit off. The correct way to map the response here would be:

return this._http.get(this._url)
    .map((response:Response)=> response.json().MRData)
    .catch(this._errorHandler);
}

Your component:

getData() {
  this.service.getData()
    .subscribe(data => {
      this.data = data;
    });
}

Then you can access data, e.g like:

<div>
  <b>Series:</b> {{data?.series}}<br>
  <a><b>Url:</b> {{data?.url}}</a>
</div>

Then you seem to have a lot of nested objects in your response, so this might help you: Access / process (nested) objects, arrays or JSON

Here's a demo with mock JSON, but I did try that url you provided and the data was received fine. So replicating the plunker should work fine in your app :)

DEMO


问:
Some Character read only in textbox using jQuery or Javascript
Textbox

```<code><input id="txtbo" type="text" value="CAN'T TOUCH THIS!" size="50" />
</code>```

jQuery or Javascript Code:

```<code>var readOnlyLength = $('#txtbo').val().length;

$('#txtbo').on('keypress, keydown', function(event) {
    if ((event.which != 37 && (event.which != 39))
        && ((this.selectionStart < readOnlyLength)
        || ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
        return false;
    }
});
</code>```

i am using this code but event was not fire. than i am using second code that is defined bellow:

```<code>function makeInitialTextReadOnly(input) {
    var readOnlyLength = input.value.length;
    field.addEventListener('keydown', function(event) {
        var which = event.which;
        if (((which == 8) && (input.selectionStart <= readOnlyLength))
                || ((which == 46) && (input.selectionStart < readOnlyLength))) {
            event.preventDefault();
        }
    });
    field.addEventListener('keypress', function(event) {
        var which = event.which;
        if ((event.which != 0) && (input.selectionStart < readOnlyLength)) {
            event.preventDefault();
        }
    });
}

makeInitialTextReadOnly(document.getElementById('field'));
</code>```

it is also doesn't work. if have you any solution or any new idea than give me plzz.

答: If you want to make input read only then you can use disabled attribute in input field.Or you may use div to display instead input.

Body:
Textbox

<input id="txtbo" type="text" value="CAN'T TOUCH THIS!" size="50" />

jQuery or Javascript Code:

var readOnlyLength = $('#txtbo').val().length;

$('#txtbo').on('keypress, keydown', function(event) {
    if ((event.which != 37 && (event.which != 39))
        && ((this.selectionStart < readOnlyLength)
        || ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
        return false;
    }
});

i am using this code but event was not fire. than i am using second code that is defined bellow:

function makeInitialTextReadOnly(input) {
    var readOnlyLength = input.value.length;
    field.addEventListener('keydown', function(event) {
        var which = event.which;
        if (((which == 8) && (input.selectionStart <= readOnlyLength))
                || ((which == 46) && (input.selectionStart < readOnlyLength))) {
            event.preventDefault();
        }
    });
    field.addEventListener('keypress', function(event) {
        var which = event.which;
        if ((event.which != 0) && (input.selectionStart < readOnlyLength)) {
            event.preventDefault();
        }
    });
}

makeInitialTextReadOnly(document.getElementById('field'));

it is also doesn't work. if have you any solution or any new idea than give me plzz.


问:
How to have icons on opposite sides in the same line?
I have tried all the answers I can find and can't seem to fix this. I'm trying to have one of the buttons on the left and the other on the right within the same line. I have tried using

```<code><div style="text-align: right;clear:left;">
</code>```

in either a div or a span tag and taking it out of the unordered list but I still can't seem to get it frustratingly! I think that I could do it by putting them in tables and floating one left and one right but that just seems a messy way to do it and I'm sure there's an easier way I just can't seem to find it. I'd be happy to allocate each a new class and then assign some new CSS to them but I can't seem to make it work that way either.

I have put my JSFiddle here: JSFiddle to illustrate the issue.

```<code><span align="right">
  <ul class="actions">
    <li><a href="salary.html" class="button special icon fa-arrow-left">Salary</a></li>
    <li><a href="courses.html" class="button special icon fa-arrow-right">Courses</a></li>
  </ul>
</span>
</code>```

Thank you so much for your help,

S.

答:
Remove the unnecessary span and simply use:

```<code>ul.actions li:last-of-type {
  float: right;
}
</code>```

This leaves the first button totally unaltered, sitting on the left, and floats the second button to far right.

Body:
I have tried all the answers I can find and can't seem to fix this. I'm trying to have one of the buttons on the left and the other on the right within the same line. I have tried using

in either a div or a span tag and taking it out of the unordered list but I still can't seem to get it frustratingly! I think that I could do it by putting them in tables and floating one left and one right but that just seems a messy way to do it and I'm sure there's an easier way I just can't seem to find it. I'd be happy to allocate each a new class and then assign some new CSS to them but I can't seem to make it work that way either.

I have put my JSFiddle here: JSFiddle to illustrate the issue.

Salary

Courses

Thank you so much for your help,

S.

Body:
Remove the unnecessary span and simply use:

ul.actions li:last-of-type {
  float: right;
}

This leaves the first button totally unaltered, sitting on the left, and floats the second button to far right.