问:
Wrong size with JScrollPane containing updated image
I am coding a GUI containing a JScrollPane that displays an image that gets updated (with potential modification of its dimensions). The image is in an ImageIcon in a JLabel. The image size is retrieved using ImageIcon.getIconWith() and getIconHeight(). And the JLabel preferred size is updated with those dimensions.

When the application is started for the first time, the JScrollPane and its scrollbars have the right dimensions to view the whole image (potentially using scrolling). But when the image gets updated the JScrollPane and the scrollbars assume the image has the dimensions of the previous image. How do I get the JScrollPane to update correctly ?

Here is a curated version of my GUI. Visualizer.java uses the GUI VisualizerGUI.java. When the "Run" button is pushed, a new image is randomly generated using ImageDrawer.drawImage() (simulates the behavior of the real application) and the content of the JScrollPane is updated using the function VisualizerGUI.setTransitionsImage(String imgPath).

Visualizer.java:

```<code>import java.util.*;
import java.io.*;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Visualizer implements ActionListener {

    private VisualizerGUI gui = null;

    public Visualizer() {
    gui =  VisualizerGUI.createAndStart(this);
    }

    public static void main(String[] args) {
    Visualizer viz = new Visualizer();
    }

    public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals("Run command")) {
        run();
    }
    }

    public void run() {
    updateGUIwithSolution();
    }

    public void updateGUIwithSolution() {
    gui.initGUIupdate();
    try {
        ImageDrawer.drawImage();
        gui.setTransitionsImage("image.png");
    } catch (Exception e) {
        System.out.println("Error while generating image");
        e.printStackTrace();
    }
    gui.finalizeGUIupdate();
    }
}
</code>```

VisualizerGUI.java:

```<code>import java.util.*;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.lang.reflect.InvocationTargetException;

public final class VisualizerGUI {

    private JFrame frame;
    private JButton runButton;
    private JButton nextButton;
    private JScrollPane transitionsDisplay;
    private JTabbedPane executionsDisplay;
    private JTabbedPane tracesDisplay;
    private JTextArea textInfoArea;

    public VisualizerGUI() {}

    private void initGUI(ActionListener actionsHandler) {
        //Create and set up the window.
        frame = new JFrame("Visualizer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel controlPanel = new JPanel(new FlowLayout());
    runButton = new JButton("Run");
    runButton.addActionListener(actionsHandler);
    runButton.setActionCommand("Run command");
    controlPanel.add(runButton);
    nextButton = new JButton("Next");
    nextButton.addActionListener(actionsHandler);
    nextButton.setActionCommand("Find next solution");
    controlPanel.add(nextButton);

    transitionsDisplay = new JScrollPane();
    executionsDisplay = new JTabbedPane();
    tracesDisplay = new JTabbedPane();

    JSplitPane ETspliter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, executionsDisplay, tracesDisplay);
    JSplitPane graphsSpliter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, transitionsDisplay, ETspliter);

    textInfoArea = new JTextArea();
    textInfoArea.setLineWrap(true);
    textInfoArea.setWrapStyleWord(true);
    textInfoArea.setEditable(false);
    JScrollPane textInfoAreaSP = new JScrollPane(textInfoArea);

    JSplitPane topSpliter = new JSplitPane(JSplitPane.VERTICAL_SPLIT, graphsSpliter, textInfoAreaSP);

    transitionsDisplay.setPreferredSize(new Dimension(200,200));
    executionsDisplay.setPreferredSize(new Dimension(200,200));
    tracesDisplay.setPreferredSize(new Dimension(200,200));
    textInfoAreaSP.setPreferredSize(new Dimension(200,100));

    frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add(controlPanel, BorderLayout.NORTH);
        frame.getContentPane().add(topSpliter, BorderLayout.CENTER);

        frame.pack();
        frame.setVisible(true);
    }

    public static VisualizerGUI createAndStart(ActionListener actionsHandler) {
    VisualizerGUI gui = new VisualizerGUI();
    final Runnable guiRunner =
        new Runnable() {
        public void run() {
            gui.initGUI(actionsHandler);
            // gui.pack();
        }
        };
    try {
        javax.swing.SwingUtilities.invokeAndWait(guiRunner);
    } catch (InterruptedException e) {
        System.out.println(">>> WARNING <<< InterruptedException while creating the GUI");
    } catch (InvocationTargetException e) {
        System.out.println(">>> WARNING <<< InvocationTargetException while creating the GUI");
    }
    return gui;
    }

    public void clear() {
    initGUIupdate();
    finalizeGUIupdate();
    }

    public void initGUIupdate() {
    // frame.setVisible(false);
    transitionsDisplay.setViewportView(null);
    executionsDisplay.removeAll();
    tracesDisplay.removeAll();
    textInfoArea.setText(null);
    }

    public void pack() {
    frame.pack();
    }

    public void finalizeGUIupdate() {
    // frame.validate();
    // frame.repaint();
    // frame.setVisible(true);
    }

    public void setTransitionsImage(String imgPath) {
    ImageIcon icon = new ImageIcon(imgPath);
    icon.getImage().flush();
    int width = icon.getIconWidth();
    int height = icon.getIconHeight();
    JLabel label = new JLabel();
    label.setVerticalAlignment(SwingConstants.CENTER);
    label.setHorizontalAlignment(SwingConstants.CENTER);
    label.setIcon(icon);
    label.setPreferredSize(new Dimension(width,height));
    //label.setPreferredSize(null);
    transitionsDisplay.setViewportView(label);
    label.revalidate();
    label.repaint();
    transitionsDisplay.getViewport().revalidate();
    transitionsDisplay.getViewport().repaint();
    transitionsDisplay.revalidate();
    // transitionsDisplay.validate();
    transitionsDisplay.repaint();
    frame.revalidate();
    // frame.validate();
    frame.repaint();
    }

    public void setTransitionsImageInED(String imgPath) {
    final Runnable guiRunner =
        new Runnable() {
        public void run() { setTransitionsImage(imgPath); }
        };
    // javax.swing.SwingUtilities.invokeLater(guiRunner);
    try {
        javax.swing.SwingUtilities.invokeAndWait(guiRunner);
    } catch (InterruptedException e) {
        System.out.println(">>> WARNING <<< InterruptedException while creating the GUI");
    } catch (InvocationTargetException e) {
        System.out.println(">>> WARNING <<< InvocationTargetException while creating the GUI");
    }
    }
}
</code>```

ImageDrawer.java:

```<code>import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageDrawer {

    public static void drawImage() throws Exception {
    try {
        int width = 20 + (int)(Math.random() * 1000);
        int height = 20 + (int)(Math.random() * 1000);

        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D ig2 = bi.createGraphics();
        ig2.setPaint(Color.blue);
        ig2.fillRect(0, 0, width, height);
        ig2.setPaint(Color.red);
        ig2.fillRect(5, 5, width - 10, height - 10);
        ig2.setPaint(Color.blue);
        ig2.drawLine(0, 0, width, height);
        ig2.drawLine(0, height, width, 0);

        ImageIO.write(bi, "PNG", new File("image.png"));

    } catch (IOException ie) {
        ie.printStackTrace();
    }
    }
}
</code>```

Can someone explain why I have this problem? Thanks!

答:
```<code>transitionsDisplay.setPreferredSize(new Dimension(200,200));
executionsDisplay.setPreferredSize(new Dimension(200,200));
tracesDisplay.setPreferredSize(new Dimension(200,200));
textInfoAreaSP.setPreferredSize(new Dimension(200,100));
</code>```

Don't use setPreferredSize(...). Each Swing component is responsible for determining its own size.

The image size is retrieved using ImageIcon.getIconWith() and getIconHeight(). And the JLabel preferred size is updated with those dimensions.

Not necessary. Again the JLabel will determine its own size based on the size of the Icon. This is done dynamically as the image/icon changes.

The scrollbars of the scrollpane will appear when the preferred size of the label is greater than the size of the scrollpane. Just let the layout managers do their job.

Body:
I am coding a GUI containing a JScrollPane that displays an image that gets updated (with potential modification of its dimensions). The image is in an ImageIcon in a JLabel. The image size is retrieved using ImageIcon.getIconWith() and getIconHeight(). And the JLabel preferred size is updated with those dimensions.

When the application is started for the first time, the JScrollPane and its scrollbars have the right dimensions to view the whole image (potentially using scrolling). But when the image gets updated the JScrollPane and the scrollbars assume the image has the dimensions of the previous image. How do I get the JScrollPane to update correctly ?

Here is a curated version of my GUI. Visualizer.java uses the GUI VisualizerGUI.java. When the "Run" button is pushed, a new image is randomly generated using ImageDrawer.drawImage() (simulates the behavior of the real application) and the content of the JScrollPane is updated using the function VisualizerGUI.setTransitionsImage(String imgPath).

Visualizer.java:

import java.util.*;
import java.io.*;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Visualizer implements ActionListener {

    private VisualizerGUI gui = null;

    public Visualizer() {
    gui =  VisualizerGUI.createAndStart(this);
    }

    public static void main(String[] args) {
    Visualizer viz = new Visualizer();
    }

    public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals("Run command")) {
        run();
    }
    }

    public void run() {
    updateGUIwithSolution();
    }

    public void updateGUIwithSolution() {
    gui.initGUIupdate();
    try {
        ImageDrawer.drawImage();
        gui.setTransitionsImage("image.png");
    } catch (Exception e) {
        System.out.println("Error while generating image");
        e.printStackTrace();
    }
    gui.finalizeGUIupdate();
    }
}

VisualizerGUI.java:

import java.util.*;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.lang.reflect.InvocationTargetException;

public final class VisualizerGUI {

    private JFrame frame;
    private JButton runButton;
    private JButton nextButton;
    private JScrollPane transitionsDisplay;
    private JTabbedPane executionsDisplay;
    private JTabbedPane tracesDisplay;
    private JTextArea textInfoArea;

    public VisualizerGUI() {}

    private void initGUI(ActionListener actionsHandler) {
        //Create and set up the window.
        frame = new JFrame("Visualizer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel controlPanel = new JPanel(new FlowLayout());
    runButton = new JButton("Run");
    runButton.addActionListener(actionsHandler);
    runButton.setActionCommand("Run command");
    controlPanel.add(runButton);
    nextButton = new JButton("Next");
    nextButton.addActionListener(actionsHandler);
    nextButton.setActionCommand("Find next solution");
    controlPanel.add(nextButton);

    transitionsDisplay = new JScrollPane();
    executionsDisplay = new JTabbedPane();
    tracesDisplay = new JTabbedPane();

    JSplitPane ETspliter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, executionsDisplay, tracesDisplay);
    JSplitPane graphsSpliter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, transitionsDisplay, ETspliter);

    textInfoArea = new JTextArea();
    textInfoArea.setLineWrap(true);
    textInfoArea.setWrapStyleWord(true);
    textInfoArea.setEditable(false);
    JScrollPane textInfoAreaSP = new JScrollPane(textInfoArea);

