问:
Round JButton with icon; gets clicked when not directly pointer at; setting cursor to HAND_CURSOR works on area outside the icon
So, I have JFrame with JPanel on it. JPanel has two JToggleButtons. Each button is displayed as an icon of a round button. When the cursor hovers above a button it is supposed to turn into a hand.

```<code>public class UserInterface extends JFrame  {
        int width;
        int height;

        JPanel panel;
        public static void main(String[] args)  {
                run();
        }
        public UserInterface()  {
                setup();
        }

        private void setup()  {
            width=800;
            height=600;

            panel=new UserInterfacePanel();
            add(panel);

            setSize(width, height);
            setLocationRelativeTo(null);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        }

        public static void run()  {
                UserInterface gui=new UserInterface();
                gui.setVisible(true);
        }
}

class UserInterfacePanel extends JPanel {
            private JToggleButton startButton;
            private JToggleButton stopButton;

            public static void main(String[] args)  {

            }

            public UserInterfacePanel()  {
                setup();
            }

            private void setup()  {
                setLayout(new GridLayout(1,2));

                setupButtons();
                setupButtonsActions();
                add(startButton);
                add(stopButton);
            }

            private void setupButtons()  {

                    ImageIcon iconStartButton = new ImageIcon("C:\\Users\\parsecer\\Desktop\\imgs\\greenReleased.png");
                    ImageIcon iconStopButton=new ImageIcon("C:\\Users\\parsecer\\Desktop\\imgs\\redReleased.png");

                    startButton=new JToggleButton(iconStartButton);
                    stopButton=new JToggleButton(iconStopButton);

                    startButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
                    stopButton.setCursor(new Cursor(Cursor.HAND_CURSOR));

                    startButton.setHorizontalAlignment(JButton.CENTER);
                    stopButton.setHorizontalAlignment(JButton.CENTER);
                    startButton.setAlignmentX(CENTER_ALIGNMENT);
                    stopButton.setAlignmentX(CENTER_ALIGNMENT);
                    startButton.setAlignmentY(CENTER_ALIGNMENT);
                    stopButton.setAlignmentY(CENTER_ALIGNMENT);

                    setupButtonIcon(startButton);
                    setupButtonIcon(stopButton);

                    ImageIcon iconStartButtonPressed=new ImageIcon("C:\\Users\\parsecer\\Desktop\\imgs\\greenPressed.png");
                    startButton.setDisabledIcon(iconStartButton);
                    startButton.setPressedIcon(iconStartButtonPressed);
                    startButton.setSelectedIcon(iconStartButtonPressed);

                    ImageIcon iconStopButtonPressed=new ImageIcon("C:\\Users\\parsecer\\Desktop\\imgs\\redPressed.png");
                    stopButton.setDisabledIcon(iconStopButton);
                    stopButton.setPressedIcon(iconStopButtonPressed);
                    stopButton.setSelectedIcon(iconStopButtonPressed);

            }

             private void setupButtonIcon(JToggleButton button)  {
                   button.setBorder(BorderFactory.createEmptyBorder());
                   button.setBorderPainted(false);
                   button.setContentAreaFilled(false);
                   button.setFocusable(false);
                   button.setPreferredSize(new Dimension(80, 80));
                   button.setFocusPainted(false);
                   button.setOpaque(false);
            }
        }
</code>```

The problem is, the cursor changes into a hand way beyond the icon itself. The same goes for clicking the button - the button get pressed wherever I click vertically - given it's in the same column as the button or when I get relatively close to it horizontally.

I suppose the first problem might be linked to button image, but the background is deleted. Can the second be linked to the GridLayout?

答:
I would do something like this:
Define the shape of your buttons, presumably a circle/ellipse.
In your click- and motionlisteners check if the event occured inside of that shape. If so, do your thing.

Put into code it would go (for the motionlistener) like this:

```<code>Cursor handCursor = new Cursor(Cursor.HAND_CURSOR);
Cursor normalCursor = new Cursor(Cursor.DEFAULT_CURSOR);
// create your shape here
Shape shape = new Ellipse2D.Float(0, 0, 30, 30);
MouseMotionAdapter motionListener = new MouseMotionAdapter() {
        @Override
        public void mouseMoved(MouseEvent e) {
            super.mouseMoved(e);
            JToggleButton src = (JToggleButton) e.getSource();
            if (shape.contains(e.getPoint())) {
                src.setCursor(handCursor);
            } else {
                src.setCursor(normalCursor);
            }
        }
    };
startButton.addMouseMotionListener(motionListener);
stopButton.addMouseMotionListener(motionListener);
</code>```

Body:
So, I have JFrame with JPanel on it. JPanel has two JToggleButtons. Each button is displayed as an icon of a round button. When the cursor hovers above a button it is supposed to turn into a hand.

public class UserInterface extends JFrame  {
        int width;
        int height;

        JPanel panel;
        public static void main(String[] args)  {
                run();
        }
        public UserInterface()  {
                setup();
        }

        private void setup()  {
            width=800;
            height=600;

            panel=new UserInterfacePanel();
            add(panel);

            setSize(width, height);
            setLocationRelativeTo(null);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        }

        public static void run()  {
                UserInterface gui=new UserInterface();
                gui.setVisible(true);
        }
}

class UserInterfacePanel extends JPanel {
            private JToggleButton startButton;
            private JToggleButton stopButton;

            public static void main(String[] args)  {

            }

            public UserInterfacePanel()  {
                setup();
            }

            private void setup()  {
                setLayout(new GridLayout(1,2));

                setupButtons();
                setupButtonsActions();
                add(startButton);
                add(stopButton);
            }

            private void setupButtons()  {

                    ImageIcon iconStartButton = new ImageIcon("C:\\Users\\parsecer\\Desktop\\imgs\\greenReleased.png");
                    ImageIcon iconStopButton=new ImageIcon("C:\\Users\\parsecer\\Desktop\\imgs\\redReleased.png");

                    startButton=new JToggleButton(iconStartButton);
                    stopButton=new JToggleButton(iconStopButton);

                    startButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
                    stopButton.setCursor(new Cursor(Cursor.HAND_CURSOR));

                    startButton.setHorizontalAlignment(JButton.CENTER);
                    stopButton.setHorizontalAlignment(JButton.CENTER);
                    startButton.setAlignmentX(CENTER_ALIGNMENT);
                    stopButton.setAlignmentX(CENTER_ALIGNMENT);
                    startButton.setAlignmentY(CENTER_ALIGNMENT);
                    stopButton.setAlignmentY(CENTER_ALIGNMENT);

                    setupButtonIcon(startButton);
                    setupButtonIcon(stopButton);

                    ImageIcon iconStartButtonPressed=new ImageIcon("C:\\Users\\parsecer\\Desktop\\imgs\\greenPressed.png");
                    startButton.setDisabledIcon(iconStartButton);
                    startButton.setPressedIcon(iconStartButtonPressed);
                    startButton.setSelectedIcon(iconStartButtonPressed);

                    ImageIcon iconStopButtonPressed=new ImageIcon("C:\\Users\\parsecer\\Desktop\\imgs\\redPressed.png");
                    stopButton.setDisabledIcon(iconStopButton);
                    stopButton.setPressedIcon(iconStopButtonPressed);
                    stopButton.setSelectedIcon(iconStopButtonPressed);

            }

             private void setupButtonIcon(JToggleButton button)  {
                   button.setBorder(BorderFactory.createEmptyBorder());
                   button.setBorderPainted(false);
                   button.setContentAreaFilled(false);
                   button.setFocusable(false);
                   button.setPreferredSize(new Dimension(80, 80));
                   button.setFocusPainted(false);
                   button.setOpaque(false);
            }
        }

The problem is, the cursor changes into a hand way beyond the icon itself. The same goes for clicking the button - the button get pressed wherever I click vertically - given it's in the same column as the button or when I get relatively close to it horizontally.

I suppose the first problem might be linked to button image, but the background is deleted. Can the second be linked to the GridLayout?

Body:
I would do something like this:
Define the shape of your buttons, presumably a circle/ellipse.
In your click- and motionlisteners check if the event occured inside of that shape. If so, do your thing.

Put into code it would go (for the motionlistener) like this:

Cursor handCursor = new Cursor(Cursor.HAND_CURSOR);
Cursor normalCursor = new Cursor(Cursor.DEFAULT_CURSOR);
// create your shape here
Shape shape = new Ellipse2D.Float(0, 0, 30, 30);
MouseMotionAdapter motionListener = new MouseMotionAdapter() {
        @Override
        public void mouseMoved(MouseEvent e) {
            super.mouseMoved(e);
            JToggleButton src = (JToggleButton) e.getSource();
            if (shape.contains(e.getPoint())) {
                src.setCursor(handCursor);
            } else {
                src.setCursor(normalCursor);
            }
        }
    };
startButton.addMouseMotionListener(motionListener);
stopButton.addMouseMotionListener(motionListener);


来源: stackexchange

问:
Using python how do I manage windows on OSX
I am trying to manage windows using python.

Specifically I am trying to find a window that I have opened using selenium then have it focused and maximise it. I believe this is possible using a window manager as there are programs like qtile written in python.

I have read on the python documentation that there is something called pythonw.

https://docs.python.org/3/using/mac.html

I am using python 3.5 but I can upgrade if this is an easier option.

How do I use this on OSX?

Is there a library or are there any more resources on this subject?

I would like to learn how to use simple window management in python for osx.

Any help is appreciated.

答: You need a system level window manager for this</p>

ContentLicense: CC BY-SA 3.0


问:
C++ member initialization from derived class to base class
Let's see the following C++ codes.
Each inherited class has its member variables and initialization function.
These member variables are some different(almost same type) between inherited classes.
Is there any good way to move (or merge) this initialization into base class?</p>

```<code>class Base {
public:
   virtual init() = 0;
}
class A: public Base {
public:
   int a1;
   void init() { a1 = 0;}
}
class B: public Base {
public:
   int b1;
   void init() { b1 = 1;}
}
</code>```

答:
No. Base has no knowledge of A::a1 or B::b1. More importantly it should not have any knowledge of it's subclass members as this leads to a fundamental breakdown of the encapsulation you're trying to achieve in the first place.

The best you can do is have your Base class define a virtual method for initialisation and control when that method is called. It is up to each subclass to override the method and ensure that when initialisation is needed it is performed according to each subclass's respective requirements.

One thing to note is that if your initialisation is intended to be once-off for the lifetime of each object, the the correct place to do this is using constructors as per koizyd's answer.

On a related note, I'd like to point out that what you're asking is a variation on one of the most common OO design flaws I've seen in my career.

Using inheritance for code reuse not encapsulation.

Basically you're trying to push functionality into the base class (for reuse), and all this really achieves is making the Base class large, top-heavy and unmaintainable.

