问:
Python How To Import Files Like The Mac Does
I'm doing a note-taking software with PyGame and in the program I want to import some .png or .jpeg files to the background. It is easy to get an input and import an "x" file as "/Users/a/Desktop/Noting/a.jpg" But what I wanna do is to open a menu just like the Mac does.

How could I trigger that screen to be opened with Python and import files from there?

答:
PyGame is not GUI Framework and it doesn't have methods to open window and select file.

There are modules with some widgets for PyGame like PGU or OcempGUI and there can be simple window to select file. Maybe you should write it with real GUI framework like tkinter, PyQt, wxPython, etc.

BTW: They use own mainloop to control widgets so probably you will have to change own loop and use only methods from this GUI.


来源: stackexchange

问:
Is there a library for iPhone to work with HMAC-SHA-1 encoding
For all operation with Amazon services(S3, EC2, SimpleDB) You need to sign all resquest with HMAC-SHA-1 Signature(http://en.wikipedia.org/wiki/HMAC , http://docs.amazonwebservices.com/AWSFWS/latest/DeveloperGuide/index.html?SummaryOfAuthentication.html).

I'm working under asp.net backend and there is no problems. Problem is in the iPhone application. iPhone developer says that there is no way to use HMAC-SHA-1 encoding, and he have no rigths to implement his own algorithm. As programmer I cannot understand why there can be a problem.

So I want too know is iPhone developer right?

I've never coded for iPhone, so I don't even where to search such an information.

答:
I think the CommonCrypto library will do what you want. Look at this file:

/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.2.sdk/usr/include/CommonCrypto/CommonHMAC.h

OwnerDisplayName: AlfeG

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Boot To The Head


问:
SQL Server Management Studio (SSMS) quit automatically after installing Visual Studio 2017
I get this error:

The Microsoft.VisualStudio.Editor.Implementation.EditorPackage package did not load correctly.The problem may have been caused by a configuration change or by the installation of another extension....

when I try to start SQL Server Management Studio (SSMS) after installing Visual Studio 2017.

SSMS quits after I click 'Yes'. SSMS quits automatically when I try to restart it.

Visual Studio version: Visual Studio 2017

SSMS version: SQL Server Management Studio 17

Operation version: Windows 10

答:
SSMS 17 is using VS 2015 editor engine, looks like some sequence of apps installation/un-installation causes VS 2015 editor corruption.

What helped me is to uninstall SSMS, uninstall "Microsoft Visual Studio Tools for Applications 2015 Language Support", uninstall (via Modify) "Microsoft Visual Studio Tools for Applications 2015", uninstall (via Modify) "Microsoft Visual Studio 2015 Shell (Isolated)". Then reinstall SSMS.

Also I've seen posts that SSMS user settings corruption can cause that issue, the easiest way to check that is to create a new windows account and see if SSMS can be started from it. Wasn't my case though.

ContentLicense: CC BY-SA 3.0


问:
Reshaping 2 numpy dimensions into one with zipping?
I tried searching for this question but I couldn't find anything relevant.

The quickest way to describe the problem is with a simple example:
lets say I have a 2D numpy arrayl like this:

```<code>[[0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23]]
</code>```

So it has the shape [3,6]
I want to reshape it into a 1D array that looks like this:

```<code>[0, 10 ,20 ,1 ,11 ,21 ,2 ,12 ,22 ,3 ,13 ,23 ]
</code>```

Unlike the array we get with reshape:

```<code>[ 0,  1,  2,  3, 10, 11, 12, 13, 20, 21, 22, 23]
</code>```

Now, to the actual problem I have...
I actually have a 3D array and I want to reshape it into 2D array, and I want to do so with the method described above.
And another example would be:

```<code>import numpy
a = numpy.array([[[0,1,2],[10,11,12],[20,21,22]],
[[100,101,102],[110,111,112],[120,121,122]],
 [[200,201,202],[210,211,212],[220,221,222]]])
a.shape
a.reshape(3,9)
OUTPUT: array([[  0,   1,   2,  10,  11,  12,  20,  21,  22],
       [100, 101, 102, 110, 111, 112, 120, 121, 122],
       [200, 201, 202, 210, 211, 212, 220, 221, 222]])
</code>```

And again, I want my output to look like this instead:

```<code>[[  0,  10,  20,   1,  11,  21,   2,  12,  22],
 [100, 110, 120, 101, 111, ..................],
 [...........................................]]
</code>```

EDIT: just for the sake of people who google this problem, I add some search terms that some people might search for:

Interweave dimensions numpy array

Zip dimensions numpy array

Numpy reshape ordered dimensions

Tensor reshape dimensions timesteps

答:
Also, you can use np.ravel with order='F'.

```<code>In [35]: arr
Out[35]:
array([[ 0,  1,  2,  3],
       [10, 11, 12, 13],
       [20, 21, 22, 23]])

In [36]: np.ravel(arr, order='F')
Out[36]: array([ 0, 10, 20,  1, 11, 21,  2, 12, 22,  3, 13, 23])
</code>```

Please note that unlike in np.reshape(), you don't have to specify any shape information here.

Body:
I tried searching for this question but I couldn't find anything relevant.

The quickest way to describe the problem is with a simple example:
lets say I have a 2D numpy arrayl like this:

[[0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23]]

So it has the shape [3,6]
I want to reshape it into a 1D array that looks like this:

[0, 10 ,20 ,1 ,11 ,21 ,2 ,12 ,22 ,3 ,13 ,23 ]

Unlike the array we get with reshape:

[ 0,  1,  2,  3, 10, 11, 12, 13, 20, 21, 22, 23]

Now, to the actual problem I have...
I actually have a 3D array and I want to reshape it into 2D array, and I want to do so with the method described above.
And another example would be:

import numpy
a = numpy.array([[[0,1,2],[10,11,12],[20,21,22]],
[[100,101,102],[110,111,112],[120,121,122]],
 [[200,201,202],[210,211,212],[220,221,222]]])
a.shape
a.reshape(3,9)
OUTPUT: array([[  0,   1,   2,  10,  11,  12,  20,  21,  22],
       [100, 101, 102, 110, 111, 112, 120, 121, 122],
       [200, 201, 202, 210, 211, 212, 220, 221, 222]])

And again, I want my output to look like this instead:

[[  0,  10,  20,   1,  11,  21,   2,  12,  22],
 [100, 110, 120, 101, 111, ..................],
 [...........................................]]

EDIT: just for the sake of people who google this problem, I add some search terms that some people might search for:

Interweave dimensions numpy array

Zip dimensions numpy array

Numpy reshape ordered dimensions

Tensor reshape dimensions timesteps

Body:
Also, you can use np.ravel with order='F'.

In [35]: arr
Out[35]:
array([[ 0,  1,  2,  3],
       [10, 11, 12, 13],
       [20, 21, 22, 23]])

In [36]: np.ravel(arr, order='F')
Out[36]: array([ 0, 10, 20,  1, 11, 21,  2, 12, 22,  3, 13, 23])

Please note that unlike in np.reshape(), you don't have to specify any shape information here.


问:
i draw a circle with pygame, but it says i have too many arguments
I am coding a game for a project and am trying to figure out how to draw a circle that I can use as a button. I have used the pygame.draw.circle function. here is my current code:

```<code>import pygame
block_color = (0, 0, 255)
display_height = 600
display_width = 600
pygame.init()
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.draw.circle(gameDisplay, block_color, (50, 50), 20, 0)
thing_width = 100
thing_height = 100
thing_startx = 10
thing_starty = 10
circle(thing_startx, thing_starty, thing_width, thing_height, block_color)
pygame.display.update()
</code>```

according to the pygame function documentation, this should work, but all I get is:

```<code>line 12, in <module>
circle(thing_startx, thing_starty, thing_width, thing_height, block_color)
NameError: name 'circle' is not defined
</code>```

答:
You can calculate the distance to the center of the circle with the math.hypot function. If the distance is below the radius, the circle was clicked.

```<code>import math
import pygame as pg

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    circle_pos = (300, 200)
    circle_radius = 40

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.MOUSEBUTTONDOWN:
                # x and y distance to the mouse position (event.pos).
                x_offset = event.pos[0] - circle_pos[0]
                y_offset = event.pos[1] - circle_pos[1]
                distance = math.hypot(x_offset, y_offset)
                if distance < circle_radius:
                    print('Circle clicked.', distance)

        screen.fill((30, 30, 30))
        pg.draw.circle(screen, (240, 120, 0), circle_pos, circle_radius)

        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
</code>```

You could also use pygame.mask.Masks for the collision detection, but the hypot solution is simpler.

Body:
I am coding a game for a project and am trying to figure out how to draw a circle that I can use as a button. I have used the pygame.draw.circle function. here is my current code:

import pygame
block_color = (0, 0, 255)
display_height = 600
display_width = 600
pygame.init()
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.draw.circle(gameDisplay, block_color, (50, 50), 20, 0)
thing_width = 100
thing_height = 100
thing_startx = 10
thing_starty = 10
circle(thing_startx, thing_starty, thing_width, thing_height, block_color)
pygame.display.update()

according to the pygame function documentation, this should work, but all I get is:

line 12, in <module>
circle(thing_startx, thing_starty, thing_width, thing_height, block_color)
NameError: name 'circle' is not defined

Body:
You can calculate the distance to the center of the circle with the math.hypot function. If the distance is below the radius, the circle was clicked.

import math
import pygame as pg

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    circle_pos = (300, 200)
    circle_radius = 40

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.MOUSEBUTTONDOWN:
                # x and y distance to the mouse position (event.pos).
                x_offset = event.pos[0] - circle_pos[0]
                y_offset = event.pos[1] - circle_pos[1]
                distance = math.hypot(x_offset, y_offset)
                if distance < circle_radius:
                    print('Circle clicked.', distance)

        screen.fill((30, 30, 30))
        pg.draw.circle(screen, (240, 120, 0), circle_pos, circle_radius)

        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

You could also use pygame.mask.Masks for the collision detection, but the hypot solution is simpler.


问:
check a user_role laravel 5.4
What would be the best way to add a custom validation of checking if a user has a certain role. using a roles table and role_user pivot table

the roles table has 3 roles

1 user
2 mentor
3 admin

```<code>protected function validateLogin(Request $request)
{
    $this->validate($request, [
        $this->username() => [
        'required','string',
        Rule::exists('users')->where(function ($query){
            $query->where('active', true);
            }),
        ],

        'password' => 'required|string',
       ], $this->validation_errors());

 }
</code>```

答:
Check out the middleware documentation: Laravel - Middlewares

You should create a middleware that checks if the user has the role you want and add it to your route.

Title: check a user_role laravel 5.4

Body:
What would be the best way to add a custom validation of checking if a user has a certain role. using a roles table and role_user pivot table

the roles table has 3 roles

1 user
2 mentor
3 admin

protected function validateLogin(Request $request)
{
    $this->validate($request, [
        $this->username() => [
        'required','string',
        Rule::exists('users')->where(function ($query){
            $query->where('active', true);
            }),
        ],

        'password' => 'required|string',
       ], $this->validation_errors());

 }


问:
new never fails?
In C++, we usually see and write code like,

```<code>Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}
</code>```

But in C#, I rarely see this: (at least I've never seen this)

```<code>Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}
</code>```

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.

答: There are an OutOfMemoryException in C#</p>

Title: new never fails?

Body:
In C++, we usually see and write code like,

Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}