    JSplitPane topSpliter = new JSplitPane(JSplitPane.VERTICAL_SPLIT, graphsSpliter, textInfoAreaSP);

    transitionsDisplay.setPreferredSize(new Dimension(200,200));
    executionsDisplay.setPreferredSize(new Dimension(200,200));
    tracesDisplay.setPreferredSize(new Dimension(200,200));
    textInfoAreaSP.setPreferredSize(new Dimension(200,100));

    frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add(controlPanel, BorderLayout.NORTH);
        frame.getContentPane().add(topSpliter, BorderLayout.CENTER);

        frame.pack();
        frame.setVisible(true);
    }

    public static VisualizerGUI createAndStart(ActionListener actionsHandler) {
    VisualizerGUI gui = new VisualizerGUI();
    final Runnable guiRunner =
        new Runnable() {
        public void run() {
            gui.initGUI(actionsHandler);
            // gui.pack();
        }
        };
    try {
        javax.swing.SwingUtilities.invokeAndWait(guiRunner);
    } catch (InterruptedException e) {
        System.out.println(">>> WARNING <<< InterruptedException while creating the GUI");
    } catch (InvocationTargetException e) {
        System.out.println(">>> WARNING <<< InvocationTargetException while creating the GUI");
    }
    return gui;
    }

    public void clear() {
    initGUIupdate();
    finalizeGUIupdate();
    }

    public void initGUIupdate() {
    // frame.setVisible(false);
    transitionsDisplay.setViewportView(null);
    executionsDisplay.removeAll();
    tracesDisplay.removeAll();
    textInfoArea.setText(null);
    }

    public void pack() {
    frame.pack();
    }

    public void finalizeGUIupdate() {
    // frame.validate();
    // frame.repaint();
    // frame.setVisible(true);
    }

    public void setTransitionsImage(String imgPath) {
    ImageIcon icon = new ImageIcon(imgPath);
    icon.getImage().flush();
    int width = icon.getIconWidth();
    int height = icon.getIconHeight();
    JLabel label = new JLabel();
    label.setVerticalAlignment(SwingConstants.CENTER);
    label.setHorizontalAlignment(SwingConstants.CENTER);
    label.setIcon(icon);
    label.setPreferredSize(new Dimension(width,height));
    //label.setPreferredSize(null);
    transitionsDisplay.setViewportView(label);
    label.revalidate();
    label.repaint();
    transitionsDisplay.getViewport().revalidate();
    transitionsDisplay.getViewport().repaint();
    transitionsDisplay.revalidate();
    // transitionsDisplay.validate();
    transitionsDisplay.repaint();
    frame.revalidate();
    // frame.validate();
    frame.repaint();
    }

    public void setTransitionsImageInED(String imgPath) {
    final Runnable guiRunner =
        new Runnable() {
        public void run() { setTransitionsImage(imgPath); }
        };
    // javax.swing.SwingUtilities.invokeLater(guiRunner);
    try {
        javax.swing.SwingUtilities.invokeAndWait(guiRunner);
    } catch (InterruptedException e) {
        System.out.println(">>> WARNING <<< InterruptedException while creating the GUI");
    } catch (InvocationTargetException e) {
        System.out.println(">>> WARNING <<< InvocationTargetException while creating the GUI");
    }
    }
}

ImageDrawer.java:

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageDrawer {

    public static void drawImage() throws Exception {
    try {
        int width = 20 + (int)(Math.random() * 1000);
        int height = 20 + (int)(Math.random() * 1000);

        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D ig2 = bi.createGraphics();
        ig2.setPaint(Color.blue);
        ig2.fillRect(0, 0, width, height);
        ig2.setPaint(Color.red);
        ig2.fillRect(5, 5, width - 10, height - 10);
        ig2.setPaint(Color.blue);
        ig2.drawLine(0, 0, width, height);
        ig2.drawLine(0, height, width, 0);

        ImageIO.write(bi, "PNG", new File("image.png"));

    } catch (IOException ie) {
        ie.printStackTrace();
    }
    }
}

Can someone explain why I have this problem? Thanks!

Body:
transitionsDisplay.setPreferredSize(new Dimension(200,200));
executionsDisplay.setPreferredSize(new Dimension(200,200));
tracesDisplay.setPreferredSize(new Dimension(200,200));
textInfoAreaSP.setPreferredSize(new Dimension(200,100));

Don't use setPreferredSize(...). Each Swing component is responsible for determining its own size.

The image size is retrieved using ImageIcon.getIconWith() and getIconHeight(). And the JLabel preferred size is updated with those dimensions.

Not necessary. Again the JLabel will determine its own size based on the size of the Icon. This is done dynamically as the image/icon changes.

The scrollbars of the scrollpane will appear when the preferred size of the label is greater than the size of the scrollpane. Just let the layout managers do their job.


来源: stackexchange

问:
Serial object as function parameter in Arduino
I have a class called Client. The constructor of that class is defined as

```<code>Client(HardwareSerial * serial);
</code>```

I also have a private field HardwareSerial * serial in my class. In the constructor I assign this->serial = serial. The class is initiated with Client * client = new Client(&Serial2);.

Everything is fine until I call this->serial->begin(baud) in the constructor. Arduino gets stuck after this point. What is happening?

Class definition

```<code>#include <HardwareSerial.h>

class Client {
  private:
    HardwareSerial * serial;

  public:
    Client(HardwareSerial * serial);
};
</code>```

Class implementation

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

Client::Client(HardwareSerial * serial) {
  this->serial = serial;
  this->serial->begin(115200);
}
</code>```

And instantiation

```<code>Client * client = new Client(&Serial2);
</code>```

Passing a Stream object to the class instead (changing the variable types, of course) and calling begin in the Arduino setup function works but this is not optimal. This way the class won't handle the calling of the begin function.

答:
The constructor gets called before the serial interface is initialized.

You need to have a begin method that is then called inside setup().

Client.h

```<code>#include <HardwareSerial.h>

class Client {
  private:
    HardwareSerial * serial;

  public:
    Client(HardwareSerial * serial);
    void begin();
};
</code>```

Client.cpp

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

Client::Client(HardwareSerial * serial) {
  this->serial = serial;
}

void Client::begin() {
  this->serial->begin(115200);
}
</code>```

Your program:

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

Client * client = new Client(&Serial2);

void setup() {
  client->begin();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a class called Client. The constructor of that class is defined as

Client(HardwareSerial * serial);

I also have a private field HardwareSerial * serial in my class. In the constructor I assign this->serial = serial. The class is initiated with Client * client = new Client(&Serial2);.

Everything is fine until I call this->serial->begin(baud) in the constructor. Arduino gets stuck after this point. What is happening?

Class definition

#include <HardwareSerial.h>

class Client {
  private:
    HardwareSerial * serial;

  public:
    Client(HardwareSerial * serial);
};

Class implementation

#include "Client.h"

Client::Client(HardwareSerial * serial) {
  this->serial = serial;
  this->serial->begin(115200);
}

And instantiation

Client * client = new Client(&Serial2);

Passing a Stream object to the class instead (changing the variable types, of course) and calling begin in the Arduino setup function works but this is not optimal. This way the class won't handle the calling of the begin function.

Body:
The constructor gets called before the serial interface is initialized.

You need to have a begin method that is then called inside setup().

Client.h

#include <HardwareSerial.h>

class Client {
  private:
    HardwareSerial * serial;

  public:
    Client(HardwareSerial * serial);
    void begin();
};

Client.cpp

#include "Client.h"

Client::Client(HardwareSerial * serial) {
  this->serial = serial;
}

void Client::begin() {
  this->serial->begin(115200);
}

Your program:

#include "Client.h"

Client * client = new Client(&Serial2);

void setup() {
  client->begin();
}


问:
Excluding lines conditional upon multiple fields with awk
I have a pretty simple awk question:

I have the following file test1.txt

```<code>ids op  count
id1 op1 1
id7 op1 2
id13    op1 3
id4 op1 4
id10    op1 5
id11    op2 1
id2 op2 2
id8 op2 3
id14    op2 4
id5 op2 5
</code>```

I would like to exclude certain rows based on the op and count columns. For example exclude anything in op2 that has a count from 2 to 5, finally giving me the following test2.txt:

```<code>ids op  count
id1 op1 1
id7 op1 2
id13    op1 3
id4 op1 4
id10    op1 5
id11    op2 1
id5 op2 5
</code>```

I'm looking for an awk code that would do something like:

```<code>awk '{
    if($2 ~ /op2/ && $3>1 && $3<5)
    skip
    else
    print $0
    }' test1.txt > test2.txt
</code>```

This code actually works. But I appreciate any suggestions for 1 liners.

Many thanks!

答:
If yo want an onliner, try:</p>

```<code>awk '($2 != "op2") || ($3 <= 1) || ($3 >= 5) { print }' test1.txt > test2.txt
</code>```

Body:
I have a pretty simple awk question:

I have the following file test1.txt

ids op  count
id1 op1 1
id7 op1 2
id13    op1 3
id4 op1 4
id10    op1 5
id11    op2 1
id2 op2 2
id8 op2 3
id14    op2 4
id5 op2 5

I would like to exclude certain rows based on the op and count columns. For example exclude anything in op2 that has a count from 2 to 5, finally giving me the following test2.txt:

ids op  count
id1 op1 1
id7 op1 2
id13    op1 3
id4 op1 4
id10    op1 5
id11    op2 1
id5 op2 5

I'm looking for an awk code that would do something like:

awk '{
    if($2 ~ /op2/ && $3>1 && $3<5)
    skip
    else
    print $0
    }' test1.txt > test2.txt

This code actually works. But I appreciate any suggestions for 1 liners.

Many thanks!

Body:
If yo want an onliner, try:

awk '($2 != "op2") || ($3 <= 1) || ($3 >= 5) { print }' test1.txt > test2.txt


问:
I want to resize certain images on my site ONLY on mobile
On the website I have I can only input code into the body and the footer.

The website is bothellhomes.com. The homepage shows three round images. On a mobile device, I want to resize the images so they show horizontally. Right now, since the images are so large, they go vertically.

Body code:

```<code><section class="three-widgets">
<ul class="small-block-grid-1 medium-block-grid-3 text-center">
<li><a title="Advanced Search" href="/search/advanced_search/"><img src="https://u.realgeeks.media/lookinwa/advancedsearch.png" alt="Advanced Search" width="300" height="300" /></a></li>
<li><a title="Interactive Map Search" href="/map_search/results/9k/1/#/?city=Kenmore&city=Bothell&city=Kirkland&city=Woodinville&city=Bellevue&city=Lynnwood&city=Mill%20Creek&city=Redmond&page=1&list_price_max=800000&per_page=100&type=res&type=con&list_price_min=250000"><img src="https://u.realgeeks.media/lookinwa/mapsearch.png" alt="Interactive Map Search" width="300" height="300" /></a></li>
<li><a title="What's My Home Worth?" href="/cma/property-valuation/"><img src="https://u.realgeeks.media/lookinwa/homevaluation.png" alt="Home Value" width="300" height="300" /></a></li>
</ul>
</section>
</code>```