Body:
Let's see the following C++ codes.
Each inherited class has its member variables and initialization function.
These member variables are some different(almost same type) between inherited classes.
Is there any good way to move (or merge) this initialization into base class?

class Base {
public:
   virtual init() = 0;
}
class A: public Base {
public:
   int a1;
   void init() { a1 = 0;}
}
class B: public Base {
public:
   int b1;
   void init() { b1 = 1;}
}


问:
Trouble with removing TLS from Kubernetes Install/Cores
I'm trying to modify the coreos installer to remove TLS.  We've been using TLS in dev, but our production does not have TLS and we are trying to get in sync for dev/test/prod.  It's kubernetes 1.3.6.  I have no control or influence on getting prod to use TLS.

I've based my work off of this master node install script:  https://github.com/coreos/coreos-kubernetes/blob/v0.8.2/multi-node/generic/controller-install.sh

My modified script is here:  https://gist.github.com/pswenson/a687735ce9054c39aa56fe40d8bed70a

This question is concerning one master node install at this point... once I have the master working I'll take another crack at getting workers to work.

When I run the installer, the api server seems to work fine.  I can connect with kubectl get get nodes and pods.    I can curl $MASTER_IP:8080 fine. However, the dashboard doesn't work.

When I run journalctl -u kubelet -f on the master node I see this in the logs:

```<code>kubelet-wrapper[1994]: I0615 19:52:13.341824    1994 logs.go:41] http: TLS handshake error from $MASTER_IP:46922: tls: first record does not look like a TLS handshake
kubelet-wrapper[1994]: I0615 19:53:07.397110    1994 logs.go:41] http: TLS handshake error from $MASTER_IP:46966: tls: first record does not look like a TLS handshake
kubelet-wrapper[1994]: I0615 19:55:18.190503    1994 logs.go:41] http: TLS handshake error from $MASTER_IP:47054: tls: first record does not look like a TLS handshake
kubelet-wrapper[1994]: I0615 19:55:47.159931    1994 logs.go:41] http: TLS handshake error from 10.168.141.212:57342: tls: first record does not look like a TLS handshake
kubelet-wrapper[1994]: I0615 19:55:50.799724    1994 logs.go:41] http: TLS handshake error from 10.168.141.212:57394: tls: first record does not look like a TLS handshake
kubelet-wrapper[1994]: I0615 19:55:56.944580    1994 logs.go:41] http: TLS handshake error from 10.168.141.212:57471: tls: first record does not look like a TLS handshake
</code>```

I'm not sure what to make of the above... obviously kubelet still wants a TLS response.  I have no idea why.  And I'm not sure where these high ports are coming from.

When I try to get the logs via kubectl logs kube-proxy-$MASTER_IP --namespace=kube-system the response is

```<code>Error from server: Get http://$MASTER_IP:10250/containerLogs/kube-system/kube-proxy-96.118.242.147/kube-proxy: malformed HTTP response "\x15\x03\x01\x00\x02\x02"
</code>```

The HTTP response looks like an HTTPS/HTTP mismatch.

So it appears that there is a remnant of TLS left.  The API Server itself seems ok.  But other pieces such as the kublet are still making TLS requests?

Any insights would be greatly appreciated.

Thanks!

答:
I use a similar CoreOS script to deploy a v1.6.4 cluster on bare metal, but I implement even more aggressive TLS. My version is found here.

After reading my config and the latest documentation for kubelet, it doesn't seem possible to disable encryption on kubelet's port 10250.

The high-numbered ports are used by the control plane elements trying to talk to kubelet.

You said that the dashboard doesn't work, but do the other pods get successfully deployed?

Body:
I'm trying to modify the coreos installer to remove TLS.  We've been using TLS in dev, but our production does not have TLS and we are trying to get in sync for dev/test/prod.  It's kubernetes 1.3.6.  I have no control or influence on getting prod to use TLS.

I've based my work off of this master node install script:  https://github.com/coreos/coreos-kubernetes/blob/v0.8.2/multi-node/generic/controller-install.sh

My modified script is here:  https://gist.github.com/pswenson/a687735ce9054c39aa56fe40d8bed70a

This question is concerning one master node install at this point... once I have the master working I'll take another crack at getting workers to work.

When I run the installer, the api server seems to work fine.  I can connect with kubectl get get nodes and pods.    I can curl $MASTER_IP:8080 fine. However, the dashboard doesn't work.

When I run journalctl -u kubelet -f on the master node I see this in the logs:

kubelet-wrapper[1994]: I0615 19:52:13.341824    1994 logs.go:41] http: TLS handshake error from $MASTER_IP:46922: tls: first record does not look like a TLS handshake
kubelet-wrapper[1994]: I0615 19:53:07.397110    1994 logs.go:41] http: TLS handshake error from $MASTER_IP:46966: tls: first record does not look like a TLS handshake
kubelet-wrapper[1994]: I0615 19:55:18.190503    1994 logs.go:41] http: TLS handshake error from $MASTER_IP:47054: tls: first record does not look like a TLS handshake
kubelet-wrapper[1994]: I0615 19:55:47.159931    1994 logs.go:41] http: TLS handshake error from 10.168.141.212:57342: tls: first record does not look like a TLS handshake
kubelet-wrapper[1994]: I0615 19:55:50.799724    1994 logs.go:41] http: TLS handshake error from 10.168.141.212:57394: tls: first record does not look like a TLS handshake
kubelet-wrapper[1994]: I0615 19:55:56.944580    1994 logs.go:41] http: TLS handshake error from 10.168.141.212:57471: tls: first record does not look like a TLS handshake

I'm not sure what to make of the above... obviously kubelet still wants a TLS response.  I have no idea why.  And I'm not sure where these high ports are coming from.

When I try to get the logs via kubectl logs kube-proxy-$MASTER_IP --namespace=kube-system the response is

Error from server: Get http://$MASTER_IP:10250/containerLogs/kube-system/kube-proxy-96.118.242.147/kube-proxy: malformed HTTP response "\x15\x03\x01\x00\x02\x02"

The HTTP response looks like an HTTPS/HTTP mismatch.

So it appears that there is a remnant of TLS left.  The API Server itself seems ok.  But other pieces such as the kublet are still making TLS requests?

Any insights would be greatly appreciated.

Thanks!


问:
Remove clicking from element when opacity is at 0%
I have some content on a page that needs fading to 0% opacity rather than fading out and having the element being totally removed from the page, so the height and width of the element is still there but just inactive.

The problem is, the objects in that element are still clickable and still fire events.  Is there a special way of making them inactive or is it quite simply cursor:default; and preventDefault();?

答:
For me, it worked this way:</p>

```<code>.dropdown-menu {
    transition: all .32s ease;
    opacity: 0;
    display: block;
    visibility: hidden;
}

.show {
    visibility: visible;
    opacity: 1;
}
</code>```

Body:
For me, it worked this way:

.dropdown-menu {
    transition: all .32s ease;
    opacity: 0;
    display: block;
    visibility: hidden;
}

.show {
    visibility: visible;
    opacity: 1;
}


问:
What RGB format do tensorflow image ops expect?
How does a tensorflow image op (like nn.conv2d) expect image channels to be represented?

an array of 3 values ranging from [0-255]

an array of 3 values ranging from [0-1]

an array of 3 one-hot arrays of size 255

something else?

I'm trying to understand why my learning rate is so poor and I'm guessing it's because my input is malformed.

答: The conv2d accepts all the forms you mentioned here. It doesn't care what the input range should be, as long it is within the data-type range. But from a neural network training perspective its very important that the inputs are scaled properly. Not only with the input image, but even at each layer level we want the inputs to be scaled properly. And that why techniques like batch-normalization is present in almost all recent networks because it improves training by enabling better flow of gradients through the network. So scaling the images to [-1, +1] range (or zero mean unit variance) is important.


问:
DrawArc not Closing Edges
I made a control to display a circular progress-bar.
The control is shown below:

The control works with 2 ARC's:

One of them displays the current value (blue colored)

The other one displays the remaining value (red colored).

Both works with ProgressPen and DrawArc from Graphics library.

The problem is that, as you can see, the edges from the two arcs has some pixels between them and they really do not connect - although the angle is a double-number and set exactly to ensure 360 degrees.

In the image above, blue is 90.0 degrees and red is 270.0 degrees (the 25% within circle is just a test of font).

How to avoid this behaviour?

The routine I'm using to draw both arcs is:

```<code>Private Sub UserControl1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint

    e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
    e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
    e.Graphics.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality

    e.Graphics.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias

    e.Graphics.CompositingMode = Drawing2D.CompositingMode.SourceOver
    e.Graphics.CompositingQuality = Drawing2D.CompositingQuality.HighQuality

    Dim NewRect As Rectangle = New Rectangle(m_X + (20 / 2.0f), m_Y + (20 / 2.0f), m_Width - 20, m_Height - 20)

    DrawProgress(e.Graphics, NewRect, m_Valor)

End Sub

Private Sub DrawProgress(g As Graphics, rect As Rectangle, percentage As integer)

        Dim progressAngle As single = CSng(360.000F / 100.000F * percentage)
        Dim remainderAngle As single = 360.000F - progressAngle
        'create pens to use for the arcs

        Using progressPen As New Pen(m_Color, 20), remainderPen As New Pen(m_EmptyColor, 20)
            g.DrawArc(progressPen, rect, -90.000F, progressAngle)
            g.DrawArc(remainderPen, rect, progressAngle - 90.000F, remainderAngle)
            progressPen.Dispose
        End Using

End Sub
</code>```

What am I doing wrong?

How can I have a perfect circle without the blank-space between RED and BLUE bars?

NOTE: I see that if the bar-width is 1 or 2, the effect is not seen. But I need to have the control able to work even if the width is 20 or more.

Thanks for any help

答: I would just draw the blue color as a complete circle and superimpose the red arc over it.</p>

Title: DrawArc not Closing Edges

Body:
I made a control to display a circular progress-bar.
The control is shown below:

The control works with 2 ARC's:

One of them displays the current value (blue colored)

The other one displays the remaining value (red colored).

Both works with ProgressPen and DrawArc from Graphics library.

The problem is that, as you can see, the edges from the two arcs has some pixels between them and they really do not connect - although the angle is a double-number and set exactly to ensure 360 degrees.

In the image above, blue is 90.0 degrees and red is 270.0 degrees (the 25% within circle is just a test of font).

How to avoid this behaviour?

The routine I'm using to draw both arcs is:

Private Sub UserControl1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint

    e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
    e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
    e.Graphics.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality

    e.Graphics.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias

    e.Graphics.CompositingMode = Drawing2D.CompositingMode.SourceOver
    e.Graphics.CompositingQuality = Drawing2D.CompositingQuality.HighQuality

    Dim NewRect As Rectangle = New Rectangle(m_X + (20 / 2.0f), m_Y + (20 / 2.0f), m_Width - 20, m_Height - 20)

    DrawProgress(e.Graphics, NewRect, m_Valor)