But in C#, I rarely see this: (at least I've never seen this)

Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.

Body: There are an OutOfMemoryException in C#


问:
More than 1 object in a single JFrame
I'm hoping someone can push me in the right direction with this. I have 3 separate classes, Calculator, Calculator2, and a Calculator3. In principal they are all the same, except for a few changes to some of the buttons, so I'll just paste the code for Calculator. I was wondering how can I get them so all appear in a single JFrame next to each other in a main? I attached my most recent attempt of the main as well.

Here is Calculator:

```<code>public class Calculator implements ActionListener {
private JFrame frame;
private JTextField xfield, yfield;
private JLabel result;
private JButton subtractButton;
private JButton divideButton;
private JButton addButton;
private JButton timesButton;
private JPanel xpanel;

public Calculator() {
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());

    xpanel = new JPanel();
    xpanel.setLayout(new GridLayout(3,2));

    xpanel.add(new JLabel("x:", SwingConstants.RIGHT));
    xfield = new JTextField("0", 5);
    xpanel.add(xfield);

    xpanel.add(new JLabel("y:", SwingConstants.RIGHT));
    yfield = new JTextField("0", 5);
    xpanel.add(yfield);

    xpanel.add(new JLabel("Result:"));
    result = new JLabel("0");
    xpanel.add(result);
    frame.add(xpanel, BorderLayout.NORTH);

    /***********************************************************************
     ***********************************************************************
     **********************************************************************/

    JPanel southPanel = new JPanel();                      //New panel for the artimatic buttons
    southPanel.setBorder(BorderFactory.createEtchedBorder());

    timesButton = new JButton("Multiplication");
    southPanel.add(timesButton);
    timesButton.addActionListener(this);

    subtractButton = new JButton("Subtract");
    southPanel.add(subtractButton);
    subtractButton.addActionListener(this);

    divideButton = new JButton("Division");
    southPanel.add(divideButton);
    divideButton.addActionListener(this);

    addButton = new JButton("Addition");
    southPanel.add(addButton);
    addButton.addActionListener(this);

    frame.add(southPanel , BorderLayout.SOUTH);

    Font thisFont = result.getFont();                                       //Get current font
    result.setFont(thisFont.deriveFont(thisFont.getStyle() ^ Font.BOLD));   //Make the result bold
    result.setForeground(Color.red);                                        //Male the result answer red in color
    result.setBackground(Color.yellow);                                     //Make result background yellow
    result.setOpaque(true);

    frame.pack();
    frame.setVisible(true);
}
/**
 * clear()
 * Resets the x and y field to 0 after invalid integers were input
 */
public void clear() {
    xfield.setText("0");
    yfield.setText("0");
}

@Override
public void actionPerformed(ActionEvent event) {
    String xText = xfield.getText();                        //Get the JLabel fiels and set them to strings
    String yText = yfield.getText();

    int xVal;
    int yVal;

    try {
        xVal = Integer.parseInt(xText);                     //Set global var xVal to incoming string
        yVal = Integer.parseInt(yText);                     //Set global var yVal to incoming string
    }
    catch (NumberFormatException e) {                       //xVal or yVal werent valid integers, print message and don't continue
        result.setText("ERROR");
        clear();
        return ;
    }

    if(event.getSource().equals(timesButton)) {             //Button pressed was multiply
        result.setText(Integer.toString(xVal*yVal));
    }
    else if(event.getSource().equals(divideButton)) {       //Button pressed was division
        if(yVal == 0) {                                   //Is the yVal (bottom number) 0?
            result.setForeground(Color.red);              //Yes it is, print message
            result.setText("CAN'T DIVIDE BY ZERO!");
            clear();
        }
        else
            result.setText(Integer.toString(xVal/yVal));  //No it's not, do the math
    }
    else if(event.getSource().equals(subtractButton)) {    //Button pressed was subtraction
        result.setText(Integer.toString(xVal-yVal));
    }
    else if(event.getSource().equals(addButton)) {        //Button pressed was addition
        result.setText(Integer.toString(xVal+yVal));
    }
  }
}
</code>```

And here is my current main:

```<code>public class DemoCalculator {
public static void main(String[] args) {
    JFrame mainFrame = new JFrame("Calculators");
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Calculator calc = new Calculator();
    Calculator2 calc2 = new Calculator2();
    JPanel calcPanel = new JPanel(new BorderLayout());
    JPanel calcPanel2 = new JPanel(new BorderLayout());

    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

    //calcPanel.add(calc, BorderLayout.CENTER);
    //calcPanel2.add(calc2, BorderLayout.CENTER);
    mainPanel.add(calcPanel);
    mainPanel.add(calcPanel2);
    calcPanel.add(mainPanel);

    mainFrame.getContentPane().add(calcPanel);
    mainFrame.getContentPane().add(calcPanel2);
    mainFrame.pack();
    mainFrame.setVisible(true);
    }
}
</code>```

答:
You should just create a single JFrame and put your Calculator classes each into a single JPanel.Don't create a new JFrame for each class.

```<code>public class Calculator{

JPanel panel;
public Calculator(){

  panel = new JPanel();

  /*
  *  Add labels and buttons etc.
  */
   panel.add(buttons);
   panel.add(labels);
}

  //Method to return the JPanel
  public JPanel getPanel(){
  return panel;
 }
}
</code>```

Then add the panels to your JFrame in your testers class using whatever layout best suits your needs.

```<code>public class DemoCalculator {

public static void main(String[] args) {

    JPanel cal1,cal2;
    JFrame frame = new JFrame("Calculators");

    frame.add(cal1 = new Calculator().getPanel(),new BorderLayout().EAST);
    frame.add(cal2 = new Calculator2().getPanel(),new BorderLayout().WEST);

    frame.setSize(1000,600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setVisible(true);
  }
}
</code>```

Title: More than 1 object in a single JFrame

Body:
I'm hoping someone can push me in the right direction with this. I have 3 separate classes, Calculator, Calculator2, and a Calculator3. In principal they are all the same, except for a few changes to some of the buttons, so I'll just paste the code for Calculator. I was wondering how can I get them so all appear in a single JFrame next to each other in a main? I attached my most recent attempt of the main as well.

Here is Calculator:

public class Calculator implements ActionListener {
private JFrame frame;
private JTextField xfield, yfield;
private JLabel result;
private JButton subtractButton;
private JButton divideButton;
private JButton addButton;
private JButton timesButton;
private JPanel xpanel;

public Calculator() {
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());

    xpanel = new JPanel();
    xpanel.setLayout(new GridLayout(3,2));

    xpanel.add(new JLabel("x:", SwingConstants.RIGHT));
    xfield = new JTextField("0", 5);
    xpanel.add(xfield);

    xpanel.add(new JLabel("y:", SwingConstants.RIGHT));
    yfield = new JTextField("0", 5);
    xpanel.add(yfield);

    xpanel.add(new JLabel("Result:"));
    result = new JLabel("0");
    xpanel.add(result);
    frame.add(xpanel, BorderLayout.NORTH);

    /***********************************************************************
     ***********************************************************************
     **********************************************************************/

    JPanel southPanel = new JPanel();                      //New panel for the artimatic buttons
    southPanel.setBorder(BorderFactory.createEtchedBorder());

    timesButton = new JButton("Multiplication");
    southPanel.add(timesButton);
    timesButton.addActionListener(this);

    subtractButton = new JButton("Subtract");
    southPanel.add(subtractButton);
    subtractButton.addActionListener(this);

    divideButton = new JButton("Division");
    southPanel.add(divideButton);
    divideButton.addActionListener(this);

    addButton = new JButton("Addition");
    southPanel.add(addButton);
    addButton.addActionListener(this);

    frame.add(southPanel , BorderLayout.SOUTH);

    Font thisFont = result.getFont();                                       //Get current font
    result.setFont(thisFont.deriveFont(thisFont.getStyle() ^ Font.BOLD));   //Make the result bold
    result.setForeground(Color.red);                                        //Male the result answer red in color
    result.setBackground(Color.yellow);                                     //Make result background yellow
    result.setOpaque(true);

    frame.pack();
    frame.setVisible(true);
}
/**
 * clear()
 * Resets the x and y field to 0 after invalid integers were input
 */
public void clear() {
    xfield.setText("0");
    yfield.setText("0");
}