Footer code:

```<code><script>// <![CDATA[
document.write("<style>.three-widgets {margin-top: -60px;}.three-widgets img {background: #fff;border: 1px solid #ddd;border-radius: 100%;padding: 5px;}.three-widgets p {color: #000}.three-widgets li img {     opacity: .9;-webkit-transition: all 0.3s ease-out;     -moz-transition: all 0.3s ease-out;     -o-transition: all 0.3s ease-out;transition: all 0.3s ease-out;}.three-widgets li:hover img {border: 1px solid #444444;opacity: 1; -webkit-transform: scale(1.1);-moz-transform: scale(1.1);-ms-transform: scale(1.1);transform: scale(1.1);}@media (max-width:767px) {.three-widgets {     margin-top: 0}}h1{ line-height:38px!important}</style>");
// ]]></script>
</code>```

答:
Not sure why you cannot use css.  But it seems like you cannot so you can use inline styles to just float them next to each other.  Keep in mind that it will become really small images the smaller the screen size is.

```<code><li style="float:left;width="30%">
</code>```

put this style on all the
 elements.  and the middle one should perhaps have 5% margin on each side to prevent the image edges from touching each other.

```<code> <li style="float:left;width="30%;margin:0 5%;">
</code>```

You also need to remove the height of the image and only set the width of the image to 100% so it will stretch to the edge of it's container which is the li.

You can of course do the same with css by giving the li's a class and floating them left.

Body:
On the website I have I can only input code into the body and the footer.

The website is bothellhomes.com. The homepage shows three round images. On a mobile device, I want to resize the images so they show horizontally. Right now, since the images are so large, they go vertically.

Body code:

Footer code:

Body:
Not sure why you cannot use css.  But it seems like you cannot so you can use inline styles to just float them next to each other.  Keep in mind that it will become really small images the smaller the screen size is.

<li style="float:left;width="30%">

put this style on all the < li > elements.  and the middle one should perhaps have 5% margin on each side to prevent the image edges from touching each other.

 <li style="float:left;width="30%;margin:0 5%;">

You also need to remove the height of the image and only set the width of the image to 100% so it will stretch to the edge of it's container which is the li.

You can of course do the same with css by giving the li's a class and floating them left.


问:
Interacting between two pieces of Swift code (Apple ARKit sample code)
Apple has posted some sample code for "Creating Face-Based AR Experiences" here. </p>

<p>My question deals with passing a variable between two sections of code.  In RobotHead.swift I would like to detect a condition within blendShapes, and somehow pass it back to ViewController.swift so code in the ViewController can react to that condition.  What is the simplest way to do this?  Thank you. </p>

答:
One thing you could do is create a public function in your ViewController class, pass your view controller to VirualContentUpdater, and then call the method from its renderer(:didUpdate:for) function.

In ViewController.swift:

```<code>override func viewDidLoad() {
    contentUpdater.viewController = self
    /* ... */
}

public func update(withFaceAnchor anchor: ARFaceAnchor) {
    // do something with anchor.blendShapes
}
</code>```

In VirtualContentUpdater.swift

```<code>public var viewController: ViewController?
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
    viewController?.update(withFaceAnchor: anchor)
    /* ... */
}
</code>```

Body:
Apple has posted some sample code for "Creating Face-Based AR Experiences" here.

My question deals with passing a variable between two sections of code.  In RobotHead.swift I would like to detect a condition within blendShapes, and somehow pass it back to ViewController.swift so code in the ViewController can react to that condition.  What is the simplest way to do this?  Thank you.

Body:
One thing you could do is create a public function in your ViewController class, pass your view controller to VirualContentUpdater, and then call the method from its renderer(:didUpdate:for) function.

In ViewController.swift:

override func viewDidLoad() {
    contentUpdater.viewController = self
    /* ... */
}

public func update(withFaceAnchor anchor: ARFaceAnchor) {
    // do something with anchor.blendShapes
}

In VirtualContentUpdater.swift

public var viewController: ViewController?
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
    viewController?.update(withFaceAnchor: anchor)
    /* ... */
}


问:
Last name usort
I asked a similar question but still having issues when some aspects.
The way this php file is working is that a persons name is being stored in the database in the names cell, in the format John Doe(firstname lastname).  So I've separated the name with this code, so surname, firstname:

```<code>foreach ($customer_names as $key => $value) {
                        $parts = explode(" ", $value->name);
                        $lastname = array_pop($parts);
                        $firstname = implode(" ", $parts);
                        $name = $lastname.", ".$firstname." ";

                        echo "<option value='$value->name'>$name </option>";
</code>```

now that gives me a list of names like Doe, John.
However, I need to sort the names in order of the surname.
using usort.  How would I do that?  I've tried playing around with the code, but still is showing up in the order of the first name (set by the db query).
Still a bit new to usort functionality.

答:
```<code>//Program for sorting list of names according to last name
<?php
class array_sort
{
    public $temp;
    public function alhsort(array $sorted)
     {
        for($i=0; $i<count($sorted)-1; $i++){
            for($j=$i+1; $j<count($sorted); $j++){
                if(strcasecmp(end(explode(' ', $sorted[$i])), end(explode(' ', $sorted[$j])))>0){
                    $temp =  $sorted[$i];
                    $sorted[$i] = $sorted[$j];
                    $sorted[$j] = $temp;
                }
            }
        }
        return $sorted;
      }
}
$sortarray = new array_sort();
print_r($sortarray->alhsort(array('Ayush Jain', 'Abhishek Gupta', 'Rahul Rajput', 'Kapil Patel', 'Shobit Shrivastav', 'Hitesh Gupta')));
?>
</code>```

Title: Last name usort

Body:
I asked a similar question but still having issues when some aspects.
The way this php file is working is that a persons name is being stored in the database in the names cell, in the format John Doe(firstname lastname).  So I've separated the name with this code, so surname, firstname:

foreach ($customer_names as $key => $value) {
                        $parts = explode(" ", $value->name);
                        $lastname = array_pop($parts);
                        $firstname = implode(" ", $parts);
                        $name = $lastname.", ".$firstname." ";

                        echo "<option value='$value->name'>$name </option>";

now that gives me a list of names like Doe, John.
However, I need to sort the names in order of the surname.
using usort.  How would I do that?  I've tried playing around with the code, but still is showing up in the order of the first name (set by the db query).
Still a bit new to usort functionality.


问:
UILabel layer cornerRadius negatively impacting performance
I've created a document view which displays the page number in the corner.  The page number is a uilabel with a semi-transparent background colour, and has a corner radius (using the cornerRadius property of the view's layer).  I've positioned this above a UIScrollView.  However, this makes scrolling jerky.  If I remove the cornerRadius, performance is good.  Is there anything I can do about this?  What would be a better solution?  It seems to have been achieved in the UIWebView without any performance issues.

答:
I had a similar issue with UILabel in a custom UITableViewCell with rounded corners. To get smooth performance I 'made' images with rounded-corners to get around this (see).

Lots of other posts, including this, or this might help out.

ContentLicense: CC BY-SA 2.5


问:
Mxnet Gluon custom data iterator
I have written a custom data iterator using mx.io.DataIter class. What's the easiest way to use this data iterator with Gluon interface?

I went through the documentation and couldn't find an easy way to do so. One of my idea was to use it as iterator and get data adn label from each batch as follows.

```<code>for e in range(epochs):
    train_iter.reset()
    for batch_data in train_iter:
        data = nd.concatenate(([d for d in batch_data.data]))
        label = nd.concatenate(([l for l in batch_data.label]))
        with autograd.record():
            output = net(data)
            loss = softmax_cross_entropy(output, label)
        loss.backward()
        trainer.step(batch_size)
        print(nd.mean(loss).asscalar())
</code>```

But this may not be optimal as I need to concatenate per batch.

What's the optimal way to achieve this? i.e. is there a systematic

way to write a simple custom iterator for gluon?

How do I add context information in above cases?

答:
I think your approach works. Basically you can get data from batch_data.data and label from batch_data.label and feed them into the network.

I'm not sure why you need to concat the data and labels - maybe it's to do with your network definition.

If you ever need to split the data and train on multiple GPUs, you can use the gluon.utils.split_and_load function to do that.

Title: Mxnet Gluon custom data iterator

Body:
I have written a custom data iterator using mx.io.DataIter class. What's the easiest way to use this data iterator with Gluon interface?

I went through the documentation and couldn't find an easy way to do so. One of my idea was to use it as iterator and get data adn label from each batch as follows.

for e in range(epochs):
    train_iter.reset()
    for batch_data in train_iter:
        data = nd.concatenate(([d for d in batch_data.data]))
        label = nd.concatenate(([l for l in batch_data.label]))
        with autograd.record():
            output = net(data)
            loss = softmax_cross_entropy(output, label)
        loss.backward()
        trainer.step(batch_size)
        print(nd.mean(loss).asscalar())

But this may not be optimal as I need to concatenate per batch.

What's the optimal way to achieve this? i.e. is there a systematic

way to write a simple custom iterator for gluon?

How do I add context information in above cases?


问:
Spring Data GemFire 2.0.1.RELEASE is throwing an Initialization Error
Initially, my application was running fine with spring-data-gemfire 1.9.7.RELEASE.  However, after upgrading to spring-data-gemfire 2.0.1.RELEASE, my application fails to start and throws an Initialization Error as shown below:

C:\Dev\projects\JavaWebClient\web\target>java -jar
  web-0.0.1-SNAPSHOT.jar

.   ____          _            __ _ _

   /\ / ' __ _ ()_ __  __ _ \ \ \ \

  ( ( )_ | '_ | '| | ' / ` | \ \ \ \

   \/  )| |)| | | | | || (| |  ) ) ) )

    '  |____| .|| ||| |__, | / / / /

   =========|_|==============|___/=///_/

   :: Spring Boot ::        (v1.5.8.RELEASE)

[info 2017/11/15 19:07:23.999 EAT  tid=0x1] Starting
  JavaWebClientApplication v0.0.1-SNAPSHOT on MY-PC with PID 13804
  (C:\Dev\projects\JavaWebClient\web\target\web-0.0.1-SNAPSHOT.jar
  started by edwards in C:\Dev\projects\JavaWebClient\web\target)

[info 2017/11/15 19:07:24.019 EAT  tid=0x1] No active profile
  set, falling back to default profiles: default

[info 2017/11/15 19:07:24.812 EAT  tid=0x1] Refreshing
  org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6e6c3152:
  startup date [Wed Nov 15 19:07:24 EAT 2017]; root of context
  hierarchy