End Sub

Private Sub DrawProgress(g As Graphics, rect As Rectangle, percentage As integer)

        Dim progressAngle As single = CSng(360.000F / 100.000F * percentage)
        Dim remainderAngle As single = 360.000F - progressAngle
        'create pens to use for the arcs

        Using progressPen As New Pen(m_Color, 20), remainderPen As New Pen(m_EmptyColor, 20)
            g.DrawArc(progressPen, rect, -90.000F, progressAngle)
            g.DrawArc(remainderPen, rect, progressAngle - 90.000F, remainderAngle)
            progressPen.Dispose
        End Using

End Sub

What am I doing wrong?

How can I have a perfect circle without the blank-space between RED and BLUE bars?

NOTE: I see that if the bar-width is 1 or 2, the effect is not seen. But I need to have the control able to work even if the width is 20 or more.

Thanks for any help


问:
python using requests with valid hostname
Trying to use requests to download a list of urls and catch the exception if it is a bad url. Here's my test code:

```<code>import requests
from requests.exceptions import ConnectionError

#goodurl
url = "http://www.google.com"

#badurl with good host
#url = "http://www.google.com/thereisnothing.jpg"

#url with bad host
#url = "http://somethingpotato.com"

print url
try:
    r = requests.get(url, allow_redirects=True)
    print "the url is good"
except ConnectionError,e:
    print e
    print "the url is bad"
</code>```

The problem is if I pass in url = "http://www.google.com" everything works as it should and as expected since it is a good url.

```<code>http://www.google.com
the url is good
</code>```

But if I pass in url = "http://www.google.com/thereisnothing.jpg"

I still get :

```<code>http://www.google.com/thereisnothing.jpg
the url is good
</code>```

So its almost like its not even looking at anything after the "/"

just to see if the error checking is working at all I passed a bad hostname: #url = "http://somethingpotato.com"

Which kicked back the error message I expected:

```<code>http://somethingpotato.com
HTTPConnectionPool(host='somethingpotato.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f1b6cd15b90>: Failed to establish a new connection: [Errno -2] Name or service not known',))
the url is bad
</code>```

What am I missing to make request capture a bad url not just a bad hostname?

Thanks

答:
requests do not create a throwable exception at a 404 response. Instead you need to filter them out be checking to see if the status is 'ok' (HTTP response 200)

```<code>import requests
from requests.exceptions import ConnectionError

#goodurl
url = "http://www.google.com/nothing"

#badurl with good host
#url = "http://www.google.com/thereisnothing.jpg"

#url with bad host
#url = "http://somethingpotato.com"

print url
try:
    r = requests.get(url, allow_redirects=True)
    if r.status_code == requests.codes.ok:
        print "the url is good"
    else:
        print "the url is bad"
except ConnectionError,e:
    print e
    print "the url is bad"
</code>```

EDIT:
import requests
    from requests.exceptions import ConnectionError

```<code>def printFailedUrl(url, response):
    if isinstance(response, ConnectionError):
        print "The url " + url + " failed to connect with the exception " + str(response)
    else:
        print "The url " + url + " produced the failed response code " + str(response.status_code)

def testUrl(url):
    try:
        r = requests.get(url, allow_redirects=True)
        if r.status_code == requests.codes.ok:
            print "the url is good"
        else:
            printFailedUrl(url, r)
    except ConnectionError,e:
        printFailedUrl(url, e)

def main():
    testUrl("http://www.google.com") #'Good' Url
    testUrl("http://www.google.com/doesnotexist.jpg") #'Bad' Url with 404 response
    testUrl("http://sdjgb") #'Bad' url with inaccessable url

main()
</code>```

In this case one function can handle both getting an exception or a request response passed into it. This way you can have separate responses for if the url returns some non 'good' (non-200) response vs an unusable url which throws an exception. Hope this has the information you need in it.

Body:
Trying to use requests to download a list of urls and catch the exception if it is a bad url. Here's my test code:

import requests
from requests.exceptions import ConnectionError

#goodurl
url = "http://www.google.com"

#badurl with good host
#url = "http://www.google.com/thereisnothing.jpg"

#url with bad host
#url = "http://somethingpotato.com"

print url
try:
    r = requests.get(url, allow_redirects=True)
    print "the url is good"
except ConnectionError,e:
    print e
    print "the url is bad"

The problem is if I pass in url = "http://www.google.com" everything works as it should and as expected since it is a good url.

http://www.google.com
the url is good

But if I pass in url = "http://www.google.com/thereisnothing.jpg"

I still get :

http://www.google.com/thereisnothing.jpg
the url is good

So its almost like its not even looking at anything after the "/"

just to see if the error checking is working at all I passed a bad hostname: #url = "http://somethingpotato.com"

Which kicked back the error message I expected:

http://somethingpotato.com
HTTPConnectionPool(host='somethingpotato.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f1b6cd15b90>: Failed to establish a new connection: [Errno -2] Name or service not known',))
the url is bad

What am I missing to make request capture a bad url not just a bad hostname?

Thanks

Body:
requests do not create a throwable exception at a 404 response. Instead you need to filter them out be checking to see if the status is 'ok' (HTTP response 200)

import requests
from requests.exceptions import ConnectionError

#goodurl
url = "http://www.google.com/nothing"

#badurl with good host
#url = "http://www.google.com/thereisnothing.jpg"

#url with bad host
#url = "http://somethingpotato.com"

print url
try:
    r = requests.get(url, allow_redirects=True)
    if r.status_code == requests.codes.ok:
        print "the url is good"
    else:
        print "the url is bad"
except ConnectionError,e:
    print e
    print "the url is bad"

EDIT:
import requests
    from requests.exceptions import ConnectionError

def printFailedUrl(url, response):
    if isinstance(response, ConnectionError):
        print "The url " + url + " failed to connect with the exception " + str(response)
    else:
        print "The url " + url + " produced the failed response code " + str(response.status_code)

def testUrl(url):
    try:
        r = requests.get(url, allow_redirects=True)
        if r.status_code == requests.codes.ok:
            print "the url is good"
        else:
            printFailedUrl(url, r)
    except ConnectionError,e:
        printFailedUrl(url, e)

def main():
    testUrl("http://www.google.com") #'Good' Url
    testUrl("http://www.google.com/doesnotexist.jpg") #'Bad' Url with 404 response
    testUrl("http://sdjgb") #'Bad' url with inaccessable url

main()

In this case one function can handle both getting an exception or a request response passed into it. This way you can have separate responses for if the url returns some non 'good' (non-200) response vs an unusable url which throws an exception. Hope this has the information you need in it.


问:
Optionally descend a nested struct
Assuming a class template Optional exists:

```<code>template <class T>
class Optional
{
public:
  ...
  bool isPresent(void) const {...}
  const T& value(void) {...} // throws if !isPresent()
  ...
};
</code>```

Also, some structs with nested Optional fields are defined:

```<code>struct A;
struct B;
struct C;
struct D;

struct A
{
   Optional<B> b1_;
   int i_;
};

struct B
{
   Optional<C> c1_;
   int j_;
};

struct C
{
   Optional<D> d1_;
   int k_;
};

struct D
{
   int l_;
   int m_;
   int n_;
};
</code>```

I'm looking for a programming idiom that provides the following behavior without the ugliness.

```<code>int get_l_OrDefault(const A& a, int def)
{
  if (!a.b_.isPresent()) return def;
  else if (!a.b_.value().c_.isPresent()) return def;
  else if (!a.b_.value().c_.value().d_.isPresent()) return def;
  else return a.b_.value().c_.value().d_.value().l_;
}
</code>```

Given an A a;, can I define something that takes some representation of the path to the non-optional leaf field and a default value?

```<code>getValueOrDefault(a.b.j_, 0);
getValueOrDefault(a.b.c.k_, 0);
... etc
</code>```

答:
This needs bind.

Bind takes optional of a and a function from a to b or optional of b, and returns an optional of b.

Suppose we had a named operator ->*bind* that understands poinnter to members.  Then

```<code>auto op_l = a->*bind*&A::b1_->*bind*&B::c1_->*bind*&C::d1_->*bind*&D::l_;
return value_or(op_l,def);
</code>```

(Where value or takes an optional and a default).

Title: Optionally descend a nested struct

Body:
Assuming a class template Optional exists:

template <class T>
class Optional
{
public:
  ...
  bool isPresent(void) const {...}
  const T& value(void) {...} // throws if !isPresent()
  ...
};

Also, some structs with nested Optional fields are defined:

struct A;
struct B;
struct C;
struct D;

struct A
{
   Optional b1_;
   int i_;
};

struct B
{
   Optional<C> c1_;
   int j_;
};

struct C
{
   Optional<D> d1_;
   int k_;
};

struct D
{
   int l_;
   int m_;
   int n_;
};

I'm looking for a programming idiom that provides the following behavior without the ugliness.

int get_l_OrDefault(const A& a, int def)
{
  if (!a.b_.isPresent()) return def;
  else if (!a.b_.value().c_.isPresent()) return def;
  else if (!a.b_.value().c_.value().d_.isPresent()) return def;
  else return a.b_.value().c_.value().d_.value().l_;
}

Given an A a;, can I define something that takes some representation of the path to the non-optional leaf field and a default value?

getValueOrDefault(a.b.j_, 0);
getValueOrDefault(a.b.c.k_, 0);
... etc

Body:
This needs bind.

Bind takes optional of a and a function from a to b or optional of b, and returns an optional of b.

Suppose we had a named operator ->*bind* that understands poinnter to members.  Then

auto op_l = a->*bind*&A::b1_->*bind*&B::c1_->*bind*&C::d1_->*bind*&D::l_;
return value_or(op_l,def);

(Where value or takes an optional and a default).


问:
Dynamic Object .NET
I am facing an interesting problem right now.
I know it is not that pretty but I have to cope with it anyway.

I am calling a webservice that returns (array of string) something like that (by index)

0 - Table Name ("Employees")

1 - List of all fields returned ("Id, Name, Birthdate")

2 - First field value ("1")

3 - Second field value ("Bobby")

4 - Third field value ("1970-01-01")

What I would like to accomplish is to create a object name after the index 0, having all the strings in the index 1 being all the properties and feed them with their proper value.

What would be the best way to accomplish this? I have started reading about the ExpandoObject but before going too far I would like to hear your take on this.

Regards

EDIT: I will have quite a few different tables to fetch the data from, that is what is causing me the problem.

答:
It depends on your use-case but I doubt that dynamic is the way to go here. I would just have a name-value collection like so:

```<code>class Result {
    Dictionary<string, string> values = new Dictionary<string, string>();
    public string this[string name] {
        get {
            return this.values[name];
        }
        set {
            this.values[name] = value;
        }
    }

    // some details
}
</code>```

Then you can populate the values from the webservice and query the values by saying