@Override
public void actionPerformed(ActionEvent event) {
    String xText = xfield.getText();                        //Get the JLabel fiels and set them to strings
    String yText = yfield.getText();

    int xVal;
    int yVal;

    try {
        xVal = Integer.parseInt(xText);                     //Set global var xVal to incoming string
        yVal = Integer.parseInt(yText);                     //Set global var yVal to incoming string
    }
    catch (NumberFormatException e) {                       //xVal or yVal werent valid integers, print message and don't continue
        result.setText("ERROR");
        clear();
        return ;
    }

    if(event.getSource().equals(timesButton)) {             //Button pressed was multiply
        result.setText(Integer.toString(xVal*yVal));
    }
    else if(event.getSource().equals(divideButton)) {       //Button pressed was division
        if(yVal == 0) {                                   //Is the yVal (bottom number) 0?
            result.setForeground(Color.red);              //Yes it is, print message
            result.setText("CAN'T DIVIDE BY ZERO!");
            clear();
        }
        else
            result.setText(Integer.toString(xVal/yVal));  //No it's not, do the math
    }
    else if(event.getSource().equals(subtractButton)) {    //Button pressed was subtraction
        result.setText(Integer.toString(xVal-yVal));
    }
    else if(event.getSource().equals(addButton)) {        //Button pressed was addition
        result.setText(Integer.toString(xVal+yVal));
    }
  }
}

And here is my current main:

public class DemoCalculator {
public static void main(String[] args) {
    JFrame mainFrame = new JFrame("Calculators");
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Calculator calc = new Calculator();
    Calculator2 calc2 = new Calculator2();
    JPanel calcPanel = new JPanel(new BorderLayout());
    JPanel calcPanel2 = new JPanel(new BorderLayout());

    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

    //calcPanel.add(calc, BorderLayout.CENTER);
    //calcPanel2.add(calc2, BorderLayout.CENTER);
    mainPanel.add(calcPanel);
    mainPanel.add(calcPanel2);
    calcPanel.add(mainPanel);

    mainFrame.getContentPane().add(calcPanel);
    mainFrame.getContentPane().add(calcPanel2);
    mainFrame.pack();
    mainFrame.setVisible(true);
    }
}

Body:
You should just create a single JFrame and put your Calculator classes each into a single JPanel.Don't create a new JFrame for each class.

public class Calculator{

JPanel panel;
public Calculator(){

  panel = new JPanel();

  /*
  *  Add labels and buttons etc.
  */
   panel.add(buttons);
   panel.add(labels);
}

  //Method to return the JPanel
  public JPanel getPanel(){
  return panel;
 }
}

Then add the panels to your JFrame in your testers class using whatever layout best suits your needs.

public class DemoCalculator {

public static void main(String[] args) {

    JPanel cal1,cal2;
    JFrame frame = new JFrame("Calculators");

    frame.add(cal1 = new Calculator().getPanel(),new BorderLayout().EAST);
    frame.add(cal2 = new Calculator2().getPanel(),new BorderLayout().WEST);

    frame.setSize(1000,600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setVisible(true);
  }
}


问:
Replace Floating point numbers in a list with '0'
So my programming assignment wants me to take a user inputted list of numbers, ints and floating, and then order them in descending order and replace any of the floating with "0". I have got the reorder part done but the replace is getting me lost.

Reading Numbers
Write a program that shall ask the user to enter several integer numbers on
the same line, separated by vertical bars surrounded by zero or more spaces
(e.g., “|” or “ |” or “| ” or “ | ”). The program then shall display the entered
numbers in the descending sorted order (from the largest to the smallest),
all on the same line, separated by vertical bars and spaces (“ | ”). If
any entry on the command line is not an integer number, the program shall
replace it with a 0. Use only “for” loop(s) or list comprehensions. Use exception
handling.

```<code># takes input and split them to get a list
numbers = input("Please enter numbers separated by vertical bars '|' :
").split("|")
# replace the floating numbers with "0"
for number in numbers:
    print(type(number))
    if number.isdigit() == False:
        numbers.replace(number,'0')
# takes the list and reverse order sort and prints it with a "|" in between
numbers.sort(key = float , reverse = True)
[print(number,end = ' | ') for number in numbers]
</code>```

答:
the instructions permit you to use exceptions.  the following should get you most of the way there.</p>

```<code>>>> numbers = ['1', '1.5', 'dog', '2', '2.0']
>>> for number in numbers:
>>>    try:
>>>        x = int(number)
>>>    except:
>>>        x  = 0
>>>    print(x)
1
0
0
2
0
</code>```

Body:
So my programming assignment wants me to take a user inputted list of numbers, ints and floating, and then order them in descending order and replace any of the floating with "0". I have got the reorder part done but the replace is getting me lost.

Reading Numbers
Write a program that shall ask the user to enter several integer numbers on
the same line, separated by vertical bars surrounded by zero or more spaces
(e.g., “|” or “ |” or “| ” or “ | ”). The program then shall display the entered
numbers in the descending sorted order (from the largest to the smallest),
all on the same line, separated by vertical bars and spaces (“ | ”). If
any entry on the command line is not an integer number, the program shall
replace it with a 0. Use only “for” loop(s) or list comprehensions. Use exception
handling.

# takes input and split them to get a list
numbers = input("Please enter numbers separated by vertical bars '|' :
").split("|")
# replace the floating numbers with "0"
for number in numbers:
    print(type(number))
    if number.isdigit() == False:
        numbers.replace(number,'0')
# takes the list and reverse order sort and prints it with a "|" in between
numbers.sort(key = float , reverse = True)
[print(number,end = ' | ') for number in numbers]

Body:
the instructions permit you to use exceptions.  the following should get you most of the way there.

>>> numbers = ['1', '1.5', 'dog', '2', '2.0']
>>> for number in numbers:
>>>    try:
>>>        x = int(number)
>>>    except:
>>>        x  = 0
>>>    print(x)
1
0
0
2
0


问:
How to keep a div on the right side of the page in CSS
I'm building a website, and I'm trying to get a div element to stick to the right side of the page.

However, when my other divs, that contain blog post data/images scroll over to the next page, the div gets entered down.

How do I prevent the right side column from being entered down, while still allowing my blog post entries to scroll over?

Here is my code, what's relevant anyways. I'm sorry if this is a beginner question (it really is). I appreciate all the help I can get.
Thanks.

```<code>.column {
    float:left;
}

.column.main {
    width:70%;
    min-height:1px;
}

.column.side {
    width:20%;
    min-height:1px;

}

.column.left {
    width:10%;
    background-color:012C40;
    height:85%;
    min-width:1px;
}

.column.right {
    width:10%;
    background-color:012C40;
    height:85%;
    float:right;
    min-height:1px;
}

.postAd {
    width:19%;
    height:32%;
    float:left;
    background-color:DAEBF2;
    text-align:center;
    display:inline-block;
    margin:.5%;
    overflow: auto;
}

.postAd img {
    width:80%;
    height:80%;*/
}

<div class="column left">
</div>
<!--middle content-->

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">
</div>

<!--right side content-->

<div class="column right">
</div>
</code>```

First of all, thanks for all of the proposed solutions! However, I've tried each one, and I'm running into problems. I have a navigation bar on top of my website, and each one overwrites that bar. When I try to make adaptations, I get the same problem as before. How do I implement these without completely destroying the layout of my website?

Again, huge thanks to everyone that responded.

答:
You can use flex positioning like below

```<code>.parent
{
 display:flex;
}

.right
{
 flex:1; /*which is equal to 1 portion of width */
}
.left
{
flex:1; /*which is equal to 1 portion of width */
}
.center
{
 flex:8; /*which is equal to 8 portion of width */
}
</code>```

I suggest you to watch this video on youtube .

Body:
I'm building a website, and I'm trying to get a div element to stick to the right side of the page.

However, when my other divs, that contain blog post data/images scroll over to the next page, the div gets entered down.

How do I prevent the right side column from being entered down, while still allowing my blog post entries to scroll over?

Here is my code, what's relevant anyways. I'm sorry if this is a beginner question (it really is). I appreciate all the help I can get.
Thanks.

.column {
    float:left;
}

.column.main {
    width:70%;
    min-height:1px;
}

.column.side {
    width:20%;
    min-height:1px;

}

.column.left {
    width:10%;
    background-color:012C40;
    height:85%;
    min-width:1px;
}

.column.right {
    width:10%;
    background-color:012C40;
    height:85%;
    float:right;
    min-height:1px;
}

.postAd {
    width:19%;
    height:32%;
    float:left;
    background-color:DAEBF2;
    text-align:center;
    display:inline-block;
    margin:.5%;
    overflow: auto;
}

.postAd img {
    width:80%;
    height:80%;*/
}

Text here!

Text here!

Text here!

Text here!

First of all, thanks for all of the proposed solutions! However, I've tried each one, and I'm running into problems. I have a navigation bar on top of my website, and each one overwrites that bar. When I try to make adaptations, I get the same problem as before. How do I implement these without completely destroying the layout of my website?

Again, huge thanks to everyone that responded.

Body:
You can use flex positioning like below

.parent
{
 display:flex;
}

.right
{
 flex:1; /*which is equal to 1 portion of width */
}
.left
{
flex:1; /*which is equal to 1 portion of width */
}
.center
{
 flex:8; /*which is equal to 8 portion of width */
}

I suggest you to watch this video on youtube .


问:
How can I check if two sprites are overlapping/touching in Monogame?
I'd like to determine if two sprites are overlapping in Monogame. I'd like to use a check similar to that below:  </p>

```<code>if ( /* Are Sprites Overlapping? */ )
{
    // Do stuff;
}
</code>```

答:
This is what you need:</p>

```<code> if (mySprite.Intersects(otherSprite))
</code>```

Body:
I'd like to determine if two sprites are overlapping in Monogame. I'd like to use a check similar to that below:

if ( /* Are Sprites Overlapping? */ )
{
    // Do stuff;
}

Body:
This is what you need:

 if (mySprite.Intersects(otherSprite))


问:
Lag when visible frame layout that has been put beside another resizing frame layout
 I have 2 Frame Layout in Relative Layout like that :

```<code> <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_nav_bar" >

        <FrameLayout
            android:id="@+id/for_dashboard_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clickable="true" >
        </FrameLayout>

        <FrameLayout
            android:id="@+id/for_main_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clickable="true" >
        </FrameLayout>
    </RelativeLayout>
</code>```

 Case 1 : I set the for_main_layout adjust resize when the for_dashboard_layout is visible, so it has been lag / delay about 2-3 seconds

 Case 2 : The for_dashboard_layout being GONE and the for_main_layout being resize, next I show the for_dashboard_layout by call VISIBLE, same problem ( lag about 2-3 seconds ) has been happend

Any body can help me to solve that...

答: Can't really tell until it's clear what else is happening around your logic to show and hide your dashboard, maybe your dashboard is trying to load large data or a list with many elements. Try replacing with INVISIBLE instead of GONE to reduce the time lag.</p>

Body:
 I have 2 Frame Layout in Relative Layout like that :

 <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_nav_bar" >

        <FrameLayout
            android:id="@+id/for_dashboard_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clickable="true" >
        </FrameLayout>

        <FrameLayout
            android:id="@+id/for_main_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clickable="true" >
        </FrameLayout>
    </RelativeLayout>

 Case 1 : I set the for_main_layout adjust resize when the for_dashboard_layout is visible, so it has been lag / delay about 2-3 seconds

 Case 2 : The for_dashboard_layout being GONE and the for_main_layout being resize, next I show the for_dashboard_layout by call VISIBLE, same problem ( lag about 2-3 seconds ) has been happend

Any body can help me to solve that...


问:
Two ways to put image into graphics context - which is better?
I've noticed examples of two ways to put images into core graphics.  One is much simpler than the other.  So what's the advantage of the second, more sophisticated, approach?  Is it faster?

example 1

```<code>UIImage *myImage = [UIImage imageNamed:@"picture.png"];
CGRect imageRect = CGRectMake(70, 330, 40, 40);
[myImage drawInRect:imageRect];
[myImage release];
</code>```

example 2

```<code>// Load image from application bundle
NSString* imageFileName = [[[NSBundle mainBundle] resourcePath]         stringByAppendingPathComponent:@"picture.png"];
CGDataProviderRef provider = CGDataProviderCreateWithFilename([imageFileName UTF8String]);
CGImageRef image = CGImageCreateWithPNGDataProvider(provider, NULL, true,      kCGRenderingIntentDefault);
CGDataProviderRelease(provider);

// Draw image
CGContextTranslateCTM(context, 70, 370 );
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0, 0, 40, 40), image);
CGImageRelease(image);
</code>```

答: I don't know any advantages for the second way. It has the disadvantage of having more steps. If you use the first way and have a UIImage and you need a CGImageRef you can access it through the CGImage property. I find myself using the first most often. When you have a UIImage you can use your own UIImageView to add it to a view hierarchy or you can assign it directly to some of the UIKit objects like UITableViewCell's imageView. If you get the CGImageRef (second way) then you would need to imageWithCGImage: first...</p>

Body:
I've noticed examples of two ways to put images into core graphics.  One is much simpler than the other.  So what's the advantage of the second, more sophisticated, approach?  Is it faster?

example 1

UIImage *myImage = [UIImage imageNamed:@"picture.png"];
CGRect imageRect = CGRectMake(70, 330, 40, 40);
[myImage drawInRect:imageRect];
[myImage release];

example 2

// Load image from application bundle
NSString* imageFileName = [[[NSBundle mainBundle] resourcePath]         stringByAppendingPathComponent:@"picture.png"];
CGDataProviderRef provider = CGDataProviderCreateWithFilename([imageFileName UTF8String]);
CGImageRef image = CGImageCreateWithPNGDataProvider(provider, NULL, true,      kCGRenderingIntentDefault);
CGDataProviderRelease(provider);

// Draw image
CGContextTranslateCTM(context, 70, 370 );
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0, 0, 40, 40), image);
CGImageRelease(image);