[error 2017/11/15 19:07:25.892 EAT  tid=0x1] Application startup
  failed java.lang.NoSuchMethodError:
  org.springframework.data.repository.config.RepositoryConfigurationSource.getAttribute(Ljava/lang/String;)Ljava/util/Optional;
          at org.springframework.data.gemfire.repository.config.GemfireRepositoryConfigurationExtension.registerBeansForRoot(GemfireRepositoryConfigurationExtensi
  on.java:120)
          at org.springframework.data.repository.config.RepositoryConfigurationDelegate.registerRepositoriesIn(RepositoryConfigurationDelegate.java:116)
          at org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport.registerBeanDefinitions(RepositoryBeanDefinitionRegistrarSupport.
  java:83)
          at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.lambda$loadBeanDefinitionsFromRegistrars$0(ConfigurationClassBeanDefini
  tionReader.java:360)
          at java.util.LinkedHashMap.forEach(Unknown Source)
          at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromRegistrars(ConfigurationClassBeanDefinitionReade
  r.java:359)
          at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefiniti
  onReader.java:144)
          at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:117)
          at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:328)
          at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:233)
          at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.ja
  va:273)
          at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:93)
          at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:693)
          at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531)
          at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
          at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
          at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
          at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
          at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
          at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
          at com.nftconsult.gemfire.web.JavaWebClientApplication.main(JavaWebClientApplication.java:173)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
          at java.lang.reflect.Method.invoke(Unknown Source)
          at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
          at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
          at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
          at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)

[info 2017/11/15 19:07:25.897 EAT  tid=0x1] Closing
  org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6e6c3152:
  startup date [Wed Nov 15 19:07:24 EAT 2017]; root of context
  hierarchy

[warn 2017/11/15 19:07:25.901 EAT  tid=0x1] Exception thrown
  from LifecycleProcessor on context close
  java.lang.IllegalStateException: LifecycleProcessor not initialized -
  call 'refresh' before invoking lifecycle methods via the context:
  org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6e6c3152:
  startup date [Wed Nov 15 19:07:24 EAT 2017]; root of context hierarchy
          at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:433)
          at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1004)
          at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:963)
          at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:750)
          at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
          at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
          at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
          at com.nftconsult.gemfire.web.JavaWebClientApplication.main(JavaWebClientApplication.java:173)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
          at java.lang.reflect.Method.invoke(Unknown Source)
          at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
          at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
          at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
          at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)

[error 2017/11/15 19:07:25.905 EAT  tid=0x1] Destroy method on
  bean with name
  'org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory
  ' threw an exception java.lang.IllegalStateException:
  ApplicationEventMulticaster not initialized - call 'refresh' before
  multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6e6c3152:
  startup date [Wed Nov 15 19:07:24 EAT 2017]; root of context hierarchy
          at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:420)
          at org.springframework.context.support.ApplicationListenerDetector.postProcessBeforeDestruction(ApplicationListenerDetector.java:95)
          at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:240)
          at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:576)
          at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:552)
          at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:953)
          at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:521)
          at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.destroySingletons(FactoryBeanRegistrySupport.java:227)
          at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:960)
          at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1035)
          at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1011)
          at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:963)
          at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:750)
          at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
          at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
          at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
          at com.nftconsult.gemfire.web.JavaWebClientApplication.main(JavaWebClientApplication.java:173)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
          at java.lang.reflect.Method.invoke(Unknown Source)
          at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
          at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
          at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
          at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)

C:\Dev\projects\JavaWebClient\web\target>

答:
Not surprising since your Spring application is based on Spring Boot 1.5.8.RELEASE and it isn't clear how you specifically upgraded the Spring Data GemFire dependency from 1.9.7.RELEASE to 2.0.1.RELEASE.

The problem is, you are pulling in an incompatible version of Spring Data Commons as well as, and I suspect, several other Spring dependencies (e.g. the core Spring Framework) since your applications is rooted in Spring Boot 1.5.8.RELEASE.  Hence the java.lang.NoSuchMethodError error...

```<code>java.lang.NoSuchMethodError: org.springframework.data.repository.config.RepositoryConfigurationSource.getAttribute(Ljava/lang/String;)Ljava/util/Optional;
at org.springframework.data.gemfire.repository.config.GemfireRepositoryConfigurationExtension.registerBeansForRoot(GemfireRepositoryConfigurationExtensi on.java:120)
</code>```

First, you need to understand that all Spring Data modules (see "Main modules", "Community modules" and "Related modules" and the section about the "Release train" on the SD project page) build on a particular version of both Spring Data Commons and the core Spring Framework.  You cannot simply upgrade 1 dependency and not expect to have to upgrade others.

The SD Release Trains (such as Ingalls or Kay) are all based on a particular version of Spring Data Commons and the core Spring Framework.  For instance, with SD Kay, see "Core themes" and "Participating modules".

The java.lang.NoSuchMethodError is specifically occurring because you are using an incompatible version of Spring Data Commons (i.e. SDC 1.13.8.RELEASE from Ingalls, which is pulled in by Spring Boot 1.5.x) with Spring Data GemFire 2.0.1.RELEASE, which comes from SD Kay, and expects SDC 2.0.x.RELEASE.

This class, (i.e. org.springframework.data.repository.config.RepositoryConfigurationSource) is a Spring Data Commons class.  Clearly the method signature (i.e. getAttribute(:String):String) in SDC 1.13.8 (Ingalls) for the method in question is not what SDG 2.0.1.RELEASE expects (i.e. getAttribute(:String):Optional<String>), which comes from SDC 2.0.1.RELEASE.

There is a reason why Spring Boot, and by extension, the Spring IO Platform, provide a curated and harmonized set of dependencies that have all been tested and proven to work together.  When you deviate from the prescribed dependencies, you need to be mindful of this.

Technically, only the upcoming Spring Boot 2.0 release will be based on SD Kay.

However, if you do need a GA release of Spring Boot (i.e. 1.5.8.RELEASE, the current latest) and wish to use Spring Data GemFire 2.0.1.RELEASE, or Kay-SR1, then fortunately you are in luck!

I too wanted to use Spring Data Kay with the latest GA version of Spring Boot (i.e. 1.5.8.RELEASE) in the Spring IO Guides (for instance) to showcase the new features in Spring Data GemFire 2.0.x Kay, since many things have changed for the better (like this).

I was able to get this to work, but I need to set specific things in the Maven (or Gradle) build file, such as overriding the dependency versions of SD and the core Spring Framework managed by Spring Boot (specifically this, and this).  Note this as well.  Also note my dependencies.

Gradle is a bit more tricky, but you can see the new build file here and compare it with the previous version here.

Anyway, keep these things in mind the next time you are wrangling dependency versions, which is the whole reason why Spring IO Platform was created in the first place, to manage all the dependencies and dependencies of dependencies (i.e. transitive dependencies) when possible overlap/conflicts occur (since certain transitive dependencies will have the same dependencies), etc, etc.

Hope this helps!

Regards,
-j

Body:
Not surprising since your Spring application is based on Spring Boot 1.5.8.RELEASE and it isn't clear how you specifically upgraded the Spring Data GemFire dependency from 1.9.7.RELEASE to 2.0.1.RELEASE.

The problem is, you are pulling in an incompatible version of Spring Data Commons as well as, and I suspect, several other Spring dependencies (e.g. the core Spring Framework) since your applications is rooted in Spring Boot 1.5.8.RELEASE.  Hence the java.lang.NoSuchMethodError error...

java.lang.NoSuchMethodError: org.springframework.data.repository.config.RepositoryConfigurationSource.getAttribute(Ljava/lang/String;)Ljava/util/Optional;
at org.springframework.data.gemfire.repository.config.GemfireRepositoryConfigurationExtension.registerBeansForRoot(GemfireRepositoryConfigurationExtensi on.java:120)

First, you need to understand that all Spring Data modules (see "Main modules", "Community modules" and "Related modules" and the section about the "Release train" on the SD project page) build on a particular version of both Spring Data Commons and the core Spring Framework.  You cannot simply upgrade 1 dependency and not expect to have to upgrade others.

The SD Release Trains (such as Ingalls or Kay) are all based on a particular version of Spring Data Commons and the core Spring Framework.  For instance, with SD Kay, see "Core themes" and "Participating modules".

The java.lang.NoSuchMethodError is specifically occurring because you are using an incompatible version of Spring Data Commons (i.e. SDC 1.13.8.RELEASE from Ingalls, which is pulled in by Spring Boot 1.5.x) with Spring Data GemFire 2.0.1.RELEASE, which comes from SD Kay, and expects SDC 2.0.x.RELEASE.

This class, (i.e. org.springframework.data.repository.config.RepositoryConfigurationSource) is a Spring Data Commons class.  Clearly the method signature (i.e. getAttribute(:String):String) in SDC 1.13.8 (Ingalls) for the method in question is not what SDG 2.0.1.RELEASE expects (i.e. getAttribute(:String):Optional<String>), which comes from SDC 2.0.1.RELEASE.

There is a reason why Spring Boot, and by extension, the Spring IO Platform, provide a curated and harmonized set of dependencies that have all been tested and proven to work together.  When you deviate from the prescribed dependencies, you need to be mindful of this.

Technically, only the upcoming Spring Boot 2.0 release will be based on SD Kay.

However, if you do need a GA release of Spring Boot (i.e. 1.5.8.RELEASE, the current latest) and wish to use Spring Data GemFire 2.0.1.RELEASE, or Kay-SR1, then fortunately you are in luck!

I too wanted to use Spring Data Kay with the latest GA version of Spring Boot (i.e. 1.5.8.RELEASE) in the Spring IO Guides (for instance) to showcase the new features in Spring Data GemFire 2.0.x Kay, since many things have changed for the better (like this).

I was able to get this to work, but I need to set specific things in the Maven (or Gradle) build file, such as overriding the dependency versions of SD and the core Spring Framework managed by Spring Boot (specifically this, and this).  Note this as well.  Also note my dependencies.

Gradle is a bit more tricky, but you can see the new build file here and compare it with the previous version here.

Anyway, keep these things in mind the next time you are wrangling dependency versions, which is the whole reason why Spring IO Platform was created in the first place, to manage all the dependencies and dependencies of dependencies (i.e. transitive dependencies) when possible overlap/conflicts occur (since certain transitive dependencies will have the same dependencies), etc, etc.

Hope this helps!

Regards,
-j


问:
VBA - destroy a modeless UserForm instance properly
Intro:

I am aware that - showing UserForms - it's best practice to

handle QueryClose within the userform code (If CloseMode = vbFormControlMenu ...)

doing no Unload Me therein, just a timid Me.Hide instruction
(after preventing [x]-itting and eventual self-destruction via Cancel = True )

setting a related variable/[property] within the [class] code (e.g. .IsCancelled=True)

in order to be able to have the UF unloaded by the calling code.

Useful link

An outstanding overview "UserForm1.Show?" can be found at https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/
as well as in numerous examplary SO answers (thx to Mathieu Guindon aka Mat's Mug and RubberDuck).

Further selection (►edit as of 5/1 2019)

Disadvantages in putting code into userforms instead of modules

Passing variable from form to module

Apply logic for userform dialog (Rubberduck)

The perfect userform (Vitosh academy)

1) Working examples for modal UserForms