```<code>Result result = PopulateResultFromWebservice();
string id = result["Id"];
</code>```

etc. If you knew the types you could make this indexer of type object instead and parse the values to their appropriate type and store them as those typed objects.

The issue with dynamic is that if the names of the fields are an unknown, how are you possibly going to write code that utilizes those fields?

EDIT: I will have quite a few different tables to fetch the data from, that is what is causing me the problem.

Dude, name-value collection all day every day.

ContentLicense: CC BY-SA 2.5

Title: Dynamic Object .NET

Body:
It depends on your use-case but I doubt that dynamic is the way to go here. I would just have a name-value collection like so:

class Result {
    Dictionary<string, string> values = new Dictionary<string, string>();
    public string this[string name] {
        get {
            return this.values[name];
        }
        set {
            this.values[name] = value;
        }
    }

    // some details
}

Then you can populate the values from the webservice and query the values by saying

Result result = PopulateResultFromWebservice();
string id = result["Id"];

etc. If you knew the types you could make this indexer of type object instead and parse the values to their appropriate type and store them as those typed objects.

The issue with dynamic is that if the names of the fields are an unknown, how are you possibly going to write code that utilizes those fields?

EDIT: I will have quite a few different tables to fetch the data from, that is what is causing me the problem.

Dude, name-value collection all day every day.


问:
PHP exec() works in command line but not in web
I'm trying to use jarun's "googler" in a PHP script in order to search YouTube and find the URL of the first result. The command I'm executing is googler --np --json -C -n 1 -w youtube.com -x <name of youtube video>, and it works perfectly on my local machine. Here is my code:

```<code><?php
exec("googler --np --json -C -n 1 -w youtube.com -x thomas the dank engine", $results);
var_dump($results);
?>
</code>```

When I execute this in the command line, it works perfectly as it should, but when I do it via a web browser or a GET request, it does not work. I am aware that it is being executed as another user. In my case, it's the user www-data, so I gave that user full sudo permissions without a password, and did the following commands:

```<code>sudo -u pi googler --np --json -C -n 1 -w youtube.com -x thomas the dank engine
</code>```

as well as

```<code>su - pi -c 'googler --np --json -C -n 1 -w youtube.com -x thomas the dank engine'
</code>```

neither of these worked. Does it have to do with googler? What am I doing wrong?

When adding 2>&1 to the command, I get the following error message:

stdout encoding 'ascii' detected. googler requires utf-8 to work properly. The wrong encoding may be due to a non-UTF-8 locale or an improper PYTHONIOENCODING. (For the record, your locale language is and locale encoding is ; your PYTHONIOENCODING is not set.) Please set a UTF-8 locale (e.g., en_US.UTF-8) or set PYTHONIOENCODING to utf-8.

答:
Try putting:

```<code>putenv("PYTHONIOENCODING=utf-8");
</code>```

in the script before calling exec(). googler apparently requires the locale or this environment variable to be set.

Body:
I'm trying to use jarun's "googler" in a PHP script in order to search YouTube and find the URL of the first result. The command I'm executing is googler --np --json -C -n 1 -w youtube.com -x <name of youtube video>, and it works perfectly on my local machine. Here is my code:

<?php
exec("googler --np --json -C -n 1 -w youtube.com -x thomas the dank engine", $results);
var_dump($results);
?>

When I execute this in the command line, it works perfectly as it should, but when I do it via a web browser or a GET request, it does not work. I am aware that it is being executed as another user. In my case, it's the user www-data, so I gave that user full sudo permissions without a password, and did the following commands:

sudo -u pi googler --np --json -C -n 1 -w youtube.com -x thomas the dank engine

as well as

su - pi -c 'googler --np --json -C -n 1 -w youtube.com -x thomas the dank engine'

neither of these worked. Does it have to do with googler? What am I doing wrong?

When adding 2>&1 to the command, I get the following error message:

stdout encoding 'ascii' detected. googler requires utf-8 to work properly. The wrong encoding may be due to a non-UTF-8 locale or an improper PYTHONIOENCODING. (For the record, your locale language is and locale encoding is ; your PYTHONIOENCODING is not set.) Please set a UTF-8 locale (e.g., en_US.UTF-8) or set PYTHONIOENCODING to utf-8.

Body:
Try putting:

putenv("PYTHONIOENCODING=utf-8");

in the script before calling exec(). googler apparently requires the locale or this environment variable to be set.


问:
xamarin list view not populating
I am a little stuck here. I have a fragment that displays a list view. I want to load the items that make up that list view async. I do it like this:

```<code> public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // do other stuff here
        Task.Run(async () =>
        {
            _items = await GetItems();
            _listView.Adapter = new FooAdapter(Activity, _items);
        });

        return view;
    }
</code>```

But even though the items are getting populated the list view never is updated in the ui.  When I do the same thing with the SwipeRefreshLayout like so it works fine.

```<code>public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    _refresher = view.FindViewById<SwipeRefreshLayout>(Resource.Id.refresher);
    _refresher.Refresh += async delegate {
        _items = await GetItems(true);
        _refresher.Refreshing = false;
        _listView.Adapter = new RecipeListAdapter(Activity, _items);
    };
};
</code>```

so initially the view is empty, but when I pull down then the refresh view works and the list is populated and my list view shows up. I can't figure out why the first way doesn't work.

For reference my GetItems looks like this:

```<code>private async Task<List<Summary>> GetItems(bool clear = false)
{
        if (clear)
        {
            _items.Clear();
        }

       return await _service.GetItems(Token);
}
</code>```

答:
In your second example you are calling a delegate which using await to populate the _items variable before the adapter is set. But this is being bound to _refresher.Refresh

In your first example, you are running an Task asynchronously to get the data but you are returning the view before the data is retrieved. Unless something is going to refresh the data in that view how is it supposed to change?

Title: xamarin list view not populating

Body:
I am a little stuck here. I have a fragment that displays a list view. I want to load the items that make up that list view async. I do it like this:

 public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // do other stuff here
        Task.Run(async () =>
        {
            _items = await GetItems();
            _listView.Adapter = new FooAdapter(Activity, _items);
        });

        return view;
    }

But even though the items are getting populated the list view never is updated in the ui.  When I do the same thing with the SwipeRefreshLayout like so it works fine.

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    _refresher = view.FindViewById<SwipeRefreshLayout>(Resource.Id.refresher);
    _refresher.Refresh += async delegate {
        _items = await GetItems(true);
        _refresher.Refreshing = false;
        _listView.Adapter = new RecipeListAdapter(Activity, _items);
    };
};

so initially the view is empty, but when I pull down then the refresh view works and the list is populated and my list view shows up. I can't figure out why the first way doesn't work.

For reference my GetItems looks like this:

private async Task<List> GetItems(bool clear = false)
{
        if (clear)
        {
            _items.Clear();
        }

       return await _service.GetItems(Token);
}


问:
Responsive textboxes and a null 'Select' option in loaded list
I have two select boxes, one is for products and the other is for product type. what a appears in the product type list is dependent on what is selected in the product.  What i want to achieve is a null option at the top of the loaded list so that i can search just on the product. How would i go about this?

so far i have

```<code><select class="form-control" name="product_type" id="producttype">
  <option value=""></option>
</select>
</code>```

and JS/jquery

```<code>$('#product').on('change', function(e) {
  console.log(e);

  var prod_id = e.target.value;

  $.get('/ajax-subcat?prod_id=' + prod_id, function(data) {
    $('#producttype').empty();

    $.each(data, function(index, subcatObj) {
      $('#producttype').append('<option value="' + subcatObj.id + '">' + subcatObj.name + '</option>');
    });
  });
});
</code>```

答:
You can append that default options before filling your select in the each, something like this:</p>

```<code>$('#product').on('change', function(e) {
  console.log(e);

  var prod_id = e.target.value;

  $.get('/ajax-subcat?prod_id=' + prod_id, function(data) {
    $('#producttype').empty();

    $('#producttype').append('<option selected disabled>Select a product type</option>');

    $.each(data, function(index, subcatObj) {
      $('#producttype').append('<option value="' + subcatObj.id + '">' + subcatObj.name + '</option>');
    });
  });
});
</code>```

Body:
I have two select boxes, one is for products and the other is for product type. what a appears in the product type list is dependent on what is selected in the product.  What i want to achieve is a null option at the top of the loaded list so that i can search just on the product. How would i go about this?

so far i have

<select class="form-control" name="product_type" id="producttype">
  <option value=""></option>
</select>

and JS/jquery

$('#product').on('change', function(e) {
  console.log(e);

  var prod_id = e.target.value;

  $.get('/ajax-subcat?prod_id=' + prod_id, function(data) {
    $('#producttype').empty();

    $.each(data, function(index, subcatObj) {
      $('#producttype').append('<option value="' + subcatObj.id + '">' + subcatObj.name + '</option>');
    });
  });
});

Body:
You can append that default options before filling your select in the each, something like this:

$('#product').on('change', function(e) {
  console.log(e);

  var prod_id = e.target.value;

  $.get('/ajax-subcat?prod_id=' + prod_id, function(data) {
    $('#producttype').empty();

    $('#producttype').append('<option selected disabled>Select a product type</option>');

    $.each(data, function(index, subcatObj) {
      $('#producttype').append('<option value="' + subcatObj.id + '">' + subcatObj.name + '</option>');
    });
  });
});


问:
How many times a digit show up
Please help me. I don't get why the out put is in "occurs" is "30", instead of '3'.. It's as if I'm multiplying the answer with '10', but I'm not.. Maybe the answer to my problem is right in to my code but Can someone explain why and how? please..  Thank you very much in advance..

Please take a look at my code.

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