问:
How to output a table as a parquet file in spark-sql, not spark-shell?
It is easy to read a table from CSV file using spark-sql:

```<code>CREATE TABLE MyTable (
    X   STRING,
    Y   STRING
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
    "separatorChar" = "\,",
    "quoteChar"     = "\""
)
STORED AS TEXTFILE;

LOAD DATA LOCAL INPATH 'input.csv' INTO TABLE MyTable;
</code>```

But how can I output this result as Parquet file?

PS: I know how to do that in spark-shell, but it is not what I'm looking for.

答:
You have to create one table with the schema of your results in hive stored as parquet. After getting the results you can export them into the parquet file format table like this.

set hive.insert.into.external.tables = true

create external table mytable_parq ( use your source table DDL) stored as parquet location '/hadoop/mytable';

insert into mytable_parq select * from mytable ;

or

```<code>insert overwrite directory '/hadoop/mytable' STORED AS PARQUET select * from MyTable ;
</code>```

Body:
It is easy to read a table from CSV file using spark-sql:

CREATE TABLE MyTable (
    X   STRING,
    Y   STRING
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
    "separatorChar" = "\,",
    "quoteChar"     = "\""
)
STORED AS TEXTFILE;

LOAD DATA LOCAL INPATH 'input.csv' INTO TABLE MyTable;

But how can I output this result as Parquet file?

PS: I know how to do that in spark-shell, but it is not what I'm looking for.

Body:
You have to create one table with the schema of your results in hive stored as parquet. After getting the results you can export them into the parquet file format table like this.

set hive.insert.into.external.tables = true

create external table mytable_parq ( use your source table DDL) stored as parquet location '/hadoop/mytable';

insert into mytable_parq select * from mytable ;

or

insert overwrite directory '/hadoop/mytable' STORED AS PARQUET select * from MyTable ;


问:
difference between Graph API Explorer access token and App access token
What is the difference between Graph API Explorer access token and App access token.

When I try to post with restfb using App access token I am not able to see my post in the page. The same post is visible when it is posted using Graph API Explorer access token.

I am force to use App access token as the Graph API Explorer access token is short validity.

答:
You would be best to read here through the facebook developer documentation,

but as a summary,

User access tokens are needed any time the app calls an API to read, modify or write a specific person's Facebook data on their behalf.

App access tokens are needed to modify and read the app settings. It can also be used to publish Open Graph actions.

Page Access Tokens are similar to user access tokens, except that they provide permission to APIs that read, write or modify the data belonging to a Facebook Page.

You will also find on that page some details on how to make your token "live" longer.


问:
Storing data from the keyboard to an array while ignoring duplicates
So I have a program that I'm working on as an assignment, and part of the requirement is asking me to call a method that retrieve numbers from the user, and storing them into an array of size 20. I have to do this while not including any duplicate values in the array, and I will continue storing the users numbers until the array is full, or the user has entered a negative value. I'm running into a couple of issues.

The user has to be able to enter data through multiple lines of text (using the 'enter' key) without interruption, for example:

Enter the integers for the array:
1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 18 18 18 18 19
20

That should store: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 into the array without duplicate values. The program didn't accept any other values because 20 unique digits had been entered, which filled the array.
I've tried to use different options such as nextInt(), nextLine(), and even storing the numbers as a List and then converting but I'm having so many issues.

So my question is, how do I allow the user to enter values across multiple lines of input as well as checking if the current value in the keyboard buffer is duplicate/negative, so I can know to skip that value in the buffer or end the program?

I'll include my code, but honestly I've tried reworking this so many times that it's an absolute mess. Any help will be more than welcomed.

```<code>    public static int getData(int [] set){
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter the integers for the array.");
    System.out.println("The program will stop accepting values when you enter a negative number or reach the 20 unique limit.");

    int usrInput=keyboard.nextInt(), arraySizeUsed = 0;

    for(int position = 0; position < 20; ) {

        if(!Arrays.asList(set).contains(usrInput)) {
            if(usrInput > -1) {

                set[position] = usrInput;
                position++;
                arraySizeUsed++;
            }

            else {
                return arraySizeUsed;
            }
        }
        else {
            continue;
        }
    }

    return arraySizeUsed;
}
</code>```

I don't think I should use 'continue' in the loop as I just want to keep the position from incrementing in the case that the current number in the keyboard buffer is already in the array. What am I missing?

答:
Here is another solution using a int array and a direct comparison search. </p>

```<code>import java.util.Scanner;

public class NumberScanner {

    private static final int MAX_SIZE = 20;

    static int[] intArray = new int[MAX_SIZE];

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        int value = 0;
        int size = 0; // Not an array counter, starts at 1. 0 means empty.

        System.out.println("Enter a series of positive integers on one or more lines. Enter a negative number to quit.");

        // Loop until a negative number is found or the MAX_SIZE is reached
        while (size < MAX_SIZE) {
            value = keyboard.nextInt();
            if (value < 0)
                break;

            boolean found = false;
            if (value >= 0 && size > 0) {
                // Add the value to the array
                // First, check if its already there
                for (int i = 0; i<size; i++) {
                    if (intArray[i] == value) {
                        found = true;
                        break;  // Stop the loop
                    }
                }
            }
            if (!found) {
                intArray[size] = value;
                size++;
            }
        }

        for (int i=0; i<size; i++) {
            System.out.printf(intArray[i] + " ");
        }
        System.out.printf("\n");

        keyboard.close();
    }
}
</code>```

Body:
So I have a program that I'm working on as an assignment, and part of the requirement is asking me to call a method that retrieve numbers from the user, and storing them into an array of size 20. I have to do this while not including any duplicate values in the array, and I will continue storing the users numbers until the array is full, or the user has entered a negative value. I'm running into a couple of issues.

The user has to be able to enter data through multiple lines of text (using the 'enter' key) without interruption, for example:

Enter the integers for the array:
1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 18 18 18 18 19
20

That should store: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 into the array without duplicate values. The program didn't accept any other values because 20 unique digits had been entered, which filled the array.
I've tried to use different options such as nextInt(), nextLine(), and even storing the numbers as a List and then converting but I'm having so many issues.

So my question is, how do I allow the user to enter values across multiple lines of input as well as checking if the current value in the keyboard buffer is duplicate/negative, so I can know to skip that value in the buffer or end the program?

I'll include my code, but honestly I've tried reworking this so many times that it's an absolute mess. Any help will be more than welcomed.

    public static int getData(int [] set){
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter the integers for the array.");
    System.out.println("The program will stop accepting values when you enter a negative number or reach the 20 unique limit.");

    int usrInput=keyboard.nextInt(), arraySizeUsed = 0;

    for(int position = 0; position < 20; ) {

        if(!Arrays.asList(set).contains(usrInput)) {
            if(usrInput > -1) {

                set[position] = usrInput;
                position++;
                arraySizeUsed++;
            }

            else {
                return arraySizeUsed;
            }
        }
        else {
            continue;
        }
    }

    return arraySizeUsed;
}