As far as I understood - and I do try to learn -, the following code should be okay for modal UF's:

Case 1a) .. with a local variable for the UF instance, as often seen:

```<code>Public Sub ShowFormA
  Dim ufA As UserForm1
  Set ufA = New UserForm1
' show userform
  ufA.Show          ' equivalent to: ufA.Show vbModal

' handle data after user okay
  If Not ufA.IsCancelled Then
      '  do something ...
  End If

' >> object reference destroyed expressly (as seen in some examples)
  unload ufA
End Sub
</code>```

Case 1b) .. without a local variable, but using a With New codeblock:

```<code>' ----------------------------------------------------------
' >> no need to destruct object reference expressly,
'    as it will be destroyed whenever exiting the with block
' ----------------------------------------------------------
  With New UserForm1
      .Show         ' equivalent to: ufA.Show vbModal

    ' handle data after user okay
      If Not .IsCancelled Then
      '  do something ...
      End If
  End With
</code>```

2) Problem

Problems arise using a MODELESS UserForm instance.

Okay, the with block method (cf. 1b) should be sufficient to destroy any object reference after x-iting it:

```<code>  With New UserForm1
      .Show vbModeless  ' << show modeless uf
  End With
</code>```

If I try, however to

a) get information about a possible user cancelling as well as

b) to Unload a form if baptized using a local variable (e.g. "ufA") after the Show instruction,

all code lines will be executed at once for precisely the reason that the form is MODELESS:

code shows the form, the next moment ..

code finds no user cancelling, as there was no time for any user action, the next moment ..

[code unloads the form if using a local variable for the userform]

3) Question

How can I handle a) correctly reported UserForm cancels by the calling code of a MODELESS form as well as b) a (necessary?) unloading if using a local variable?

答:
For modeless forms, Use DoEvents coupled with custom userform property.

```<code>Sub test()

    Dim frm As New UserForm1

    frm.Show vbModeless

    Do
        DoEvents
        If frm.Cancelled Then
            Unload frm
        Exit Do
    End If
    Loop Until False

    MsgBox "You closed the modeless form."

    '/ Using With
    With New UserForm1
        .Show vbModeless
        Do
            DoEvents
            If .Cancelled Then Exit Do
        Loop Until False
    End With

    MsgBox "You closed the modeless form (with)"

End Sub
</code>```

'/ User Form

```<code>Private m_bCancelled As Boolean

Public Property Get Cancelled() As Boolean
    Cancelled = m_bCancelled
End Property

Public Property Let Cancelled(ByVal bNewValue As Boolean)
    m_bCancelled = bNewValue
End Property
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    Me.Cancelled = True
    Cancel = 1
    Me.Hide
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Intro:

I am aware that - showing UserForms - it's best practice to

handle QueryClose within the userform code (If CloseMode = vbFormControlMenu ...)

doing no Unload Me therein, just a timid Me.Hide instruction
(after preventing [x]-itting and eventual self-destruction via Cancel = True )

setting a related variable/[property] within the [class] code (e.g. .IsCancelled=True)

in order to be able to have the UF unloaded by the calling code.

Useful link

An outstanding overview "UserForm1.Show?" can be found at https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/
as well as in numerous examplary SO answers (thx to Mathieu Guindon aka Mat's Mug and RubberDuck).

Further selection (►edit as of 5/1 2019)

Disadvantages in putting code into userforms instead of modules

Passing variable from form to module

Apply logic for userform dialog (Rubberduck)

The perfect userform (Vitosh academy)

1) Working examples for modal UserForms

As far as I understood - and I do try to learn -, the following code should be okay for modal UF's:

Case 1a) .. with a local variable for the UF instance, as often seen:

Public Sub ShowFormA
  Dim ufA As UserForm1
  Set ufA = New UserForm1
' show userform
  ufA.Show          ' equivalent to: ufA.Show vbModal

' handle data after user okay
  If Not ufA.IsCancelled Then
      '  do something ...
  End If

' >> object reference destroyed expressly (as seen in some examples)
  unload ufA
End Sub

Case 1b) .. without a local variable, but using a With New codeblock:

' ----------------------------------------------------------
' >> no need to destruct object reference expressly,
'    as it will be destroyed whenever exiting the with block
' ----------------------------------------------------------
  With New UserForm1
      .Show         ' equivalent to: ufA.Show vbModal

    ' handle data after user okay
      If Not .IsCancelled Then
      '  do something ...
      End If
  End With

2) Problem

Problems arise using a MODELESS UserForm instance.

Okay, the with block method (cf. 1b) should be sufficient to destroy any object reference after x-iting it:

  With New UserForm1
      .Show vbModeless  ' << show modeless uf
  End With

If I try, however to

a) get information about a possible user cancelling as well as

b) to Unload a form if baptized using a local variable (e.g. "ufA") after the Show instruction,

all code lines will be executed at once for precisely the reason that the form is MODELESS:

code shows the form, the next moment ..

code finds no user cancelling, as there was no time for any user action, the next moment ..

[code unloads the form if using a local variable for the userform]

3) Question

How can I handle a) correctly reported UserForm cancels by the calling code of a MODELESS form as well as b) a (necessary?) unloading if using a local variable?

Body:
For modeless forms, Use DoEvents coupled with custom userform property.

Sub test()

    Dim frm As New UserForm1

    frm.Show vbModeless

    Do
        DoEvents
        If frm.Cancelled Then
            Unload frm
        Exit Do
    End If
    Loop Until False

    MsgBox "You closed the modeless form."

    '/ Using With
    With New UserForm1
        .Show vbModeless
        Do
            DoEvents
            If .Cancelled Then Exit Do
        Loop Until False
    End With

    MsgBox "You closed the modeless form (with)"

End Sub

'/ User Form

Private m_bCancelled As Boolean

Public Property Get Cancelled() As Boolean
    Cancelled = m_bCancelled
End Property

Public Property Let Cancelled(ByVal bNewValue As Boolean)
    m_bCancelled = bNewValue
End Property
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    Me.Cancelled = True
    Cancel = 1
    Me.Hide
End Sub


问:
Redirect after posting form using XMLHttpRequest
Following scenario. I have a simple login-form for username and password.
Wher the user clicks the login-button the form is posted to the server which is checking the credentials. When they are okay, a redirect is made to the default landing-page.

For sending the form-data I have written the following:

```<code>static async postData<TResult>(options: { method: string, url: string, data?: any }): Promise<TResult> {
    return new Promise<TResult>((resolve, reject) => {
        try {
            const xhr = new XMLHttpRequest();

            xhr.onload = (): void => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        resolve(xhr.response);
                    } else {
                        reject(xhr.status);
                    }
                }
            };

            xhr.withCredentials = true;
            xhr.open(options.method, options.url, true);
            xhr.send(options.data);
        } catch (e) {
            console.error(e);
        }
    });
}
</code>```

which is called like:

```<code>const response = await postData({ method: theForm.method, url: theForm.action, data: formData })
    .then(response => {
        console.log(response);
    })
    .catch(reason => {
        console.error(reason);
    });
</code>```

In Chrome and Firefox the response has an responseURL-property which I could use for setting window.location.url = xhr.responseURL; to redirect the page. But this wont work in IE as the response-type is something completely other.
On the other hand I have the complete HTML (which is the content of the redirect aka the landing-page) in xhr.responseText but I have no idea how I can use this?

I tried to replace the page-content as described here But this is throwing a bunch of errors in Chrome and IE it's not working at all showing

SCRIPT70: Permission denied

Some additional notes. I am using TypeScript to write the client-code which is targeted to es6 and afterwards transpiled using babel-loader to es5 via webpack.

答:
I think you need try next code: </p>

```<code>    location.href = 'http://www.example.com' or
    location.assign("http://www.mozilla.org"); // or
    location = "http://www.mozilla.org";
</code>```

Body:
Following scenario. I have a simple login-form for username and password.
Wher the user clicks the login-button the form is posted to the server which is checking the credentials. When they are okay, a redirect is made to the default landing-page.

For sending the form-data I have written the following:

static async postData<TResult>(options: { method: string, url: string, data?: any }): Promise<TResult> {
    return new Promise<TResult>((resolve, reject) => {
        try {
            const xhr = new XMLHttpRequest();

            xhr.onload = (): void => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        resolve(xhr.response);
                    } else {
                        reject(xhr.status);
                    }
                }
            };

            xhr.withCredentials = true;
            xhr.open(options.method, options.url, true);
            xhr.send(options.data);
        } catch (e) {
            console.error(e);
        }
    });
}

which is called like:

const response = await postData({ method: theForm.method, url: theForm.action, data: formData })
    .then(response => {
        console.log(response);
    })
    .catch(reason => {
        console.error(reason);
    });

In Chrome and Firefox the response has an responseURL-property which I could use for setting window.location.url = xhr.responseURL; to redirect the page. But this wont work in IE as the response-type is something completely other.
On the other hand I have the complete HTML (which is the content of the redirect aka the landing-page) in xhr.responseText but I have no idea how I can use this?

I tried to replace the page-content as described here But this is throwing a bunch of errors in Chrome and IE it's not working at all showing

SCRIPT70: Permission denied

Some additional notes. I am using TypeScript to write the client-code which is targeted to es6 and afterwards transpiled using babel-loader to es5 via webpack.

Body:
I think you need try next code:

    location.href = 'http://www.example.com' or
    location.assign("http://www.mozilla.org"); // or
    location = "http://www.mozilla.org";


问:
Get ASPNET Core Razor Page name in _Layout file to update navigation items
Using Bootstrap 4 and need to add the active class to navigation items to reflect current Razor page (new razor pages in Core 2.0).  How can I find out which page/controller I am on so I can add the active class name to the proper:

class="active">...

Thanks.

Update:
I was able to solve this with the following code in my page initializer:

```<code>@{
    var _action = this.Url.ActionContext.ActionDescriptor.DisplayName;
    var NavDashboard = "/abc";
    ...
}
</code>```

Then I can add the "active" class in each nav items like:

```<code><a asp-page="@NavDashboard" class="nav-link@(_action=="@NavDashboard" ? " active" : string.Empty)">Dashboard</a>
</code>```

Rinse and repeat for each nav item.

答:
I'd go with a custom tag helper to add the active class to an element.

I forked Ben Cull's ActiveRouteTagHelper for MVC and modified it for Razor Pages and called it ActivePageTagHelper. It's used similarly to his, like this:

```<code><div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li is-active-page asp-page="/Index"><a asp-page="/Index">Home</a></li>
        <li is-active-page asp-page="/About"><a asp-page="/About">About</a></li>
        <li is-active-page asp-page="/Contact"><a asp-page="/Contact">Contact</a></li>
    </ul>