int main(){

    int arr[10] = {7, 7, 3, 2, 9, 8, 5, 1, 7, 9};
    int occur[10] = {NULL};
    int max = 0;
    int most;

    for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            occur[arr[j]]++;
            if(occur[arr[j]] > max)
            {
                max = occur[arr[j]];
                most = arr[j];
            }
        }
    }

    printf("Most frequent: %d\ occurs: %d\n", most, max);

    return 0;
}
</code>```

I am getting the correct answer in "Most Frequent". But the "occurs" is 30, instead of just 3 because 7 occurs 3 times.

答:
I will not argue that your O(n^2) operations algorithm is not the ideal way to do the task.

But moving one line of code will fix your code.

Your loop:

```<code>  for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            occur[arr[j]]++;
</code>```

Fix:

```<code>  for(int i = 0; i < 10; i++)
  {
      occur[arr[i]]++;
      for(int j = 0; j < 10; j++)
      {
</code>```

I'll let you figure out how you can do this in O(2n) operations or less...

Title: How many times a digit show up

Body:
Please help me. I don't get why the out put is in "occurs" is "30", instead of '3'.. It's as if I'm multiplying the answer with '10', but I'm not.. Maybe the answer to my problem is right in to my code but Can someone explain why and how? please..  Thank you very much in advance..

Please take a look at my code.

#include <stdio.h>

int main(){

    int arr[10] = {7, 7, 3, 2, 9, 8, 5, 1, 7, 9};
    int occur[10] = {NULL};
    int max = 0;
    int most;

    for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            occur[arr[j]]++;
            if(occur[arr[j]] > max)
            {
                max = occur[arr[j]];
                most = arr[j];
            }
        }
    }

    printf("Most frequent: %d\ occurs: %d\n", most, max);

    return 0;
}

I am getting the correct answer in "Most Frequent". But the "occurs" is 30, instead of just 3 because 7 occurs 3 times.

Body:
I will not argue that your O(n^2) operations algorithm is not the ideal way to do the task.

But moving one line of code will fix your code.

Your loop:

  for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            occur[arr[j]]++;

Fix:

  for(int i = 0; i < 10; i++)
  {
      occur[arr[i]]++;
      for(int j = 0; j < 10; j++)
      {

I'll let you figure out how you can do this in O(2n) operations or less...


问:
Echo mysql data using group_concat in PHP
This is my SQL Fiddle: SQL Fiddle

I am trying to echo this result using PHP. This is my expected result:

```<code>// Some Stuff Here

The Dark Knight Rises -  7.5
Batman Begins - 7.5
Iron Man - 7.3
The Lord of the Rings: The Return of the King - 8.1
etc...

// Some more Stuff here
</code>```

My PHP Code:

```<code>$stmt = $conn->prepare("SELECT tmdb_movies.movie_title
,GROUP_CONCAT(recommendations.recommendations_title  ORDER BY recommendations.recommendations_title) as recommendations_title
,GROUP_CONCAT(recommendations.recommendations_vote_average ORDER BY recommendations.recommendations_title) as recommendations_vote_average

FROM tmdb_movies

LEFT JOIN cast ON cast.cast_tmdb_id=tmdb_movies.tmdb_id
LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id

Where tmdb_movies.tmdb_id= 155

GROUP BY tmdb_movies.movie_title
 ");

     // Then fire it up
     $stmt->execute();
     // Pick up the result as an array
     $result = $stmt->fetchAll();

    // Now you run through this array in many ways, for example
     for($x=0, $n=count($result); $x < $n; $x++){
$recommendations_name_list = explode(',',$result[$x]["recommendations_title"]);
$recommendations_vote_average = explode(',',$result[$x]["recommendations_vote_average"]);
foreach( $recommendations_name_list as $index => $recommendations_title ) {
           echo'
    <p>'.$recommendations_title.'- '.$recommendations_vote_average[$index].'</p>';
    }
}
</code>```

Output of this code:

```<code>Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Inception- 8

Inception- 8

Inception- 8

Inception- 8

Inception- 8

Inception- 8

Inception- 8

Inception- 8

Inception- 8

Inception- 8

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Lord of th- 8
</code>```

But If i remove this line LEFT JOIN cast ON cast.cast_tmdb_id=tmdb_movies.tmdb_id
 then, my php code works fine.

Expected Result:

```<code>Batman Begins- 7.5

Captain America: The First Avenger- 6.6

Inception- 8

Iron Man- 7.3

Iron Man 2- 6.6

The Dark Knight Rises- 7.5

The Lord of the Rings: The Fellowship of the Ring- 8

The Lord of the Rings: The Return of the King- 8.1

The Lord of the Rings: The Two Towers- 7.9

The Matrix- 7.9
</code>```

答:
Many of the things you have in your post don't add up.  Your sql fiddle is missing the cast table entirely.    I have already commented that you are using GROUP_CONCAT inappropriately.  Your question does not have the complete information to help us understand your problem.

With that said, I believe I have surmised something close to what you actually want.  The main problem is that your GROUP BY should include both the original movie AND the recommended movies.  This will return you one row per group combination of movie/recommendation.  You can use GROUP_CONCAT to get the cast in one column.  Furthermore, I think that the cast data you want is actually the cast of the recommended movie, not the cast for the original movie.  You could get both together, but in the context of this query, it seems to me that you would want the cast of the recommended movie assembled into one column with GROUP_CONCAT.  As I commented to you, the problem is that you don't have the recommended movie's tmdb_id in the recommendation table.  Quite frankly that is a denormalized structure (storing the title rather than the id) and is relationally incorrect, wasteful and potentially confusing.

Why is this?

First off, the recommendation table has no Primary key and it needs one.   Title is not really a good candidate key either, because there are many movies that have the same title.  With your system there is no way to determine which film out of several that may have the same title.  Thus what you should have, is the tmdb_id as a foreign key, and at that point, you would not need (nor want) the title, because it could be gotten from the tmdb_movies table.  Your recommendation table is essentially a many-to-many table that relates movies to each other in a parent to child manner.  Aside from the foreign keys  (tmdb_id, recommended_tmdb_id) there doesn't actually need to be anything else in the table, since the values you currently have in there (title, avg rating) are denormalized values that are stored in the tmdb_movies table.

Now think ahead to the future, when perhaps you have thousands of movies, each of which may have 10 recommended movies related to it.  You will be wasting for any one movie, megabytes of database storage repeating the same title and average value that doesn't change.  Worse yet, averages are a snapshot in time.  Whenever the average rating needs to be recalculated, rather than updating a single value in one row of the tmdb_movie table, you now have to update every single row in recommendation where that movie was recommended to the original.  These are some of the costs of de-normalization.

Now to the specifics of GROUPing.

First to illustrate the way that GROUP BY works, I suggest you run these queries in your sqlfiddle or live db:

```<code>SELECT tmdb_movies.movie_title, recommendations.recommendations_title, recommendations.recommendations_vote_average
FROM tmdb_movies
LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id
GROUP BY tmdb_movies.tmdb_id, recommendations.recommendations_title
Where tmdb_movies.tmdb_id=1
</code>```

The key thing that is different from what you've been doing, is that I removed the useless GROUP_CONCAT statements, and did a GROUP BY on tmdb_movies.tmdb_id, recommendations.recommendations_title.

Ideally this would be by the id's but I covered that above, so for now we have to just use title.

As you can see, you get a GROUP for each unique combination of Movie & Recommended Movie.  It appears this is what you want.  Notice that I didn't used GROUP_CONCAT at all, and you get the average and the title, one per row.

Now let's assume you want to also join to the cast table.

Let's add that in:

```<code>SELECT tmdb_movies.movie_title, recommendations.recommendations_title, recommendations.recommendations_vote_average
FROM tmdb_movies
LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id
LEFT JOIN cast ON cast.recommendations_title=recommendations.recommendations_title
GROUP BY tmdb_movies.tmdb_id, recommendations.recommendations_title
</code>```

Notice that NOTHING CHANGES. You do not get extraneous rows, because the GROUP BY already reduces duplicates and leaves one row per group, even though we are now joining movie->recommendation->cast

So, now I will assume you want the cast in one column in the result.  Here is where GROUP_CONCAT actually comes in useful and seems appropriate:

```<code>SELECT tmdb_movies.movie_title, recommendations.recommendations_title, recommendations.recommendations_vote_average, GROUP_CONCAT(cast.name)
FROM tmdb_movies
LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id
LEFT JOIN cast ON cast.recommendations_title=recommendations.recommendations_title
GROUP BY tmdb_movies.tmdb_id, recommendations.recommendations_title
</code>```

Here's the sqlfiddle to this:

Body:
This is my SQL Fiddle: SQL Fiddle

I am trying to echo this result using PHP. This is my expected result:

// Some Stuff Here

The Dark Knight Rises -  7.5
Batman Begins - 7.5
Iron Man - 7.3
The Lord of the Rings: The Return of the King - 8.1
etc...

// Some more Stuff here

My PHP Code:

$stmt = $conn->prepare("SELECT tmdb_movies.movie_title
,GROUP_CONCAT(recommendations.recommendations_title  ORDER BY recommendations.recommendations_title) as recommendations_title
,GROUP_CONCAT(recommendations.recommendations_vote_average ORDER BY recommendations.recommendations_title) as recommendations_vote_average

FROM tmdb_movies

LEFT JOIN cast ON cast.cast_tmdb_id=tmdb_movies.tmdb_id
LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id

Where tmdb_movies.tmdb_id= 155

GROUP BY tmdb_movies.movie_title
 ");

     // Then fire it up
     $stmt->execute();
     // Pick up the result as an array
     $result = $stmt->fetchAll();

    // Now you run through this array in many ways, for example
     for($x=0, $n=count($result); $x < $n; $x++){
$recommendations_name_list = explode(',',$result[$x]["recommendations_title"]);
$recommendations_vote_average = explode(',',$result[$x]["recommendations_vote_average"]);
foreach( $recommendations_name_list as $index => $recommendations_title ) {
           echo'

'.$recommendations_title.'- '.$recommendations_vote_average[$index].'
';
    }
}

Output of this code:

Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Batman Begins- 7.5

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Captain America: The First Avenger- 6.6

Inception- 8

Inception- 8

Inception- 8

Inception- 8

Inception- 8

Inception- 8

Inception- 8

Inception- 8

Inception- 8

Inception- 8

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man- 7.3

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

Iron Man 2- 6.6

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Dark Knight Rises- 7.5

The Lord of th- 8

But If i remove this line LEFT JOIN cast ON cast.cast_tmdb_id=tmdb_movies.tmdb_id
 then, my php code works fine.

Expected Result:

Batman Begins- 7.5

Captain America: The First Avenger- 6.6

Inception- 8

Iron Man- 7.3

Iron Man 2- 6.6

The Dark Knight Rises- 7.5

The Lord of the Rings: The Fellowship of the Ring- 8

The Lord of the Rings: The Return of the King- 8.1

The Lord of the Rings: The Two Towers- 7.9

The Matrix- 7.9

Body:
Many of the things you have in your post don't add up.  Your sql fiddle is missing the cast table entirely.    I have already commented that you are using GROUP_CONCAT inappropriately.  Your question does not have the complete information to help us understand your problem.

With that said, I believe I have surmised something close to what you actually want.  The main problem is that your GROUP BY should include both the original movie AND the recommended movies.  This will return you one row per group combination of movie/recommendation.  You can use GROUP_CONCAT to get the cast in one column.  Furthermore, I think that the cast data you want is actually the cast of the recommended movie, not the cast for the original movie.  You could get both together, but in the context of this query, it seems to me that you would want the cast of the recommended movie assembled into one column with GROUP_CONCAT.  As I commented to you, the problem is that you don't have the recommended movie's tmdb_id in the recommendation table.  Quite frankly that is a denormalized structure (storing the title rather than the id) and is relationally incorrect, wasteful and potentially confusing.

Why is this?

First off, the recommendation table has no Primary key and it needs one.   Title is not really a good candidate key either, because there are many movies that have the same title.  With your system there is no way to determine which film out of several that may have the same title.  Thus what you should have, is the tmdb_id as a foreign key, and at that point, you would not need (nor want) the title, because it could be gotten from the tmdb_movies table.  Your recommendation table is essentially a many-to-many table that relates movies to each other in a parent to child manner.  Aside from the foreign keys  (tmdb_id, recommended_tmdb_id) there doesn't actually need to be anything else in the table, since the values you currently have in there (title, avg rating) are denormalized values that are stored in the tmdb_movies table.

Now think ahead to the future, when perhaps you have thousands of movies, each of which may have 10 recommended movies related to it.  You will be wasting for any one movie, megabytes of database storage repeating the same title and average value that doesn't change.  Worse yet, averages are a snapshot in time.  Whenever the average rating needs to be recalculated, rather than updating a single value in one row of the tmdb_movie table, you now have to update every single row in recommendation where that movie was recommended to the original.  These are some of the costs of de-normalization.

Now to the specifics of GROUPing.

First to illustrate the way that GROUP BY works, I suggest you run these queries in your sqlfiddle or live db:

SELECT tmdb_movies.movie_title, recommendations.recommendations_title, recommendations.recommendations_vote_average
FROM tmdb_movies
LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id
GROUP BY tmdb_movies.tmdb_id, recommendations.recommendations_title
Where tmdb_movies.tmdb_id=1

The key thing that is different from what you've been doing, is that I removed the useless GROUP_CONCAT statements, and did a GROUP BY on tmdb_movies.tmdb_id, recommendations.recommendations_title.

Ideally this would be by the id's but I covered that above, so for now we have to just use title.

As you can see, you get a GROUP for each unique combination of Movie & Recommended Movie.  It appears this is what you want.  Notice that I didn't used GROUP_CONCAT at all, and you get the average and the title, one per row.

Now let's assume you want to also join to the cast table.

Let's add that in:

SELECT tmdb_movies.movie_title, recommendations.recommendations_title, recommendations.recommendations_vote_average
FROM tmdb_movies
LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id
LEFT JOIN cast ON cast.recommendations_title=recommendations.recommendations_title
GROUP BY tmdb_movies.tmdb_id, recommendations.recommendations_title

Notice that NOTHING CHANGES. You do not get extraneous rows, because the GROUP BY already reduces duplicates and leaves one row per group, even though we are now joining movie->recommendation->cast

So, now I will assume you want the cast in one column in the result.  Here is where GROUP_CONCAT actually comes in useful and seems appropriate:

SELECT tmdb_movies.movie_title, recommendations.recommendations_title, recommendations.recommendations_vote_average, GROUP_CONCAT(cast.name)
FROM tmdb_movies
LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id
LEFT JOIN cast ON cast.recommendations_title=recommendations.recommendations_title
GROUP BY tmdb_movies.tmdb_id, recommendations.recommendations_title

Here's the sqlfiddle to this:


问:
Executable file generated using GCC under cygwin
I am using Cygwin and have GCC (version 4.3.4 20090804 (release) 1 ) installed as Cygwin package.

When I built C code using GCC under Cygwin shell, the generated executable output file is a executable of type (PE32 executable for MS Windows (console) Intel 80386 32-bit) and it can only be executed/run under Cygwin shell, not as standalone .exe on Windows shell/command prompt. If I try to run it standalone on Windows command prompt it gives an error window saying "The program can't run because cygwin.dll is missing from your computer".

How can one make this .exe standalone, which can be executed on a command prompt of any other system or even in my own system?

I thought GCC under Cygwin would build a Linux executable (ELF 32-bit LSB executable), but it's not so.  How can I use the gcc-cygwin combination to generate a *.out kind of Linux executable file?

Also, I cannot run a Linux executable generated on a Linux-gcc combination to execute under Cygwin.

Any pointers would be helpful.

答:
ad 1) There are currently three different mingw cross-compilers available for cygwin:

The old gcc3 -mno-cygwin is deprecated.

There are new mingw64 cross-compilers for 32 bit (mingw64-i686-gcc) and 64 bit windows targets (mingw64-x86_64-gcc).

There's no mingw-i686-gcc matching the official cygwin gcc4 compiler yet.

ad 2) There's no linux cross-compiler as cygwin package yet available. But people report success building such a cross-compiler by themselves.

ad 3) There's no cygwin cross-compiler as linux package available, but many mingw cross-compilers. Those mingw executables can also be executed under cygwin, though they cannot use cygwin features, just the simple windows runtime.

Correcting errors in others people posts:

-mswindows is not valid, -mwindows tells the linker to generate a GUI app without console.

-mno-cygwin is only valid for the old deprecated gcc3 compiler and is not supported anymore. Don't use it. With cygwin you should use ordinary host and target triples as with every other cross-compiler.


问:
Telerik RadGrid not showing any data in ASP.NET
I'm trying to make a really simple grid for some data on an ASP.NET page, but clearly I'm doing something wrong here. First of all, let me show you the grid I have on my clientside:

```<code><asp:Panel runat="server" ID="pnlDoorAccess" Visible="False">
    <asp:UpdatePanel runat="server" ID="upnlDoorAccess" UpdateMode="Conditional" ChildrenAsTriggers="false">
        <ContentTemplate>
            <tel:RadGrid runat="server" ID="gvDoorAccess" AllowSorting="false" AllowPaging="false"
                CssClass="col-sm-12 noPadding" MasterTableView-CssClass="table table-hover table-header-bg table-striped no-footer tableHeaderBorder"
                OnNeedDataSource="radDoorAccess_NeedDataSource" OnItemDataBound="radDoorAccess_ItemDataBound">
                <MasterTableView AutoGenerateColumns="false" TableLayout="Fixed" Caption="" FilterExpression="" AllowNaturalSort="false" DataKeyNames="Month" NoMasterRecordsText="No records to Display">
                    <Columns>
                        <tel:GridBoundColumn DataField="DoorName" HeaderText="Door Name" UniqueName="DoorName"></tel:GridBoundColumn>
                    </Columns>
                </MasterTableView>
            </tel:RadGrid>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Panel>
</code>```

So I wanna test the grid by only showing 1 column (DoorName), but so far it's not showing anything. Next is the server side code:

The DoorAccess property will fire up Controller.GetDoorAccess(CurrentUser.Id) when the Object Memorystore is empty and return me a DataTable object which I will return and eventually store into a DataSource property later on.

```<code>protected List<DoorAccess> DoorAccess
{
    get
    {
        if (omsDoorAccess.DataItem == null || omsDoorAccess.DataItem.GetType() != typeof(List<Option>)) omsDoorAccess.DataItem = Controller.GetDoorAccess(CurrentUser.Id);

        return (omsDoorAccess.DataItem as List<DoorAccess>);
    }
    set
    {
        omsDoorAccess.DataItem = value;
    }
}

protected void Page_Load(Object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        LoadTab_DoorAccess();
    }
}

private void LoadTab_DoorAccess()
{
    // Future implementation
    ReloadTab_DoorAccess();
}

private void ReloadTab_DoorAccess()
{
    gvDoorAccess.DataBind();

    upnlDoorAccess.DataBind();
    upnlDoorAccess.Update();
}

protected void radDoorAccess_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
    (sender as RadGrid).DataSource = DoorAccess;
    // DoorAccess holds 128 items
}

protected void radDoorAccess_ItemDataBound(object sender, GridItemEventArgs e)
{
    if (e.Item.ItemType != GridItemType.Item && e.Item.ItemType != GridItemType.AlternatingItem)
    {
       // Do stuff in the future
    }
}
</code>```

So what exactly is going on here? There is probably something obvious I'm missing, but right now I don't see it.

If this question makes no sense, could you show me a block of code that would help me create a simple grid?

答:
I see that you have AutoGeneratedColumns="False", a single column declared with the DataField="DoorName", and DataKeyName="Month".

When using Advanced DataBinding the datasource you are binding to must match the schema in the RadGrid unless you are using AutoGenerateColumns.

Without seeing your controller code, I think the issue is with the above Markup. There is no way for the grid to bind the single column with the DataField of "DoorName" to the DoorAccess object using the DataKeyName of "Month"(not knowing where "Month" is coming from). Make sure the DataKeyName property contains a unique value from the DoorAccess object and that the column DataField is equal to any property in the DoorAccess object.

ASPX:

```<code>    <telerik:RadGrid ID="RadGrid1" runat="server" OnNeedDataSource="RadGrid1_NeedDataSource">
         <MasterTableView AutoGenerateColumns="False" DataKeyNames="Id" CommandItemDisplay="Top">
            <Columns>
                <telerik:GridBoundColumn DataField="Id" UniqueName="MyId" HeaderText="My Id"></telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="Value" UniqueName="Value" HeaderText="My Value"></telerik:GridBoundColumn>
            </Columns>
        </MasterTableView>
    </telerik:RadGrid>
</code>```

C#:

```<code>public class MyDataModel
{
    public int Id { get; set; }
    public string Value { get; set; }
}

protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
   List<MyDataModel> datasource = new List<MyDataModel>();
   for (i = 0; i <= 10; i++) {
   datasource.Add(new MyDataModel {
        Id = i,
        Value = "Value" + i.ToString
    });
   }

   ((RadGrid)sender).DataSource = datasource;

}
</code>```

I would first try with autogenerated columns on to make sure valid data is being returned from the NeedDataSource event, and then make sure your DataKeyNames and DataFields are valid properties. Additionally as @Seano666 said, because your grid is in an UpdatePanel any errors the RadGrid throws due to incorrect formatting will be suppressed.

Body:
I'm trying to make a really simple grid for some data on an ASP.NET page, but clearly I'm doing something wrong here. First of all, let me show you the grid I have on my clientside:

<asp:Panel runat="server" ID="pnlDoorAccess" Visible="False">
    <asp:UpdatePanel runat="server" ID="upnlDoorAccess" UpdateMode="Conditional" ChildrenAsTriggers="false">
        <ContentTemplate>
            <tel:RadGrid runat="server" ID="gvDoorAccess" AllowSorting="false" AllowPaging="false"
                CssClass="col-sm-12 noPadding" MasterTableView-CssClass="table table-hover table-header-bg table-striped no-footer tableHeaderBorder"
                OnNeedDataSource="radDoorAccess_NeedDataSource" OnItemDataBound="radDoorAccess_ItemDataBound">
                <MasterTableView AutoGenerateColumns="false" TableLayout="Fixed" Caption="" FilterExpression="" AllowNaturalSort="false" DataKeyNames="Month" NoMasterRecordsText="No records to Display">
                    <Columns>
                        <tel:GridBoundColumn DataField="DoorName" HeaderText="Door Name" UniqueName="DoorName"></tel:GridBoundColumn>
                    </Columns>
                </MasterTableView>
            </tel:RadGrid>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Panel>

So I wanna test the grid by only showing 1 column (DoorName), but so far it's not showing anything. Next is the server side code:

The DoorAccess property will fire up Controller.GetDoorAccess(CurrentUser.Id) when the Object Memorystore is empty and return me a DataTable object which I will return and eventually store into a DataSource property later on.

protected List<DoorAccess> DoorAccess
{
    get
    {
        if (omsDoorAccess.DataItem == null || omsDoorAccess.DataItem.GetType() != typeof(List<Option>)) omsDoorAccess.DataItem = Controller.GetDoorAccess(CurrentUser.Id);

        return (omsDoorAccess.DataItem as List<DoorAccess>);
    }
    set
    {
        omsDoorAccess.DataItem = value;
    }
}

protected void Page_Load(Object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        LoadTab_DoorAccess();
    }
}

private void LoadTab_DoorAccess()
{
    // Future implementation
    ReloadTab_DoorAccess();
}

private void ReloadTab_DoorAccess()
{
    gvDoorAccess.DataBind();

    upnlDoorAccess.DataBind();
    upnlDoorAccess.Update();
}

protected void radDoorAccess_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
    (sender as RadGrid).DataSource = DoorAccess;
    // DoorAccess holds 128 items
}

protected void radDoorAccess_ItemDataBound(object sender, GridItemEventArgs e)
{
    if (e.Item.ItemType != GridItemType.Item && e.Item.ItemType != GridItemType.AlternatingItem)
    {
       // Do stuff in the future
    }
}

So what exactly is going on here? There is probably something obvious I'm missing, but right now I don't see it.

If this question makes no sense, could you show me a block of code that would help me create a simple grid?

Body:
I see that you have AutoGeneratedColumns="False", a single column declared with the DataField="DoorName", and DataKeyName="Month".

When using Advanced DataBinding the datasource you are binding to must match the schema in the RadGrid unless you are using AutoGenerateColumns.

Without seeing your controller code, I think the issue is with the above Markup. There is no way for the grid to bind the single column with the DataField of "DoorName" to the DoorAccess object using the DataKeyName of "Month"(not knowing where "Month" is coming from). Make sure the DataKeyName property contains a unique value from the DoorAccess object and that the column DataField is equal to any property in the DoorAccess object.

ASPX:

    <telerik:RadGrid ID="RadGrid1" runat="server" OnNeedDataSource="RadGrid1_NeedDataSource">
         <MasterTableView AutoGenerateColumns="False" DataKeyNames="Id" CommandItemDisplay="Top">
            <Columns>
                <telerik:GridBoundColumn DataField="Id" UniqueName="MyId" HeaderText="My Id"></telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="Value" UniqueName="Value" HeaderText="My Value"></telerik:GridBoundColumn>
            </Columns>
        </MasterTableView>
    </telerik:RadGrid>

C#:

public class MyDataModel
{
    public int Id { get; set; }
    public string Value { get; set; }
}

protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
   List<MyDataModel> datasource = new List<MyDataModel>();
   for (i = 0; i <= 10; i++) {
   datasource.Add(new MyDataModel {
        Id = i,
        Value = "Value" + i.ToString
    });
   }

   ((RadGrid)sender).DataSource = datasource;

}

I would first try with autogenerated columns on to make sure valid data is being returned from the NeedDataSource event, and then make sure your DataKeyNames and DataFields are valid properties. Additionally as @Seano666 said, because your grid is in an UpdatePanel any errors the RadGrid throws due to incorrect formatting will be suppressed.


问:
What's the difference between using a variable or %s in Python string formatting?
What is the difference between defining a variable and using it in a string and putting %s in a string and passing in the value after?

```<code>site = "Stackoverflow"
site + " is great!"