I don't think I should use 'continue' in the loop as I just want to keep the position from incrementing in the case that the current number in the keyboard buffer is already in the array. What am I missing?

Body:
Here is another solution using a int array and a direct comparison search.

import java.util.Scanner;

public class NumberScanner {

    private static final int MAX_SIZE = 20;

    static int[] intArray = new int[MAX_SIZE];

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        int value = 0;
        int size = 0; // Not an array counter, starts at 1. 0 means empty.

        System.out.println("Enter a series of positive integers on one or more lines. Enter a negative number to quit.");

        // Loop until a negative number is found or the MAX_SIZE is reached
        while (size < MAX_SIZE) {
            value = keyboard.nextInt();
            if (value < 0)
                break;

            boolean found = false;
            if (value >= 0 && size > 0) {
                // Add the value to the array
                // First, check if its already there
                for (int i = 0; i<size; i++) {
                    if (intArray[i] == value) {
                        found = true;
                        break;  // Stop the loop
                    }
                }
            }
            if (!found) {
                intArray[size] = value;
                size++;
            }
        }

        for (int i=0; i<size; i++) {
            System.out.printf(intArray[i] + " ");
        }
        System.out.printf("\n");

        keyboard.close();
    }
}


问:
How do you prevent duplicates from entering list using setdefault in python
Suppose you have a dictionary:

```<code>dict1 = {'a':[1,2], 'b':[1,2]}
</code>```

And suppose the next item is {b:2}. I don't want there to be any repeats in the values of my dictionary for all keys. So {b:2} would not update the dictionary, but {b:3} would update it as:

```<code>{'a':[1,2], 'b':[1,2,3]}
</code>```

I would like to make some alteration to the setdefault method to accomplish this.

答:
I modified your dict1 values to set.

```<code>In [44]: dict1 = {'a':[1,2],'b':[1,2]}

In [45]: dict1 = {k: set(v) for k, v in dict1.items()}

In [46]: def add_to_dict(dict_tmp):
    ...:     for k, v in dict_tmp.items():
    ...:         dict1.setdefault(k, set()).add(v)
    ...:     return dict1
    ...:

In [47]: d2 = {'b':2}

In [48]: d3 = {'b':3}

In [49]: add_to_dict(d2)
Out[49]: {'a': {1, 2}, 'b': {1, 2}}

In [50]: add_to_dict(d3)
Out[50]: {'a': {1, 2}, 'b': {1, 2, 3}}
</code>```

The function add_to_dict returns a dict with value as set. If your requirement is such that you need the values as list you can modify dict values at the end.

Body:
Suppose you have a dictionary:

dict1 = {'a':[1,2], 'b':[1,2]}

And suppose the next item is {b:2}. I don't want there to be any repeats in the values of my dictionary for all keys. So {b:2} would not update the dictionary, but {b:3} would update it as:

{'a':[1,2], 'b':[1,2,3]}

I would like to make some alteration to the setdefault method to accomplish this.

Body:
I modified your dict1 values to set.

In [44]: dict1 = {'a':[1,2],'b':[1,2]}

In [45]: dict1 = {k: set(v) for k, v in dict1.items()}

In [46]: def add_to_dict(dict_tmp):
    ...:     for k, v in dict_tmp.items():
    ...:         dict1.setdefault(k, set()).add(v)
    ...:     return dict1
    ...:

In [47]: d2 = {'b':2}

In [48]: d3 = {'b':3}

In [49]: add_to_dict(d2)
Out[49]: {'a': {1, 2}, 'b': {1, 2}}

In [50]: add_to_dict(d3)
Out[50]: {'a': {1, 2}, 'b': {1, 2, 3}}

The function add_to_dict returns a dict with value as set. If your requirement is such that you need the values as list you can modify dict values at the end.


问:
Plugging in computer to internet switch makes nothing work

Hey guys, so I came across a very odd problem, I recently bought a refurbished computer and put Ubuntu 16 onto it. However whenever I connect this computer to my ethernet-switch, after about 10-20 sec everything connected to the switch will no longer connect to the internet or LAN. I have no idea why this happening and any help would be amazing. Thanks in advance.</p>

答: I guess I fixed the problem, for some reason when I take out my gpu the problem stops, although I have no idea how the gpu would affect my internet connection.</p>


问:
passing variable from controller to partial view rails
I am stuck at passing a variable value from controller to partial. I have all the  data from skill set database on @skillSetData coming from controller: SkillSetsController

```<code>def skillsetdata
    @skillSetData = SkillSet.all
end
</code>```

The code below on skill_set/skillsetdata.html.erb display all the data.

```<code><% @skillSetData.each do |single_skill| %>

    <option value="<%= single_skill.skillname %>"><%=single_skill.skillname %></option>

<% end %>
</code>```

But I am not able to pass the variable if skillsetdata.html.erb is a partial ie: _skillsetdata.html.erb. The code for the _skillsetdata I have written is:

```<code><% skills_set_data.each do |single_skill| %>
   <option value="<%= single_skill.skillname %>">
      <%=single_skill.skillname %>
   </option>
<% end %>
</code>```

I want to make it partial because it has the dropdown list that has to be rendered on various other pages. One of the pages that I want to use on is:static_pages/home.html.erb which is from different controller ie: staticPages. The code that I have tried after the help is:

```<code><%= render partial: 'skill_sets/skillsetdata', locals: { skills_set_data:@skillSetData } %>
</code>```

But I am getting error as:
  undefined method `each' for nil:NilClass
in skill_sets/_skillsetdata.html.erb
while trying to load home.html.erb. I am not able to pass data between different pages from a partial.

Any help with example code would be helpful.

答:
I guess that you problem here: skill_sets/skillsetdata

```<code><%= render partial: 'skill_sets/skillsetdata', locals: { skills_set_data:@skillSetData } %>
</code>```

As you wrote that:

The code below on skill_set/skillsetdata.html.erb display all the data.

That the right name is: skill_set/skillsetdata

Here is right name:

```<code><%= render partial: 'skill_set/skillsetdata', locals: { skills_set_data:@skillSetData } %>
</code>```

Body:
I am stuck at passing a variable value from controller to partial. I have all the  data from skill set database on @skillSetData coming from controller: SkillSetsController

def skillsetdata
    @skillSetData = SkillSet.all
end

The code below on skill_set/skillsetdata.html.erb display all the data.

<% @skillSetData.each do |single_skill| %>

    <option value="<%= single_skill.skillname %>"><%=single_skill.skillname %></option>

<% end %>

But I am not able to pass the variable if skillsetdata.html.erb is a partial ie: _skillsetdata.html.erb. The code for the _skillsetdata I have written is:

<% skills_set_data.each do |single_skill| %>
   <option value="<%= single_skill.skillname %>">
      <%=single_skill.skillname %>
   </option>
<% end %>

I want to make it partial because it has the dropdown list that has to be rendered on various other pages. One of the pages that I want to use on is:static_pages/home.html.erb which is from different controller ie: staticPages. The code that I have tried after the help is:

<%= render partial: 'skill_sets/skillsetdata', locals: { skills_set_data:@skillSetData } %>

But I am getting error as:
  undefined method `each' for nil:NilClass
in skill_sets/_skillsetdata.html.erb
while trying to load home.html.erb. I am not able to pass data between different pages from a partial.

Any help with example code would be helpful.

Body:
I guess that you problem here: skill_sets/skillsetdata

<%= render partial: 'skill_sets/skillsetdata', locals: { skills_set_data:@skillSetData } %>

As you wrote that:

The code below on skill_set/skillsetdata.html.erb display all the data.

That the right name is: skill_set/skillsetdata

Here is right name:

<%= render partial: 'skill_set/skillsetdata', locals: { skills_set_data:@skillSetData } %>


问:
Pagination is not user friendly using php
Can someone help me why my '<<' not be in a box. And anyone know how to fix the coding as if i have 20 pages it will be page 1 until 20. I want it to be like ----->  eg: 1 2 3 4 5 ....17 . something like this. </p>

```<code>   $record_per_page = 10;
  $page = '';
    if(isset($_GET["page"]))
  {
    $page = $_GET["page"];
  }
    else
  {
    $page = 1;
  }

  $start_from = ($page-1)*$record_per_page;

  $sql = "SELECT id, created, fullname, level, filename, status FROM borang ORDER BY id DESC LIMIT $start_from, $record_per_page";
  $result = mysqli_query($con, $sql);
 }
</code>```

<p>-----here have another coding to fetch the data from database</p>

```<code> <?php
$page_result = mysqli_query($con, $sql);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
?>
<ul class="pagination">
      <?php if ($page==1) { ?>
        <li class="disabled"><span aria-hidden="true">«</span></li>
      <?php } else { ?>
        <li><a href=permohonanA.php?page=<?php echo $page-1 ?>" aria-label="Previous"><span aria-hidden="true">«</span></a></li>
      <?php } ?>
       <?php
      for ($i=1; $i<=$total_pages; $i++)
        if ($i == $page)
          echo "<li class=\"active\"><a href=\"permohonanA.php?page=$i\">$i</a></li>";
        else
          echo "<li><a href=\"permohonanA.php?page=$i\">$i</a></li>";
      ?>
      <?php if ($page==$total_pages) { ?>
        <li class="disabled"><span aria-hidden="true">»</span></li>
      <?php } else { ?>
        <li><a href=permohonanA.php?page=<?php echo $page+1 ?>" aria-label="Previous"><span aria-hidden="true">»</span></a></li>
      <?php } ?>
</ul>
</code>```

答:
You can use DataTable with server side configuration.
Sorry it is a bit off topic.
https://datatables.net/examples/server_side/simple.html</p>

Body:
Can someone help me why my '<<' not be in a box. And anyone know how to fix the coding as if i have 20 pages it will be page 1 until 20. I want it to be like ----->  eg: 1 2 3 4 5 ....17 . something like this.

   $record_per_page = 10;
  $page = '';
    if(isset($_GET["page"]))
  {
    $page = $_GET["page"];
  }
    else
  {
    $page = 1;
  }

  $start_from = ($page-1)*$record_per_page;

  $sql = "SELECT id, created, fullname, level, filename, status FROM borang ORDER BY id DESC LIMIT $start_from, $record_per_page";
  $result = mysqli_query($con, $sql);
 }