</div>
</code>```

Body:
Using Bootstrap 4 and need to add the active class to navigation items to reflect current Razor page (new razor pages in Core 2.0).  How can I find out which page/controller I am on so I can add the active class name to the proper:

...

Thanks.

Update:
I was able to solve this with the following code in my page initializer:

@{
    var _action = this.Url.ActionContext.ActionDescriptor.DisplayName;
    var NavDashboard = "/abc";
    ...
}

Then I can add the "active" class in each nav items like:

Dashboard

Rinse and repeat for each nav item.

Body:
I'd go with a custom tag helper to add the active class to an element.

I forked Ben Cull's ActiveRouteTagHelper for MVC and modified it for Razor Pages and called it ActivePageTagHelper. It's used similarly to his, like this:

<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li is-active-page asp-page="/Index"><a asp-page="/Index">Home</a></li>
        <li is-active-page asp-page="/About"><a asp-page="/About">About</a></li>
        <li is-active-page asp-page="/Contact"><a asp-page="/Contact">Contact</a></li>
    </ul>
</div>


问:
Why does the choice of solver result in different weight in sklearn (LogisticRegression)
Why do different solvers result in different learned weights on simple problems in sklearn?
This doesn't smell like numerical instability -- it looks like the different solvers are designed to converge on different sets of weights.
What's going on?

It seems to be related to regularization, as the effect goes away with increasing C

```<code>%matplotlib inline
import time
import pandas as pd
import numpy as np
from sklearn.linear_model.logistic import LogisticRegression

def linear(X,b): return X.dot(b.T)
def sigmoid(X,b): return 1/(1+np.exp(-linear(X,b)))

b = np.array([1.,1.])

def mk(X,y,model):
    model.fit(X,y)
    t = time.clock()
    c = np.concatenate((model.coef_[0,:], model.intercept_[[0]]))
    return c, time.clock()-t

max_iter = 1000
tol=0.00000001
for C in [0.0001, 0.001, 0.1, 1., 10., 1000.]:
    for n in [200, 20000]:
        x = np.arange(-5., 5, 10./n)
        Xb = np.vstack([x, np.ones(len(x))]).T
        p = sigmoid(Xb,b)
        y = np.random.binomial(1, p)
        X = x.reshape((len(x), 1))
        print C, n
        for solver in ["liblinear", "newton-cg", "lbfgs", "sag"]:
            print "  {:>14}".format(solver), mk(X,y, LogisticRegression(C=C, solver=solver, penalty='l2', max_iter=max_iter, tol=tol))
</code>```

The converged coefficients are below. The training data is generated with B=[1., 1.]

```<code>C      n
0.0001 200
       liblinear (array([ 0.01858615,  0.00219137]), 1.399999999995849e-05)
       newton-cg (array([ 0.01867489,  0.44809872]), 1.5000000000098268e-05)
           lbfgs (array([ 0.01867489,  0.44809872]), 1.5000000000098268e-05)
             sag (array([ 0.01867489,  0.448096  ]), 1.3000000000040757e-05)
0.0001 20000
       liblinear (array([ 0.49062599,  0.14814571]), 2.6999999999999247e-05)
       newton-cg (array([ 0.51257455,  0.59982733]), 2.6000000000081513e-05)
           lbfgs (array([ 0.51257471,  0.59982645]), 2.8999999999834714e-05)
             sag (array([ 0.51257455,  0.59982753]), 1.3000000000040757e-05)
0.001 200
       liblinear (array([ 0.15311436,  0.0154459 ]), 1.2999999999596668e-05)
       newton-cg (array([ 0.15456163,  0.34240309]), 1.3000000000040757e-05)
           lbfgs (array([ 0.15456166,  0.34240284]), 1.3000000000040757e-05)
             sag (array([ 0.15456163,  0.34240308]), 1.100000000020529e-05)
0.001 20000
       liblinear (array([ 0.81980482,  0.58214727]), 3.799999999998249e-05)
       newton-cg (array([ 0.86826695,  0.87335432]), 3.0999999999892225e-05)
           lbfgs (array([ 0.86826513,  0.87335497]), 3.2000000000032e-05)
             sag (array([ 0.86826695,  0.87335433]), 2.9999999999752447e-05)
0.1 200
       liblinear (array([ 0.80161404,  0.39606419]), 2.3999999999801958e-05)
       newton-cg (array([ 0.82243805,  0.57384594]), 2.9000000000056758e-05)
           lbfgs (array([ 0.82243822,  0.57384605]), 3.0000000000196536e-05)
             sag (array([ 0.82243805,  0.57384595]), 2.4999999999941735e-05)
0.1 20000
       liblinear (array([ 0.98022283,  0.97426356]), 3.799999999998249e-05)
       newton-cg (array([ 0.98180586,  0.98060186]), 2.3999999999801958e-05)
           lbfgs (array([ 0.98181404,  0.98060174]), 3.1000000000336314e-05)
             sag (array([ 0.98180586,  0.98060185]), 3.0999999999892225e-05)
1.0 200
       liblinear (array([ 0.77546388,  0.68083769]), 2.3999999999801958e-05)
       newton-cg (array([ 0.78084612,  0.71273566]), 1.1999999999900979e-05)
           lbfgs (array([ 0.7808462 ,  0.71273586]), 1.3000000000040757e-05)
             sag (array([ 0.78084612,  0.71273566]), 1.0000000000065512e-05)
1.0 20000
       liblinear (array([ 1.01286416,  1.01699803]), 3.1000000000336314e-05)
       newton-cg (array([ 1.013046  ,  1.01769302]), 1.6000000000016e-05)
           lbfgs (array([ 1.0130471 ,  1.01769538]), 3.0999999999892225e-05)
             sag (array([ 1.013046  ,  1.01769301]), 2.0999999999826713e-05)
10.0 200
       liblinear (array([ 1.19187232,  1.52139602]), 9.999999999621423e-06)
       newton-cg (array([ 1.19737431,  1.53737059]), 4.300000000023729e-05)
           lbfgs (array([ 1.19737519,  1.53736531]), 1.8999999999991246e-05)
             sag (array([ 1.19737429,  1.53737061]), 1.700000000059987e-05)
10.0 20000
       liblinear (array([ 0.9993963,  0.9748259]), 9.19999999995369e-05)
       newton-cg (array([ 0.9994126 ,  0.97489034]), 3.0999999999892225e-05)
           lbfgs (array([ 0.99941332,  0.97489202]), 3.10000000007804e-05)
             sag (array([ 0.99941261,  0.97489035]), 1.4000000000180535e-05)
1000.0 200
       liblinear (array([ 1.31759982,  1.48775989]), 9.000000000369823e-06)
       newton-cg (array([ 1.3176617 ,  1.48792683]), 1.4000000000180535e-05)
           lbfgs (array([ 1.31766183,  1.48792601]), 4.499999999918458e-05)
             sag (array([ 1.31766164,  1.48792671]), 1.100000000064938e-05)
1000.0 20000
       liblinear (array([ 0.99608584,  0.96883584]), 4.099999999951365e-05)
       newton-cg (array([ 0.99608601,  0.96883648]), 3.300000000017178e-05)
           lbfgs (array([ 0.99608665,  0.96883797]), 2.9999999999752447e-05)
             sag (array([ 0.99608603,  0.96883652]), 1.5000000000320313e-05)