"%s is great!" % "Stackoverflow"
</code>```

Printing either of these gives the same result so when is it better to use one over the other?

答:
If you want to keep certain string constants in the same file, or on the top most of the file, you can declare the string with the placeholders as constants, then replace the placeholders with actual variable at run time through the % syntax.

This also allows greater re-usability.
Eg. you can store a single constant "%s is %s years old".

Using this syntax might also make the string more readable.

Body:
What is the difference between defining a variable and using it in a string and putting %s in a string and passing in the value after?

site = "Stackoverflow"
site + " is great!"

"%s is great!" % "Stackoverflow"

Printing either of these gives the same result so when is it better to use one over the other?


问:
Drop down List from Viewbag not following selected property
I have a dropdownList that will be populated by a viewbag carrying a List values containing "Text" and "Value" property that is set by a loop.

```<code>      List<SelectListItem> year = new List<SelectListItem>();

        for (var i = 1990; i <= DateTime.Now.Year; i++)
        {
            year.Add(new SelectListItem
            {
                Text = i.ToString(),
                Value = i.ToString()
            });
        }

       ViewBag.Year = year;
</code>```

And in my view:

```<code>@Html.DropDownListFor(model => model.Year, new SelectList(ViewBag.Year, "Value", "Text", Model.Birthday.Year), htmlAttributes: new { @class = "form-control", style = "width: 80px" })
</code>```

Nothing happens.

答:
I used script instead

    $('#Year option')
     .removeAttr('selected')
     .filter('[value=@Model.Birthday.Year]')
         .attr('selected', true)```