-----here have another coding to fetch the data from database

 <?php
$page_result = mysqli_query($con, $sql);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
?>

      <?php if ($page==1) { ?>

«

      <?php } else { ?>

<a href=permohonanA.php?page=<?php echo $page-1 ?>" aria-label="Previous">«

      <?php } ?>
       <?php
      for ($i=1; $i<=$total_pages; $i++)
        if ($i == $page)
          echo "
$i
";
        else
          echo "
$i
";
      ?>
      <?php if ($page==$total_pages) { ?>

»

      <?php } else { ?>

<a href=permohonanA.php?page=<?php echo $page+1 ?>" aria-label="Previous">»

      <?php } ?>


问:
pandas between time is not working
I want to filter morning tweets from a 1-month tweet dataset. The column date originally was a timestamp column therefore I converted it to date time, index, and use between time. But it returns an empty data frame. What's wrong?

```<code>import pandas as pd
import matplotlib.pyplot as plt

if __name__ == "__main__":
    df = pd.read_csv('inst.csv',encoding='utf-8')
    df.date = pd.to_datetime(df.date)
    df.set_index(pd.DatetimeIndex(df.date),inplace=True)
    mor = df.between_time('6:00','12:00')
    print(mor)
</code>```

Here's a piece of data

```<code>,X,Unnamed..0,id,owner_id,post_src,caption,likes,comments,date,code,location_id,location_name,location_slug,location_type,postal_code,lat,lng
4,3,3,1.54153890455e+18,27131715,https://scontent.cdninstagram.com/t51.2885-15/e35/19227888_434457730286781_8956364636005859328_n.jpg,"Courage doesn't mean you don't get afraid. Courage means you don't let fear stop you.
•
•
•
•
•
•
•
•
•
#vancouver #bcplace #beautifulday #beautifulbc #explorebc #clouds #sky #city #cityliving #eveningsky #seaside #adventure #bc #instagood #goodvibes #goodtimes #positivevibes #instadaily #instagram #picoftheday #instagold #pictureoftheday #igdaily",5,0,1497985779,BVkpXddDAEC,741066469,Yaletown,yaletown,NA,,49.2757019,-123.1199065
</code>```

答: df.date = pd.to_datetime(df.date,unit='s') unit is by default nanosecond

Title: pandas between time is not working

Body:
I want to filter morning tweets from a 1-month tweet dataset. The column date originally was a timestamp column therefore I converted it to date time, index, and use between time. But it returns an empty data frame. What's wrong?

import pandas as pd
import matplotlib.pyplot as plt

if __name__ == "__main__":
    df = pd.read_csv('inst.csv',encoding='utf-8')
    df.date = pd.to_datetime(df.date)
    df.set_index(pd.DatetimeIndex(df.date),inplace=True)
    mor = df.between_time('6:00','12:00')
    print(mor)

Here's a piece of data

,X,Unnamed..0,id,owner_id,post_src,caption,likes,comments,date,code,location_id,location_name,location_slug,location_type,postal_code,lat,lng
4,3,3,1.54153890455e+18,27131715,https://scontent.cdninstagram.com/t51.2885-15/e35/19227888_434457730286781_8956364636005859328_n.jpg,"Courage doesn't mean you don't get afraid. Courage means you don't let fear stop you.
•
•
•
•
•
•
•
•
•
#vancouver #bcplace #beautifulday #beautifulbc #explorebc #clouds #sky #city #cityliving #eveningsky #seaside #adventure #bc #instagood #goodvibes #goodtimes #positivevibes #instadaily #instagram #picoftheday #instagold #pictureoftheday #igdaily",5,0,1497985779,BVkpXddDAEC,741066469,Yaletown,yaletown,NA,,49.2757019,-123.1199065


问:
Angular 2+ mongoose, let on array doesn't work due to ID object
I am trying to do a let on an array of data that is requested from a mongoose server.
This works if I don't return the ID object with the rest of the Json data.
However I want to add the ID data as params to routernavigate to another component.

Is there an easy way of receiving the id as a string rather then an object?

答:
You can use following to stringify your object data

```<code>JSON.parse(JSON.stringify(''));//use your result object as parameters
</code>```

as a example JSON.parse(JSON.stringify(result['_id']));

Body:
You can use following to stringify your object data

JSON.parse(JSON.stringify(''));//use your result object as parameters

as a example JSON.parse(JSON.stringify(result['_id']));


问:
Openssl libeay32.dll not found troubles when compiling a build CMAKE
Hi I am trying to compile a program for windows using these instructions on github.  I have installed the required dependencies (VS2017, cmake, cuda 8, amd app sdk 3.0).

I have placed the required xmr-stak-dep.zip in my C:/ folder, and the command tree. does line up with what is shown. The files are all accessible.

```<code>  C:\xmr-stak-dep>tree .

  Folder PATH listing for volume Windows
  Volume serial number is XX02-XXXX
  C:\XMR-STAK-DEP
  ├───hwloc
  │   ├───include
  │   │   ├───hwloc
  │   │   │   └───autogen
  │   │   └───private
  │   │       └───autogen
  │   └───lib
  ├───libmicrohttpd
  │   ├───include
  │   └───lib
  └───openssl
      ├───bin
      ├───include
      │   └───openssl
      └───lib
</code>```

The problem is when the program is finally built by running the commands below; when the program is executed I recieve the error  libeay32.dll & ssleay32.dll cannot be found. The command below does show that it did set cmake to that path containing those ddl files.

```<code> "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\Tools\VsMSBuildCmd.bat"

 set CMAKE_PREFIX_PATH=C:\xmr-stak-dep\hwloc;C:\xmr-stak-dep\libmicrohttpd;C:\xmr-stak-dep\openssl

 mkdir build

 cd build
</code>```

I have found this post that does show possibly how to fix this, but I am unsure how I would use the command with my configuration being this is my first time ever compiling a windows program.

As a note, I used the dev branch from here for the source.

答:
There is nothing wrong with your compilation.  It's just that your program depends on those DLLs.  Windows only looks in certain places when trying to find the DLLs that a program depends on.

This article describes how windows looks for DLLs: https://learn.microsoft.com/en-us/cpp/build/search-path-used-by-windows-to-locate-a-dll

The easiest options are to copy the openssl .dlls into the directory alongside your .exe, or to add the directory containing them to your path.  The latter can be done temporarily via set PATH=C:\XMR-STAK-DEP\openssl\lib;%PATH% (presuming the DLLs are under openssl\lib else substitiute openssl\bin)

Body:
Hi I am trying to compile a program for windows using these instructions on github.  I have installed the required dependencies (VS2017, cmake, cuda 8, amd app sdk 3.0).

I have placed the required xmr-stak-dep.zip in my C:/ folder, and the command tree. does line up with what is shown. The files are all accessible.

  C:\xmr-stak-dep>tree .

  Folder PATH listing for volume Windows
  Volume serial number is XX02-XXXX
  C:\XMR-STAK-DEP
  ├───hwloc
  │   ├───include
  │   │   ├───hwloc
  │   │   │   └───autogen
  │   │   └───private
  │   │       └───autogen
  │   └───lib
  ├───libmicrohttpd
  │   ├───include
  │   └───lib
  └───openssl
      ├───bin
      ├───include
      │   └───openssl
      └───lib

The problem is when the program is finally built by running the commands below; when the program is executed I recieve the error  libeay32.dll & ssleay32.dll cannot be found. The command below does show that it did set cmake to that path containing those ddl files.

 "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\Tools\VsMSBuildCmd.bat"

 set CMAKE_PREFIX_PATH=C:\xmr-stak-dep\hwloc;C:\xmr-stak-dep\libmicrohttpd;C:\xmr-stak-dep\openssl

 mkdir build

 cd build

I have found this post that does show possibly how to fix this, but I am unsure how I would use the command with my configuration being this is my first time ever compiling a windows program.

As a note, I used the dev branch from here for the source.


问:
django test a templatetag which uses the request
I'm using a custom templatetag to calculate currency values, currency is chosen from a select element. when the user choose the currency he want work with I save the chosen currency in the session and refresh the page.

a templatetag shows the value calculated for the choosen currency.

in any template

```<code>{% load currency %}
{% set_currency request 156 %}
</code>```

in my_app/templatetags/currency.py

```<code>from django.conf import settings
from djmoney_rates.utils import convert_money
register = template.Library()

@register.inclusion_tag('includes/price.html')
def set_currency(request, price):
    # currency_session could be 'USD', 'EUR' ...
    currency_session = request.session.get(settings.CURRENCY_SESSION_KEY, settings.DEFAULT_CURRENCY)
    money = convert_money(price, settings.DEFAULT_CURRENCY, currency_session)
    return {'amount': '%d' % money.amount, 'currency': money.currency}
</code>```

includes/price.html is just

```<code><span class="amount">{{amount}}</span>
<span class="currency">{{currency}}</span>
</code>```

Now I'm wondering the way to test this templatetag, how to pass the request, and how make session to exists in that request.

答:
I would only test the function.

```<code>from django.test import TestCase, RequestFactory
from django.conf import settings
from my_app.templatetags.currency import set_currency

class SetCurrencyTestCase(TestCase):

    def setUp(self):
        self.factory = RequestFactory()

    def test_set_currency(self):
        request = self.factory.get('/any/path/really/')
        request.session = {
            settings.CURRENCY_SESSION_KEY: settings.DEFAULT_CURRENCY
        }

        response = set_currency(request, 156)

        self.assertEqual(response['amount'], 42)
        self.assertEqual(response['currency'], 'BTC')
</code>```

I'd also consider setting request.session without using settings, but that depends on your application.

Body:
I'm using a custom templatetag to calculate currency values, currency is chosen from a select element. when the user choose the currency he want work with I save the chosen currency in the session and refresh the page.

a templatetag shows the value calculated for the choosen currency.

in any template

{% load currency %}
{% set_currency request 156 %}

in my_app/templatetags/currency.py