</code>```

And also, ... all the versions seem to converge to different coefficients depending on population size. Its almost as if the cost is not normalized by the population size and the effective regularization is C/n. Is that the case?

答:
I turns out different solvers enable different cost and gradient functions.

Here's what I found that different variants optimize:

```<code>sklearn.LR(solver=liblinear): L + lam*Rb
sklearn.LR(solver=others):    L + lam*R
statsmodels.GLM(bionomial):   L/n + lam*Rb
</code>```

where:

```<code>lam = 1/C
L = logloss
n = training sample size
R = square of L2 norm of feature weights
Rb =square of L2 norm of feature weights and intercept
</code>```

... its a little odd that sklearn doesn't normalize the loss by the sample size.

Body:
Why do different solvers result in different learned weights on simple problems in sklearn?
This doesn't smell like numerical instability -- it looks like the different solvers are designed to converge on different sets of weights.
What's going on?

It seems to be related to regularization, as the effect goes away with increasing C

%matplotlib inline
import time
import pandas as pd
import numpy as np
from sklearn.linear_model.logistic import LogisticRegression

def linear(X,b): return X.dot(b.T)
def sigmoid(X,b): return 1/(1+np.exp(-linear(X,b)))

b = np.array([1.,1.])

def mk(X,y,model):
    model.fit(X,y)
    t = time.clock()
    c = np.concatenate((model.coef_[0,:], model.intercept_[[0]]))
    return c, time.clock()-t

max_iter = 1000
tol=0.00000001
for C in [0.0001, 0.001, 0.1, 1., 10., 1000.]:
    for n in [200, 20000]:
        x = np.arange(-5., 5, 10./n)
        Xb = np.vstack([x, np.ones(len(x))]).T
        p = sigmoid(Xb,b)
        y = np.random.binomial(1, p)
        X = x.reshape((len(x), 1))
        print C, n
        for solver in ["liblinear", "newton-cg", "lbfgs", "sag"]:
            print "  {:>14}".format(solver), mk(X,y, LogisticRegression(C=C, solver=solver, penalty='l2', max_iter=max_iter, tol=tol))

The converged coefficients are below. The training data is generated with B=[1., 1.]

C      n
0.0001 200
       liblinear (array([ 0.01858615,  0.00219137]), 1.399999999995849e-05)
       newton-cg (array([ 0.01867489,  0.44809872]), 1.5000000000098268e-05)
           lbfgs (array([ 0.01867489,  0.44809872]), 1.5000000000098268e-05)
             sag (array([ 0.01867489,  0.448096  ]), 1.3000000000040757e-05)
0.0001 20000
       liblinear (array([ 0.49062599,  0.14814571]), 2.6999999999999247e-05)
       newton-cg (array([ 0.51257455,  0.59982733]), 2.6000000000081513e-05)
           lbfgs (array([ 0.51257471,  0.59982645]), 2.8999999999834714e-05)
             sag (array([ 0.51257455,  0.59982753]), 1.3000000000040757e-05)
0.001 200
       liblinear (array([ 0.15311436,  0.0154459 ]), 1.2999999999596668e-05)
       newton-cg (array([ 0.15456163,  0.34240309]), 1.3000000000040757e-05)
           lbfgs (array([ 0.15456166,  0.34240284]), 1.3000000000040757e-05)
             sag (array([ 0.15456163,  0.34240308]), 1.100000000020529e-05)
0.001 20000
       liblinear (array([ 0.81980482,  0.58214727]), 3.799999999998249e-05)
       newton-cg (array([ 0.86826695,  0.87335432]), 3.0999999999892225e-05)
           lbfgs (array([ 0.86826513,  0.87335497]), 3.2000000000032e-05)
             sag (array([ 0.86826695,  0.87335433]), 2.9999999999752447e-05)
0.1 200
       liblinear (array([ 0.80161404,  0.39606419]), 2.3999999999801958e-05)
       newton-cg (array([ 0.82243805,  0.57384594]), 2.9000000000056758e-05)
           lbfgs (array([ 0.82243822,  0.57384605]), 3.0000000000196536e-05)
             sag (array([ 0.82243805,  0.57384595]), 2.4999999999941735e-05)
0.1 20000
       liblinear (array([ 0.98022283,  0.97426356]), 3.799999999998249e-05)
       newton-cg (array([ 0.98180586,  0.98060186]), 2.3999999999801958e-05)
           lbfgs (array([ 0.98181404,  0.98060174]), 3.1000000000336314e-05)
             sag (array([ 0.98180586,  0.98060185]), 3.0999999999892225e-05)
1.0 200
       liblinear (array([ 0.77546388,  0.68083769]), 2.3999999999801958e-05)
       newton-cg (array([ 0.78084612,  0.71273566]), 1.1999999999900979e-05)
           lbfgs (array([ 0.7808462 ,  0.71273586]), 1.3000000000040757e-05)
             sag (array([ 0.78084612,  0.71273566]), 1.0000000000065512e-05)
1.0 20000
       liblinear (array([ 1.01286416,  1.01699803]), 3.1000000000336314e-05)
       newton-cg (array([ 1.013046  ,  1.01769302]), 1.6000000000016e-05)
           lbfgs (array([ 1.0130471 ,  1.01769538]), 3.0999999999892225e-05)
             sag (array([ 1.013046  ,  1.01769301]), 2.0999999999826713e-05)
10.0 200
       liblinear (array([ 1.19187232,  1.52139602]), 9.999999999621423e-06)
       newton-cg (array([ 1.19737431,  1.53737059]), 4.300000000023729e-05)
           lbfgs (array([ 1.19737519,  1.53736531]), 1.8999999999991246e-05)
             sag (array([ 1.19737429,  1.53737061]), 1.700000000059987e-05)
10.0 20000
       liblinear (array([ 0.9993963,  0.9748259]), 9.19999999995369e-05)
       newton-cg (array([ 0.9994126 ,  0.97489034]), 3.0999999999892225e-05)
           lbfgs (array([ 0.99941332,  0.97489202]), 3.10000000007804e-05)
             sag (array([ 0.99941261,  0.97489035]), 1.4000000000180535e-05)
1000.0 200
       liblinear (array([ 1.31759982,  1.48775989]), 9.000000000369823e-06)
       newton-cg (array([ 1.3176617 ,  1.48792683]), 1.4000000000180535e-05)
           lbfgs (array([ 1.31766183,  1.48792601]), 4.499999999918458e-05)
             sag (array([ 1.31766164,  1.48792671]), 1.100000000064938e-05)
1000.0 20000
       liblinear (array([ 0.99608584,  0.96883584]), 4.099999999951365e-05)
       newton-cg (array([ 0.99608601,  0.96883648]), 3.300000000017178e-05)
           lbfgs (array([ 0.99608665,  0.96883797]), 2.9999999999752447e-05)
             sag (array([ 0.99608603,  0.96883652]), 1.5000000000320313e-05)

And also, ... all the versions seem to converge to different coefficients depending on population size. Its almost as if the cost is not normalized by the population size and the effective regularization is C/n. Is that the case?

Body:
I turns out different solvers enable different cost and gradient functions.

Here's what I found that different variants optimize:

sklearn.LR(solver=liblinear): L + lam*Rb
sklearn.LR(solver=others):    L + lam*R
statsmodels.GLM(bionomial):   L/n + lam*Rb

where:

lam = 1/C
L = logloss
n = training sample size
R = square of L2 norm of feature weights
Rb =square of L2 norm of feature weights and intercept

... its a little odd that sklearn doesn't normalize the loss by the sample size.


问:
Corner detection in Image processing Opencv Python
I have an image of the box. I am trying to detect corners and mark those corner from circles. I am using the following code for this:

```<code>import cv2
import numpy as np

img_file = 'Image.jpg'
img = cv2.imread(img_file, cv2.IMREAD_COLOR)

imgDim = img.shape
dimA = imgDim[0]
dimB = imgDim[1]

# RGB to Gray scale conversion
img_gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
# Noise removal with iterative bilateral filter(removes noise while preserving edges)
noise_removal = cv2.bilateralFilter(img_gray,9,75,75)
# Thresholding the image
ret,thresh_image = cv2.threshold(noise_removal,220,255,cv2.THRESH_OTSU)
th = cv2.adaptiveThreshold(noise_removal, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

# Applying Canny Edge detection
canny_image = cv2.Canny(th,250,255)
canny_image = cv2.convertScaleAbs(canny_image)

# dilation to strengthen the edges
kernel = np.ones((3,3), np.uint8)
# Creating the kernel for dilation
dilated_image = cv2.dilate(canny_image,kernel,iterations=1)
np.set_printoptions(threshold=np.nan)

_, contours, h = cv2.findContours(dilated_image, 1, 2)
contours= sorted(contours, key = cv2.contourArea, reverse = True)[:1]

corners    = cv2.goodFeaturesToTrack(thresh_image,6,0.06,25)
corners    = np.float32(corners)

for item in corners:
    x,y    = item[0]
    cv2.circle(img,(x,y),10,255,-1)
cv2.namedWindow("Corners", cv2.WINDOW_NORMAL)
cv2.imshow("Corners",img)
cv2.waitKey()
</code>```

This code will return my image with pointing edges with circles but you can see that two edges (edges at the back of the box) are detected incorrectly. I know there is some problem in determining the corners because here we are just plotting the corners. Can anyone guide me where I am doing it wrong ? Thanks

答:
@Jeru Luke. Why not Harriscornering based on the result data from your step1?

I performed bilateral filtering on the grayscale image.

Found the edges using Canny edge detection.

Enhanced the edges using morphological dilation.

If you do that the painting on the corners would be neat and fit within the lines, right?

Body:
I have an image of the box. I am trying to detect corners and mark those corner from circles. I am using the following code for this:

import cv2
import numpy as np

img_file = 'Image.jpg'
img = cv2.imread(img_file, cv2.IMREAD_COLOR)

imgDim = img.shape
dimA = imgDim[0]
dimB = imgDim[1]

# RGB to Gray scale conversion
img_gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
# Noise removal with iterative bilateral filter(removes noise while preserving edges)
noise_removal = cv2.bilateralFilter(img_gray,9,75,75)
# Thresholding the image
ret,thresh_image = cv2.threshold(noise_removal,220,255,cv2.THRESH_OTSU)
th = cv2.adaptiveThreshold(noise_removal, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

# Applying Canny Edge detection
canny_image = cv2.Canny(th,250,255)
canny_image = cv2.convertScaleAbs(canny_image)

# dilation to strengthen the edges
kernel = np.ones((3,3), np.uint8)
# Creating the kernel for dilation
dilated_image = cv2.dilate(canny_image,kernel,iterations=1)
np.set_printoptions(threshold=np.nan)

_, contours, h = cv2.findContours(dilated_image, 1, 2)
contours= sorted(contours, key = cv2.contourArea, reverse = True)[:1]

corners    = cv2.goodFeaturesToTrack(thresh_image,6,0.06,25)
corners    = np.float32(corners)

for item in corners:
    x,y    = item[0]
    cv2.circle(img,(x,y),10,255,-1)
cv2.namedWindow("Corners", cv2.WINDOW_NORMAL)
cv2.imshow("Corners",img)
cv2.waitKey()

This code will return my image with pointing edges with circles but you can see that two edges (edges at the back of the box) are detected incorrectly. I know there is some problem in determining the corners because here we are just plotting the corners. Can anyone guide me where I am doing it wrong ? Thanks


问:
Lambda expression question
```<code>string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

/*
 This code produces the following output:

 {index=0, str=}
 {index=1, str=b}
 {index=2, str=ma}
 {index=3, str=ora}
 {index=4, str=pass}
 {index=5, str=grape}
*/
</code>```

Could somebody explain, how "index" is associated here as array index of the elements?

Say, I need a query that instead of first letter returns me the whole object (string in this case) + associated index.

答:
The index variable is simply a counter that increments from 0 as you iterate through the list of fruits. In this example there is a natural relationship between index and the position of fruit in fruits as you are iterating through fruits one element at a time.

I'm not sure about your question regarding access to 'the whole object'. You already have access to this:

```<code>var query = fruits.Select((fruit, index) => new { index, fruit });
</code>```

fruit refers to the current element in fruits as you iterate through it.

Title: Lambda expression question

Body:
string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

/*
 This code produces the following output:

 {index=0, str=}
 {index=1, str=b}
 {index=2, str=ma}
 {index=3, str=ora}
 {index=4, str=pass}
 {index=5, str=grape}
*/

Could somebody explain, how "index" is associated here as array index of the elements?

Say, I need a query that instead of first letter returns me the whole object (string in this case) + associated index.

Body:
The index variable is simply a counter that increments from 0 as you iterate through the list of fruits. In this example there is a natural relationship between index and the position of fruit in fruits as you are iterating through fruits one element at a time.

I'm not sure about your question regarding access to 'the whole object'. You already have access to this:

var query = fruits.Select((fruit, index) => new { index, fruit });

fruit refers to the current element in fruits as you iterate through it.


问:
dynamically allocated matrix gives seg fault when printed
this code allocates a matrix by means of a series of function calls, but when i print it, it return a segmentation fault error.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void mat_init(int** matx);
void pp_init(int** matx);
void p_init(int** matx);
void mat_fill(int** matx);
void mat_print(int** matx);

int main(void)
{
    srand((unsigned)time(NULL));
    int** matrix;
    mat_init(matrix);
    mat_print(matrix);
    return 0;
}

void mat_init(int** matx)
{
    pp_init(matx);
}

void pp_init(int** matx)
{

    matx=malloc(4*sizeof(int*));
    p_init(matx);
}

void p_init(int** matx)
{
    for(int i=0;i<4;i++)
    {
        *(matx+i)=malloc(4*sizeof(int));
    }
    mat_fill(matx);
}

void mat_fill(int** matx)
{
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<4;j++)
        {
            *(*(matx+i)+j)=rand()%5;
        }
    }
    //mat_print(matx);
}

void mat_print(int** matx)
{
    printf("The matrix is:\n");
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<4;j++)
        {
            printf("%1i|",*(*(matx+i)+j));
        }
        puts("");
    }
    puts("");
}
</code>```

note that this happens only if i print the matrix using mat_print() int the main, if i use it in the function mat_fill() it works correctly, showing that it's been properly initialized.
What's the problem?

答:
Essentially what you're doing is this:

```<code>void foo(int a);
{
  a = 6;
}

int main()
{
  int a = 3;
  foo(a);
  printf("a = %d\n", a);  // expecting this to print 6

  return 0;
}
</code>```

Everything in C is pass by value, so that means anytime a parameter is passed to a function, a local copy of it is made in that function, and its scope exists only in that function; there is no exception for pointers.  If I have this code instead:

```<code>void foo (int* ap2)
{
  // there are now 2 pointers in memory that point to the same thing (main's a), namely
  // ap2 on this stack frame and ap1 in the previous stack frame.
  *ap2 = 6;
  // ap2 is local to this function, but it _points_ to the same thing as
  // ap1, so when we dereference it, changes to _what it points to_ are seen
  // outside of this function. But once we return from this function, ap2
  // ceases to exist
}

int main()
{
  int a = 3;
  int* ap1 = &a;
  foo(ap1);
  printf("a = %d\n", a);  // now this prints 6

  return 0;
}
</code>```

If you want to manipulate main's matx in a function, then you need to pass a pointer to it and dereference it in that function in order to modify what it points to.

```<code>void foo (int*** matxp)
{
  // matxp now points to matx in main
  // dereference it here
  *matxp = malloc(4 * sizeof(int*));
}
int main()
{
  int** matx;
  foo(&matx);  // pass the address of matx here, which is an int*** type

  ....

  // don't forget to clean up everything
  return 0;
}
</code>```

But as I said in the comments, I've rarely/never seen 3 star pointers.  Instead you could just return the value

```<code>int** foo()
{
  matxp = malloc(4 * sizeof(int*));
  return matxp;  // this will return NULL if malloc failed
}

int main()
{
  int** matx = foo();

  ....
  // do work, cleanup
  return 0;
}
</code>```

Body:
this code allocates a matrix by means of a series of function calls, but when i print it, it return a segmentation fault error.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void mat_init(int** matx);
void pp_init(int** matx);
void p_init(int** matx);
void mat_fill(int** matx);
void mat_print(int** matx);

int main(void)
{
    srand((unsigned)time(NULL));
    int** matrix;
    mat_init(matrix);
    mat_print(matrix);
    return 0;
}

void mat_init(int** matx)
{
    pp_init(matx);
}

void pp_init(int** matx)
{

    matx=malloc(4*sizeof(int*));
    p_init(matx);
}

void p_init(int** matx)
{
    for(int i=0;i<4;i++)
    {
        *(matx+i)=malloc(4*sizeof(int));
    }
    mat_fill(matx);
}

void mat_fill(int** matx)
{
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<4;j++)
        {
            *(*(matx+i)+j)=rand()%5;
        }
    }
    //mat_print(matx);
}