Body:
I have a dropdownList that will be populated by a viewbag carrying a List values containing "Text" and "Value" property that is set by a loop.

      List<SelectListItem> year = new List<SelectListItem>();

        for (var i = 1990; i <= DateTime.Now.Year; i++)
        {
            year.Add(new SelectListItem
            {
                Text = i.ToString(),
                Value = i.ToString()
            });
        }

       ViewBag.Year = year;

And in my view:

@Html.DropDownListFor(model => model.Year, new SelectList(ViewBag.Year, "Value", "Text", Model.Birthday.Year), htmlAttributes: new { @class = "form-control", style = "width: 80px" })

Nothing happens.


问:
R:Save output for assigned variable in the nested for loop as a matrix
I have a nested for loop using two matrices M1 and M2 and I was able to get the output I want when I print it. As I have assigned another variable inside the for loop called 'y' to get my output, I'm not sure how I could save the final output in a matrix. These are my codes,

```<code>A<-c('a','a','a','b','b','b','c','c','c')
B<-c('a','b','c','a','b','c','a','b','c')
C<-c(0,1,2,1,0,3,2,3,0)
D<-data.frame(A,B,C)

library("reshape2")
M1<-acast(D, list(names(D)[1], names(D)[2]))
M2<-matrix(c(1000,800,500),nrow=3,ncol=1)

  for(i in 1:3)
  {
   for(j in 1:3)
   {
    y=0
     for(k in 1:3)
     {
      if(M1[i,k]<M1[i,j])
      {
       y=y+M2[k,1]
      }
     }

     y=y-M2[i,1]
      if(y<0)
      {
        print(0)
      }
      else
      print(y)
    }
   }
</code>```

I tried to define the output variable upfront and then assign to it.

```<code>  output<-matrix(0,9,1)

  for(i in 1:3)
  {
   for(j in 1:3)
   {
    y=0
     for(k in 1:3)
     {
      if(M1[i,k]<M1[i,j])
      {
       y=y+M2[k,1]
      }
     }

     y=y-M2[i,1]
      if(y<0)
      {
        print(0)
      }
      else
      output[y]<-y
    }
   }

  output
</code>```

When I assign like this, I get multiple NA values, zeros and some of the output values.

I'm new to for loop. Any help will be much appreciated.Thanks!

答:
I was able to get the matrix I wanted by the below code</p>

```<code>output<-matrix(0,9,1)

for(i in 1:3)
{
 for(j in 1:3)
 {
  y=0
  for(k in 1:3)
  {
   if(M1[i,k]<M1[i,j])
   {
    y=y+M2[k,1]
   }
  }

   y=y-M2[i,1]
   if(y<0)
   {
    output[j+(3*(i-1)),1]<-0
   }
   else
    output[j+(3*(i-1)),1]<-y
  }
 }

View(output)
</code>```

Body:
I have a nested for loop using two matrices M1 and M2 and I was able to get the output I want when I print it. As I have assigned another variable inside the for loop called 'y' to get my output, I'm not sure how I could save the final output in a matrix. These are my codes,

A<-c('a','a','a','b','b','b','c','c','c')
B<-c('a','b','c','a','b','c','a','b','c')
C<-c(0,1,2,1,0,3,2,3,0)
D<-data.frame(A,B,C)

library("reshape2")
M1<-acast(D, list(names(D)[1], names(D)[2]))
M2<-matrix(c(1000,800,500),nrow=3,ncol=1)

  for(i in 1:3)
  {
   for(j in 1:3)
   {
    y=0
     for(k in 1:3)
     {
      if(M1[i,k]<M1[i,j])
      {
       y=y+M2[k,1]
      }
     }

     y=y-M2[i,1]
      if(y<0)
      {
        print(0)
      }
      else
      print(y)
    }
   }

I tried to define the output variable upfront and then assign to it.

  output<-matrix(0,9,1)

  for(i in 1:3)
  {
   for(j in 1:3)
   {
    y=0
     for(k in 1:3)
     {
      if(M1[i,k]<M1[i,j])
      {
       y=y+M2[k,1]
      }
     }

     y=y-M2[i,1]
      if(y<0)
      {
        print(0)
      }
      else
      output[y]<-y
    }
   }

  output

When I assign like this, I get multiple NA values, zeros and some of the output values.

I'm new to for loop. Any help will be much appreciated.Thanks!

Body:
I was able to get the matrix I wanted by the below code

output<-matrix(0,9,1)

for(i in 1:3)
{
 for(j in 1:3)
 {
  y=0
  for(k in 1:3)
  {
   if(M1[i,k]<M1[i,j])
   {
    y=y+M2[k,1]
   }
  }

   y=y-M2[i,1]
   if(y<0)
   {
    output[j+(3*(i-1)),1]<-0
   }
   else
    output[j+(3*(i-1)),1]<-y
  }
 }

View(output)


问:
How to convert binary string value to decimal
How to convert a binary String such as

```<code>String c = "110010"; // as binary
</code>```

to the value in decimal in Java? (expected result in the example is 50)

答:
Have to think about the decimal precision, so you must to limit the bitstring length. Anyway, using BigDecimal is a good choice.</p>

```<code>public BigDecimal bitStringToBigDecimal(String bitStr){

    BigDecimal sum = new BigDecimal("0");
    BigDecimal base = new BigDecimal(2);
    BigDecimal temp;
    for(int i=0;i<bitStr.length();i++){
        if(bitStr.charAt(i)== '1'){
            int exponent= bitStr.length()-1-i;
            temp=base.pow(exponent);
            sum=sum.add(temp);
        }

    }
    return sum;
}
</code>```

Body:
How to convert a binary String such as

String c = "110010"; // as binary

to the value in decimal in Java? (expected result in the example is 50)

Body:
Have to think about the decimal precision, so you must to limit the bitstring length. Anyway, using BigDecimal is a good choice.