from django.conf import settings
from djmoney_rates.utils import convert_money
register = template.Library()

@register.inclusion_tag('includes/price.html')
def set_currency(request, price):
    # currency_session could be 'USD', 'EUR' ...
    currency_session = request.session.get(settings.CURRENCY_SESSION_KEY, settings.DEFAULT_CURRENCY)
    money = convert_money(price, settings.DEFAULT_CURRENCY, currency_session)
    return {'amount': '%d' % money.amount, 'currency': money.currency}

includes/price.html is just

{{amount}}
{{currency}}

Now I'm wondering the way to test this templatetag, how to pass the request, and how make session to exists in that request.

Body:
I would only test the function.

from django.test import TestCase, RequestFactory
from django.conf import settings
from my_app.templatetags.currency import set_currency

class SetCurrencyTestCase(TestCase):

    def setUp(self):
        self.factory = RequestFactory()

    def test_set_currency(self):
        request = self.factory.get('/any/path/really/')
        request.session = {
            settings.CURRENCY_SESSION_KEY: settings.DEFAULT_CURRENCY
        }

        response = set_currency(request, 156)

        self.assertEqual(response['amount'], 42)
        self.assertEqual(response['currency'], 'BTC')

I'd also consider setting request.session without using settings, but that depends on your application.


问:
Get error from my android login using php
i rececntly learn about android and now i'm trying a simple login with my php. Please check my script first

```<code>public class MainActivity extends Activity {

    final Context context = this;
    private Button button;
    private EditText username;
    private EditText passsword;

    ProgressDialog progress;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void GoLogin(View v){

        username   = (EditText)findViewById(R.id.input_email);
        passsword   = (EditText)findViewById(R.id.input_password);

        String usernameval =  username.getText().toString();
        String passswordval =  md5(passsword.getText().toString());
        new AsyncLogin().execute(usernameval,passswordval);
    }

    private class AsyncLogin extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }
        protected String doInBackground(String... params) {
            try {

                url = new URL("http://127.0.0.1:84/fppb/Andro_login");

            } catch (MalformedURLException e) {
                e.printStackTrace();
                return "exception";
            }
            try {
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(10000);
                conn.setRequestMethod("POST");

                conn.setDoInput(true);
                conn.setDoOutput(true);

                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("username", params[0])
                        .appendQueryParameter("password", params[1]);
                String query = builder.build().getEncodedQuery();

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

            } catch (IOException e1) {
                e1.printStackTrace();
                return "exception";
            }

            try {

                int response_code = conn.getResponseCode();

                if (response_code == HttpURLConnection.HTTP_OK) {

                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return(result.toString());

                }else{

                    return("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }

        }
        protected void onPostExecute(String result) {

            pdLoading.dismiss();
            Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
            if(result.equalsIgnoreCase("true"))
            {
                Toast.makeText(MainActivity.this, "Login success", Toast.LENGTH_LONG).show();

            }else if (result.equalsIgnoreCase("false")){

                Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();

            } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

                Toast.makeText(MainActivity.this, "Cannot connect to main server", Toast.LENGTH_LONG).show();

            }
        }
    }

}
</code>```

this is my androidmanifest.xml

```<code>    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
</code>```

when i try to run my app, i get this error

"Cannot connect to main server"

in my toast message after i submit at my form. How can i fix this ? thanks in advance ? sorry bad english

reference http://androidcss.com/android/android-php-mysql-login-tutorial/

after i read my log(s), i see this

```<code>W/System.err: java.net.SocketTimeoutException: failed to connect to /127.0.0.1 (port 84) from /10.0.2.15 (port 51319) after 10000ms
</code>```

答:
Per https://developer.android.com/training/basics/network-ops/connecting.html, you need the android.permission.INTERNET permission as well, i.e.,

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

Also, you will need to put the IP of your computer on the network into the script - 127.0.0.1 is the loopback IP (it connects to the computer it is running on), so since the server isn't running on your phone, it's not able to find the server.

Body:
i rececntly learn about android and now i'm trying a simple login with my php. Please check my script first

public class MainActivity extends Activity {

    final Context context = this;
    private Button button;
    private EditText username;
    private EditText passsword;

    ProgressDialog progress;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void GoLogin(View v){

        username   = (EditText)findViewById(R.id.input_email);
        passsword   = (EditText)findViewById(R.id.input_password);

        String usernameval =  username.getText().toString();
        String passswordval =  md5(passsword.getText().toString());
        new AsyncLogin().execute(usernameval,passswordval);
    }

    private class AsyncLogin extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }
        protected String doInBackground(String... params) {
            try {

                url = new URL("http://127.0.0.1:84/fppb/Andro_login");

            } catch (MalformedURLException e) {
                e.printStackTrace();
                return "exception";
            }
            try {
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(10000);
                conn.setRequestMethod("POST");

                conn.setDoInput(true);
                conn.setDoOutput(true);

                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("username", params[0])
                        .appendQueryParameter("password", params[1]);
                String query = builder.build().getEncodedQuery();

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

            } catch (IOException e1) {
                e1.printStackTrace();
                return "exception";
            }

            try {

                int response_code = conn.getResponseCode();

                if (response_code == HttpURLConnection.HTTP_OK) {

                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return(result.toString());

                }else{

                    return("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }

        }
        protected void onPostExecute(String result) {

            pdLoading.dismiss();
            Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
            if(result.equalsIgnoreCase("true"))
            {
                Toast.makeText(MainActivity.this, "Login success", Toast.LENGTH_LONG).show();

            }else if (result.equalsIgnoreCase("false")){

                Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();

            } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

                Toast.makeText(MainActivity.this, "Cannot connect to main server", Toast.LENGTH_LONG).show();

            }
        }
    }

}

this is my androidmanifest.xml

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"

when i try to run my app, i get this error

"Cannot connect to main server"

in my toast message after i submit at my form. How can i fix this ? thanks in advance ? sorry bad english

reference http://androidcss.com/android/android-php-mysql-login-tutorial/

after i read my log(s), i see this

W/System.err: java.net.SocketTimeoutException: failed to connect to /127.0.0.1 (port 84) from /10.0.2.15 (port 51319) after 10000ms

Body:
Per https://developer.android.com/training/basics/network-ops/connecting.html, you need the android.permission.INTERNET permission as well, i.e.,

<uses-permission android:name="android.permission.INTERNET" />

Also, you will need to put the IP of your computer on the network into the script - 127.0.0.1 is the loopback IP (it connects to the computer it is running on), so since the server isn't running on your phone, it's not able to find the server.


问:
new never fails?
In C++, we usually see and write code like,

```<code>Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}
</code>```

But in C#, I rarely see this: (at least I've never seen this)

```<code>Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}
</code>```

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.

答:
Is this some test code you wrote? If so, I assume that you don't actually keep the reference to the object you created, meaning that the garbage collection will kick in and delete some of the objects you created previously.

That said, you can certainly run out of memory if you allocate enough memory and do keep references to it (at which point an exception will be thrown - a NULL pointer as a return value for memory allocations is more common in C, and in C++ versions written for video game consoles.)

Title: new never fails?

Body:
In C++, we usually see and write code like,

Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}

But in C#, I rarely see this: (at least I've never seen this)

Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.


问:
Matlab Rounding Computation Error
Under Matlab 2014b, when making:

```<code>round((0.1:0.2:1)/0.2)
</code>```

I obtain:

```<code>1 2 3 3 5
</code>```

Instead of

```<code>1 2 3 4 5
</code>```

Is there a way to fix such weird computation? Why this happens? Why so weird? This repeats for other values, not only n=0.2.

EDIT: I checked the duplicate but, do the scenario changes when using ceil so the floating point threshold is not in the half integer (0.5, 1.5, 2.5) but in the integer (1.0, 2.0, 3.0)? What if i use some other representation, like single? Or any other more predictable?

答: since the question got reopened, I'll briefly mention that adding 1.3+0.2 with floats can result in 2.49999999999 or in 2.5000000001 etc. the round will act according to the floating point error.

Title: Matlab Rounding Computation Error

Body:
Under Matlab 2014b, when making:

round((0.1:0.2:1)/0.2)

I obtain:

1 2 3 3 5

Instead of

1 2 3 4 5

Is there a way to fix such weird computation? Why this happens? Why so weird? This repeats for other values, not only n=0.2.

EDIT: I checked the duplicate but, do the scenario changes when using ceil so the floating point threshold is not in the half integer (0.5, 1.5, 2.5) but in the integer (1.0, 2.0, 3.0)? What if i use some other representation, like single? Or any other more predictable?


问:
Changing mvc form controller on submit
I recently came upon this question as I have a solution I need to work on.

I have a controller which does some logic, with some method:

```<code>   public Controller1: MvcController
   {
     public ActionResult SomeLogic(Model model)
     {
       return view();
     }
     public ActionResult SomeLogic2(Model model)
     {
       return view();
     }
  }
</code>```

And I have a second controller which does different logic:

```<code>   public Controller2: MvcController
   {
     public ActionResult SomeLogic(Model model)
     {
       return view();
     }
     public ActionResult SomeLogic2(Model model)
     {
       return view();
     }
  }
</code>```

Both are working on the same view:

```<code>MyView.cshtml
</code>```

The view contains a begin form that works on submit:

```<code>@using(Html.BeginForm("SomeLogic", "Controller1", FormMethod.Post)
</code>```

and 4 submit buttons:

```<code><input type='submit' formaction='SomeLogic' value='submit' />
<input type='submit' formaction='SomeLogic2' value='submit2' />
<input type='submit' formaction='SomeLogic' value='submit3' />
<input type='submit' formaction='SomeLogic2' value='submit4' />
</code>```

I know I can control the action to which I am redirecting the submit using the:
formaction attribute.

I there a way to change the controller as well? meaning that:

```<code><input type='submit' formaction='SomeLogic' value='submit3' />
<input type='submit' formaction='SomeLogic2' value='submit4' />
</code>```

Will submit to controller2 instead of Controller1 which is defined in my begin form.

This will solve my debate whether to create a new controller or use the existing one, which is already full of complex logic.

答:
You need to include controller name in the formaction attribute.

Note that your controller names are not valid, but assuming your have