void mat_print(int** matx)
{
    printf("The matrix is:\n");
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<4;j++)
        {
            printf("%1i|",*(*(matx+i)+j));
        }
        puts("");
    }
    puts("");
}

note that this happens only if i print the matrix using mat_print() int the main, if i use it in the function mat_fill() it works correctly, showing that it's been properly initialized.
What's the problem?

Body:
Essentially what you're doing is this:

void foo(int a);
{
  a = 6;
}

int main()
{
  int a = 3;
  foo(a);
  printf("a = %d\n", a);  // expecting this to print 6

  return 0;
}

Everything in C is pass by value, so that means anytime a parameter is passed to a function, a local copy of it is made in that function, and its scope exists only in that function; there is no exception for pointers.  If I have this code instead:

void foo (int* ap2)
{
  // there are now 2 pointers in memory that point to the same thing (main's a), namely
  // ap2 on this stack frame and ap1 in the previous stack frame.
  *ap2 = 6;
  // ap2 is local to this function, but it _points_ to the same thing as
  // ap1, so when we dereference it, changes to _what it points to_ are seen
  // outside of this function. But once we return from this function, ap2
  // ceases to exist
}

int main()
{
  int a = 3;
  int* ap1 = &a;
  foo(ap1);
  printf("a = %d\n", a);  // now this prints 6

  return 0;
}

If you want to manipulate main's matx in a function, then you need to pass a pointer to it and dereference it in that function in order to modify what it points to.

void foo (int*** matxp)
{
  // matxp now points to matx in main
  // dereference it here
  *matxp = malloc(4 * sizeof(int*));
}
int main()
{
  int** matx;
  foo(&matx);  // pass the address of matx here, which is an int*** type

  ....

  // don't forget to clean up everything
  return 0;
}

But as I said in the comments, I've rarely/never seen 3 star pointers.  Instead you could just return the value

int** foo()
{
  matxp = malloc(4 * sizeof(int*));
  return matxp;  // this will return NULL if malloc failed
}

int main()
{
  int** matx = foo();

  ....
  // do work, cleanup
  return 0;
}


问:
CSS div height fill remaing space and scroll if reach max height of screen
I have searched everywhere on the web for this but i couldn't find anyone that really fits me or even work. The answers that I found are very old and/or are not 100% what I am looking for so I hope if anyone can help me with this.

I use bootstrap 4 in my application so if it can be done with bootstrap then yeay but pure css is ok as well.

What I try to do is having 4 div side by side

example:

```<code><div class="row">
    <div class="col">
        <h1>Item 1</h1>
    </div>

    <div class="col">
        <h1>Item 2</h1>
    </div>
    <div class="col">
        <h1>Item 2</h1>
    </div>
    <div class="col">
        <h1>Item 2</h1>
    </div>
</div>
</code>```

This works because of bootstrap 4 but now I also want the div height will extend till the bottom of the screen  and if the content of that div is longer then the screen height, then it should scroll (inside the div).

I was thinking about flex boxes but I couldn't get it to work.

答:
You'll need to set the height of the element to 100%. If the parent is not 100% of the screen, then you'll need to set the parent height as well. If your HTML structure looks like this...

```<code><html>
<body>
  <div class="row">
      <div class="col"></div>
  </div>
</body>
</html>
</code>```

...then you'll need to set the height of all of those to 100%:

```<code>html, body, div.row, div.col {
    height:100%;
}
</code>```

To create the scrollbar, you can set overflow to scroll:

```<code>.col {
    overflow:scroll;
}
</code>```

Body:
I have searched everywhere on the web for this but i couldn't find anyone that really fits me or even work. The answers that I found are very old and/or are not 100% what I am looking for so I hope if anyone can help me with this.

I use bootstrap 4 in my application so if it can be done with bootstrap then yeay but pure css is ok as well.

What I try to do is having 4 div side by side

example:

Item 1

Item 2

Item 2

Item 2

This works because of bootstrap 4 but now I also want the div height will extend till the bottom of the screen  and if the content of that div is longer then the screen height, then it should scroll (inside the div).

I was thinking about flex boxes but I couldn't get it to work.

Body:
You'll need to set the height of the element to 100%. If the parent is not 100% of the screen, then you'll need to set the parent height as well. If your HTML structure looks like this...

<html>
<body>
  <div class="row">
      <div class="col"></div>
  </div>
</body>
</html>

...then you'll need to set the height of all of those to 100%:

html, body, div.row, div.col {
    height:100%;
}

To create the scrollbar, you can set overflow to scroll:

.col {
    overflow:scroll;
}


问:
How do i reference the currentPage title property in a custom component's js file?
I'm making a semi-custom list component in AEM that acts like a sidebar nav. I want to add an active class to a list item depending on if it is the link to the current page. I know how to reference currentPage.title in html and currentPage.getTitle() in JSP.

Am I missing an easy way to reference the currentPage title property in the component's separate clientlibs js file?

Not every page has a title tag or strict html elements to reference, so I'd like to use the aem properties before I go down that route.

答:
Clientlibs contains js code that is executed on browser, so you cannot access objects like currentPage that are only available on server during jsp/htl execution.

One way to achieve that would be to put those values in html element attributes in your HTL and later access them in js.

e.g. in sightly-

```<code><div id="titleHolder" data-page-title="${currentPage.title}">
</code>```

and to access it in js-

```<code>var pageTitle = $("#titleHolder").data("page-title");
</code>```

You can also put these in a JavaScript object instead of dom element attributes.

Body:
Clientlibs contains js code that is executed on browser, so you cannot access objects like currentPage that are only available on server during jsp/htl execution.

One way to achieve that would be to put those values in html element attributes in your HTL and later access them in js.

e.g. in sightly-

<div id="titleHolder" data-page-title="${currentPage.title}">

and to access it in js-

var pageTitle = $("#titleHolder").data("page-title");

You can also put these in a JavaScript object instead of dom element attributes.


问:
While loop to repeat actionPerformed of a JButton
I've got a JFrame with some JButtons. The "update" button (named JButton1) executes a number of queries which fill a form.
Now I'd like another JButton to be the "automatic update" (named JButton2), so I would like it to loop inside the JButton1ActionPerformed method, until JButton2 is no longer selected.
When I press JButton2 the window freezes.

Is my code right? Do you think I would need a stop button?

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

       long start = System.currentTimeMillis();
       if(jToggleButton2.isSelected()){
           start = System.currentTimeMillis();

            do{
                do{
                    jButton1ActionPerformed(evt);
                }
                while(System.currentTimeMillis()-start>3000);

            }
            while(jToggleButton2.isSelected());
       }

        if(jToggleButton2.isSelected()){
            jToggleButton2.setSelected(false);
        }

    }
</code>```

答:
Lets put aside that you should not crete Thread like I will show you (but use SwingWorker for example) you need to do something like this:

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

```<code>       if(jToggleButton2.isSelected()){
          new Thread(new Runnable(){

          public void run(){
                  long start = null;
                  do{
                         start = System.currentTimeMillis();
                        jButton1ActionPerformed(evt);
                   }while(jToggleButton2.isSelected() &&jSystem.currentTimeMillis()-start>3000)
          }
          }).start();

    }
</code>```

Im not focusing on if your code is valid or not, its just shows how to run something in background, so you will not freeze your GUI.

Body:
I've got a JFrame with some JButtons. The "update" button (named JButton1) executes a number of queries which fill a form.
Now I'd like another JButton to be the "automatic update" (named JButton2), so I would like it to loop inside the JButton1ActionPerformed method, until JButton2 is no longer selected.
When I press JButton2 the window freezes.

Is my code right? Do you think I would need a stop button?

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

       long start = System.currentTimeMillis();
       if(jToggleButton2.isSelected()){
           start = System.currentTimeMillis();

            do{
                do{
                    jButton1ActionPerformed(evt);
                }
                while(System.currentTimeMillis()-start>3000);

            }
            while(jToggleButton2.isSelected());
       }

        if(jToggleButton2.isSelected()){
            jToggleButton2.setSelected(false);
        }

    }

Body:
Lets put aside that you should not crete Thread like I will show you (but use SwingWorker for example) you need to do something like this:

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

       if(jToggleButton2.isSelected()){
          new Thread(new Runnable(){

          public void run(){
                  long start = null;
                  do{
                         start = System.currentTimeMillis();
                        jButton1ActionPerformed(evt);
                   }while(jToggleButton2.isSelected() &&jSystem.currentTimeMillis()-start>3000)
          }
          }).start();

    }

Im not focusing on if your code is valid or not, its just shows how to run something in background, so you will not freeze your GUI.