public BigDecimal bitStringToBigDecimal(String bitStr){

    BigDecimal sum = new BigDecimal("0");
    BigDecimal base = new BigDecimal(2);
    BigDecimal temp;
    for(int i=0;i<bitStr.length();i++){
        if(bitStr.charAt(i)== '1'){
            int exponent= bitStr.length()-1-i;
            temp=base.pow(exponent);
            sum=sum.add(temp);
        }

    }
    return sum;
}


问:
dbConnect- Does cleaning data in R change data values in the real database
I am doing research on MySQL data. I used the dbConnect function to connect to the database and used dbReadTable to read a table.

My question is: if I start cleaning data to make it tidy using tidyr and dplyr, etc, will this change the data from the database (data that is stored in mySQL and was collected by researcher)

Or does cleaning data in R only change the data called upon in R and have NO EFFECT ON THE database.

I need a definitive, well-backed, and professional answer as the data I'm dealing with is pretty important and valuable.

答:
Given a database connection, you can definitely modify data in the database by using any of the keywords such as INSERT, UPDATE, DELETE depending on the role of the database user;

One safe way to avoid any modification of the database is ask the database administrator (I assume you are not the one) to create a user that has only read access to it, and then connect the database using this specific user. Then you would be safe to do analysis without unintentionally injecting anything into your database because the database won't allow you to do so;

But most importantly consult with the database administrator before taking next step, this answer is just for giving a clue on how to do this safely from my personal perspective. No responsibility taken for the next move you made.


问:
How to send multiple requests via Postman
I know we can send a json object via Postman as a POST request. However, I wish to send multiple such json Objects(hundreds) consecutively via. Postman.

Is there some way I can achieve that? I am stuck and will highly appreciate some solutions.

TIA:)

答:
So I ended up sending the json data via. a java code through POST requests.
Since I needed this only for load testing, I didn't care much about the code efficiency here. Might be useful for someone</p>

```<code>String line;
JSONParser jsonParser = new JSONParser();
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
while((line = br.readLine()) != null) {
            JSONObject jsonObject = (JSONObject) jsonParser.parse(line);
            HttpClient httpClient = HttpClientBuilder.create().build();
            try {
                HttpPost request = new HttpPost("http://url");
                StringEntity params = new StringEntity(jsonObject.toString());
                request.addHeader("content-type", "application/json");
                request.setEntity(params);
                HttpResponse response = httpClient.execute(request);.
            } catch (Exception ex) {
                // handle exception here
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
}
</code>```

Body:
So I ended up sending the json data via. a java code through POST requests.
Since I needed this only for load testing, I didn't care much about the code efficiency here. Might be useful for someone

String line;
JSONParser jsonParser = new JSONParser();
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
while((line = br.readLine()) != null) {
            JSONObject jsonObject = (JSONObject) jsonParser.parse(line);
            HttpClient httpClient = HttpClientBuilder.create().build();
            try {
                HttpPost request = new HttpPost("http://url");
                StringEntity params = new StringEntity(jsonObject.toString());
                request.addHeader("content-type", "application/json");
                request.setEntity(params);
                HttpResponse response = httpClient.execute(request);.
            } catch (Exception ex) {
                // handle exception here
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
}


问:
Get mean of specifics variable depending on another variable
I have a dataframe where I have different month, I want to do a mean of each row between the month of begining (in the begin variable) and the end month (in the end variable)

```<code>nom <- letters[1:5]
pseudo <- paste(nom, 21:25, sep = "")
janvier <- c(0, 1, 1, 1, 0)
fevrier <- c(1, 1, 1, 1, 1)
mars <- c(0, 0, 0, 1, 1)
avril <- c(1, 1, 1, 0, 1)
mai <- c(1, 0, 1, 1, 1)
juin <- c(1, 1, 0, 1, 0)

df <- data.frame(nom =nom, pseudo = pseudo, janvier = janvier,
                 fevrier = fevrier, mars = mars, avril = avril,
                 mai = mai, juin = juin)

dfm <- as.matrix(df[, -c(1, 2)])
my_matrix <- matrix(nrow = 10, ncol = 6)

my_matrix <- matrix("no info", nrow = 5, ncol = 2)
colnames(my_matrix) <- c("begin", "end")

for(i in 1:dim(dfm)[1]){
  for(j in 1:(dim(dfm)[2]-2)){
    if(dfm[i, j] + dfm[i, j+1] + dfm[i, j+2] == 3){
      my_matrix[i, 1] <- colnames(dfm)[j]
      my_matrix[i, 2] <- colnames(dfm)[j+2]
      break
    }
  }
}

output <- cbind(df, my_matrix)
output %>%
  filter(begin != "no info") -> output
</code>```

I tried do do it with a vectorized method, something like :

output$mean <- rowMeans(output[, output$begin:output$end])

I also tried this but not seems to recognize my begin variable :

```<code>for(i in seq_len(nrow(output))){
  for(j in seq_len(ncol(output))){
    output$mean[i, j] <- rowMeans(as.character(begin[i, j]):as.character(end[i, j]))
  }
}
</code>```

I dont want to use a loop if possible just with dplyr package, thanks for help

EDIT : I dont want to group_by, my question is a little bit complicated because I have to do means of row between the variables stored in begin and end variables

答:
If I'm understanding correctly, you'll want to switch everything to long format. Then you can join, filter, group, and average:</p>

```<code>## long format
library(reshape2)
df_long = melt(dfm)
names(df_long) = c("id", "month", "value")
id_key = as.data.frame(my_matrix)
id_key$id = 1:nrow(id_key)

## turn the months into a factor with the correct order
month_levs = c("janvier", "fevrier", "mars", "avril", "mai", "juin")

id_key = mutate(id_key, begin = factor(begin, levels = month_levs),
                end = factor(end, levels = month_levs))
df_long = mutate(df_long, month = factor(month, levels = month_levs))

## calculate results
results = df_long %>% left_join(id_key) %>%
    group_by(id) %>%
    filter(between(as.numeric(month), as.numeric(begin), as.numeric(end))) %>%
    summarize(mean = mean(value))
results
## A tibble: 3 x 2
#      id  mean
#   <int> <dbl>
# 1     1     1
# 2     4     1
# 3     5     1
</code>```

Body:
I have a dataframe where I have different month, I want to do a mean of each row between the month of begining (in the begin variable) and the end month (in the end variable)

nom <- letters[1:5]
pseudo <- paste(nom, 21:25, sep = "")
janvier <- c(0, 1, 1, 1, 0)
fevrier <- c(1, 1, 1, 1, 1)
mars <- c(0, 0, 0, 1, 1)
avril <- c(1, 1, 1, 0, 1)
mai <- c(1, 0, 1, 1, 1)
juin <- c(1, 1, 0, 1, 0)

df <- data.frame(nom =nom, pseudo = pseudo, janvier = janvier,
                 fevrier = fevrier, mars = mars, avril = avril,
                 mai = mai, juin = juin)

dfm <- as.matrix(df[, -c(1, 2)])
my_matrix <- matrix(nrow = 10, ncol = 6)

my_matrix <- matrix("no info", nrow = 5, ncol = 2)
colnames(my_matrix) <- c("begin", "end")

for(i in 1:dim(dfm)[1]){
  for(j in 1:(dim(dfm)[2]-2)){
    if(dfm[i, j] + dfm[i, j+1] + dfm[i, j+2] == 3){
      my_matrix[i, 1] <- colnames(dfm)[j]
      my_matrix[i, 2] <- colnames(dfm)[j+2]
      break
    }
  }
}

output <- cbind(df, my_matrix)
output %>%
  filter(begin != "no info") -> output

I tried do do it with a vectorized method, something like :

output$mean <- rowMeans(output[, output$begin:output$end])

I also tried this but not seems to recognize my begin variable :

for(i in seq_len(nrow(output))){
  for(j in seq_len(ncol(output))){
    output$mean[i, j] <- rowMeans(as.character(begin[i, j]):as.character(end[i, j]))
  }
}

I dont want to use a loop if possible just with dplyr package, thanks for help

EDIT : I dont want to group_by, my question is a little bit complicated because I have to do means of row between the variables stored in begin and end variables

Body:
If I'm understanding correctly, you'll want to switch everything to long format. Then you can join, filter, group, and average:

## long format
library(reshape2)
df_long = melt(dfm)
names(df_long) = c("id", "month", "value")
id_key = as.data.frame(my_matrix)
id_key$id = 1:nrow(id_key)

## turn the months into a factor with the correct order
month_levs = c("janvier", "fevrier", "mars", "avril", "mai", "juin")

id_key = mutate(id_key, begin = factor(begin, levels = month_levs),
                end = factor(end, levels = month_levs))
df_long = mutate(df_long, month = factor(month, levels = month_levs))

## calculate results
results = df_long %>% left_join(id_key) %>%
    group_by(id) %>%
    filter(between(as.numeric(month), as.numeric(begin), as.numeric(end))) %>%
    summarize(mean = mean(value))
results
## A tibble: 3 x 2
#      id  mean
#   <int> <dbl>
# 1     1     1
# 2     4     1
# 3     5     1


问:
While running the docker image docker build-arg values are not showing on console
I have created a Dockerfile shown below:

```<code>FROM ubuntu
MAINTAINER  ravat
CMD echo "Hello"
ARG jam_url
ENV jam_url=$jam_url
ENTRYPOINT echo "This is, $jam_url"
ENV name Ravat Tailor
ENTRYPOINT echo "Hello, $name"
</code>```

I build the image with the following docker build command:

```<code>docker build -t dockerdemo --build-arg jam_url=mydomain .
</code>```

after that I run the image:

```<code>docker run dockerdemo
</code>```

and get the following output:

Hello, Ravat Tailor

My problem is: why are jam_url and Hello not printing to the console?

答:
A few things:

Only the last ENTRYPOINT instruction is used when running an image. If there are more than one, the last is selected. https://docs.docker.com/engine/reference/builder/#entrypoint

The same goes for CMD https://docs.docker.com/engine/reference/builder/#cmd
And if there's a CMD and ENTRYPOINT instruction, it'll choose the ENTRYPOINT instruction instead.

This will do what you're trying to achieve:

FROM ubuntu
ARG jam_url
ENV jam_url=$jam_url
ENV name Ravat Tailor
ENTRYPOINT echo "This, $jam_url\nHello $name"

Body:
I have created a Dockerfile shown below:

FROM ubuntu
MAINTAINER  ravat
CMD echo "Hello"
ARG jam_url
ENV jam_url=$jam_url
ENTRYPOINT echo "This is, $jam_url"
ENV name Ravat Tailor
ENTRYPOINT echo "Hello, $name"

I build the image with the following docker build command:

docker build -t dockerdemo --build-arg jam_url=mydomain .

after that I run the image:

docker run dockerdemo

and get the following output:

Hello, Ravat Tailor

My problem is: why are jam_url and Hello not printing to the console?