```<code>public FirstController: Controller
{
    [HttpPost]
    public ActionResult SomeLogic(Model model)
    {
        return view();
    }
}
public SecondController: Controller
{
    [HttpPost]
    public ActionResult SomeLogic(Model model)
    {
        return view();
    }
}
</code>```

Then you can post to the correct controller using

```<code>// Post to the SomeLogic method of FirstController
<input type="submit" formaction="@Url.Action("SomeLogic", "First")" value="submit" />
// Post to the SomeLogic method of SecondController
<input type="submit" formaction="@Url.Action("SomeLogic", "Second")" value="submit3" />
</code>```

Title: Changing mvc form controller on submit

Body:
I recently came upon this question as I have a solution I need to work on.

I have a controller which does some logic, with some method:

   public Controller1: MvcController
   {
     public ActionResult SomeLogic(Model model)
     {
       return view();
     }
     public ActionResult SomeLogic2(Model model)
     {
       return view();
     }
  }

And I have a second controller which does different logic:

   public Controller2: MvcController
   {
     public ActionResult SomeLogic(Model model)
     {
       return view();
     }
     public ActionResult SomeLogic2(Model model)
     {
       return view();
     }
  }

Both are working on the same view:

MyView.cshtml

The view contains a begin form that works on submit:

@using(Html.BeginForm("SomeLogic", "Controller1", FormMethod.Post)

and 4 submit buttons:

<input type='submit' formaction='SomeLogic' value='submit' />
<input type='submit' formaction='SomeLogic2' value='submit2' />
<input type='submit' formaction='SomeLogic' value='submit3' />
<input type='submit' formaction='SomeLogic2' value='submit4' />

I know I can control the action to which I am redirecting the submit using the:
formaction attribute.

I there a way to change the controller as well? meaning that:

<input type='submit' formaction='SomeLogic' value='submit3' />
<input type='submit' formaction='SomeLogic2' value='submit4' />

Will submit to controller2 instead of Controller1 which is defined in my begin form.

This will solve my debate whether to create a new controller or use the existing one, which is already full of complex logic.

Body:
You need to include controller name in the formaction attribute.

Note that your controller names are not valid, but assuming your have

public FirstController: Controller
{
    [HttpPost]
    public ActionResult SomeLogic(Model model)
    {
        return view();
    }
}
public SecondController: Controller
{
    [HttpPost]
    public ActionResult SomeLogic(Model model)
    {
        return view();
    }
}

Then you can post to the correct controller using

// Post to the SomeLogic method of FirstController
<input type="submit" formaction="@Url.Action("SomeLogic", "First")" value="submit" />
// Post to the SomeLogic method of SecondController
<input type="submit" formaction="@Url.Action("SomeLogic", "Second")" value="submit3" />


问:
Django: Cannout update model through form POST, only Shell
What are you trying to accomplish? (Please include sample data.)

I am trying to create a form in Django that takes in data and saves them in a database.

Paste the part of the code that shows the problem. (Please indent 4 spaces.)

index4.html

```<code>    <form action="post_url/" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Submit" />
    </form>
</code>```

urls.py (project folder)

```<code>from django.conf.urls import url
from django.contrib import admin
from exercises.views import *

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^numbers/', numbers, name="numbers"),
    url(r'^about/', about, name="about"),
    url(r'^post_url/$', post_treasure, name='post_treasure')
]
</code>```

views.py

```<code>from django.shortcuts import render
from django.http import HttpResponse
from .models import Treasure
from .forms import TreasureForm

def numbers(request):
    treasures = Treasure.objects.all()
    form = TreasureForm()
    return render(request, 'index4.html', {'treasures': treasures, 'form':form})

def about(request):
    return render(request, "about.html", {})

def q1(request):
    return HttpResponse("What is the average age of a dinosaur?")

def post_treasure(request):
    form = TreasureForm(request.POST)
    if form.is_valid():
        treasure = Treasure(name = form.cleaned_data['name'],
                            value = form.cleaned_data['value'],
                            material = form.cleaned_data['material'],
                            location = form.cleaned_data['location'],
                            img_url = form.cleaned_data['img_url'])
        treasure.save()
    return HttpResponseRedirect('/')
</code>```

forms.py

```<code>from django import forms
from .models import Treasure

# class TreasureForm(forms.ModelForm):
#   class Meta:
#       model = Treasure
#       fields = ['name', 'value', 'location', 'material']
#       if form.is_valid():
#           form.save(commit = True)
#       return HttpResponseRedirect('/')

class TreasureForm(forms.Form):
    name = forms.CharField(label='Name', max_length=100)
    value = forms.DecimalField(label='Value', max_digits=10, decimal_places=2)
    material = forms.CharField(label='Material', max_length=100)
    location = forms.CharField(label='Location', max_length=100)
    img_url = forms.CharField(label='Image URL', max_length=100)
</code>```

models.py

```<code>from django.db import models

class Treasure(models.Model):
    name = models.CharField(max_length=100)
    value = models.DecimalField(max_digits=10, decimal_places=2)
    material = models.CharField(max_length=100)
    location = models.CharField(max_length=100)
    img_url = models.CharField(max_length=100)
</code>```

What do you expect the result to be? && What is the actual result you get? (Please include any errors.)
After filling in the form, I expected the Treasure model class to contain a new Treasure object. This does not occur if I confirm it using the python shell, but also through the list of treasures on the index4.html template. The only way this works is if I manually add a Treasure using the python shell

Errors: N/A, program compiles successfully

答:
Change your form action in index.html to:

```<code><form action="{% url 'post_treasure' %}" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>
</code>```

You should also consider going back to the modelform you were using. It's a better way to do this.

Body:
What are you trying to accomplish? (Please include sample data.)

I am trying to create a form in Django that takes in data and saves them in a database.

Paste the part of the code that shows the problem. (Please indent 4 spaces.)

index4.html

    <form action="post_url/" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Submit" />
    </form>

urls.py (project folder)

from django.conf.urls import url
from django.contrib import admin
from exercises.views import *

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^numbers/', numbers, name="numbers"),
    url(r'^about/', about, name="about"),
    url(r'^post_url/$', post_treasure, name='post_treasure')
]

views.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import Treasure
from .forms import TreasureForm

def numbers(request):
    treasures = Treasure.objects.all()
    form = TreasureForm()
    return render(request, 'index4.html', {'treasures': treasures, 'form':form})

def about(request):
    return render(request, "about.html", {})

def q1(request):
    return HttpResponse("What is the average age of a dinosaur?")

def post_treasure(request):
    form = TreasureForm(request.POST)
    if form.is_valid():
        treasure = Treasure(name = form.cleaned_data['name'],
                            value = form.cleaned_data['value'],
                            material = form.cleaned_data['material'],
                            location = form.cleaned_data['location'],
                            img_url = form.cleaned_data['img_url'])
        treasure.save()
    return HttpResponseRedirect('/')

forms.py

from django import forms
from .models import Treasure

# class TreasureForm(forms.ModelForm):
#   class Meta:
#       model = Treasure
#       fields = ['name', 'value', 'location', 'material']
#       if form.is_valid():
#           form.save(commit = True)
#       return HttpResponseRedirect('/')

class TreasureForm(forms.Form):
    name = forms.CharField(label='Name', max_length=100)
    value = forms.DecimalField(label='Value', max_digits=10, decimal_places=2)
    material = forms.CharField(label='Material', max_length=100)
    location = forms.CharField(label='Location', max_length=100)
    img_url = forms.CharField(label='Image URL', max_length=100)

models.py

from django.db import models

class Treasure(models.Model):
    name = models.CharField(max_length=100)
    value = models.DecimalField(max_digits=10, decimal_places=2)
    material = models.CharField(max_length=100)
    location = models.CharField(max_length=100)
    img_url = models.CharField(max_length=100)

What do you expect the result to be? && What is the actual result you get? (Please include any errors.)
After filling in the form, I expected the Treasure model class to contain a new Treasure object. This does not occur if I confirm it using the python shell, but also through the list of treasures on the index4.html template. The only way this works is if I manually add a Treasure using the python shell

Errors: N/A, program compiles successfully

Body:
Change your form action in index.html to:

<form action="{% url 'post_treasure' %}" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

You should also consider going back to the modelform you were using. It's a better way to do this.


问:
OpenCV Error: Assertion
```<code>Mat m1 = Mat(500, 300, CV_64F, Vec3b(255,255,255));
  for (int i = 0; i < m1.rows; ++i)
    for (int j = 0; j < m1.cols; ++j)
    {
        Vec3b color=m1.at<Vec3b>(Point(i, j));
    }
imshow("test2", m1);
waitKey();
</code>```

The variable color should contain the color of the pixel which is white but i when i run the code i get the error:

OpenCV Error: Assertion failed (((((sizeof(size_t)<<28)|0x8442211) >>
  ((traits::Depth<_Tp>::value) & ((1 << 3) - 1))*4) & 15) ==
  elemSize1()) in cv::Mat::at, file
  c:\opencv\build\include\opencv2\core\mat.inl.hpp, line 1118

答:
The error message is telling you what you need to know. You've gone out of bounds!

Try:

```<code>Point(j, i)
</code>```

Columns correspond to x. Rows correspond to y.

Title: OpenCV Error: Assertion

Body:
Mat m1 = Mat(500, 300, CV_64F, Vec3b(255,255,255));
  for (int i = 0; i < m1.rows; ++i)
    for (int j = 0; j < m1.cols; ++j)
    {
        Vec3b color=m1.at<Vec3b>(Point(i, j));
    }
imshow("test2", m1);
waitKey();

The variable color should contain the color of the pixel which is white but i when i run the code i get the error:

OpenCV Error: Assertion failed (((((sizeof(size_t)<<28)|0x8442211) >>
  ((traits::Depth<_Tp>::value) & ((1 << 3) - 1))*4) & 15) ==
  elemSize1()) in cv::Mat::at, file
  c:\opencv\build\include\opencv2\core\mat.inl.hpp, line 1118

Body:
The error message is telling you what you need to know. You've gone out of bounds!

Try:

Point(j, i)

Columns correspond to x. Rows correspond to y.