问:
When I try running this class in eclipse, another class gets executed
I have this class called deepToe_2. Whenever I click on the shortcut key for run, eclipse runs another class called TicTacToe which I had previously ran.
I have tried making changes to run cofig but it still does not seem to work.
Here is my code :</p>

```<code>package deepToe;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
import deepToe.deepToe_2.buttonListener;

public class deepToe_2 extends JPanel {

JButton buttons[] = new JButton[9];
int alternate = 0;
String MotherBoard[] = {"","","","","","","","",""};
String board[];

public static void main(String[] args) {

    JFrame window = new JFrame("Tic Tac Toe");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().add(new TicTacToe());
    window.setBounds(300,200,300,300);
    window.setVisible(true);
}

public deepToe_2()
{
  setLayout(new GridLayout(3,3));
  initializebuttons();
  toss();
}

public void toss(){
    Random ran = new Random();
    int r = ran.nextInt(2);
    if(r == 1){
        JOptionPane.showMessageDialog(null, "deepToe goes First.");
        alternate++;
        deepToe();
    }
    else {
        JOptionPane.showMessageDialog(null, "deepToe goes First.");
        alternate++;
        deepToe();
    }
}

public void deepToe() {
    if(alternate == 1) {
        buttons[4].setText("O");
    }else {
        int moves[] = {-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000};
        for(int i = 0; i < 9; i++) {
            board = MotherBoard;
            if(board[i] == "") {
                board[i] = "O";
                moves[i] = evaluateBoard();
            }
        }
        int high = -999, final_move = -1;
        for(int j = 0; j < 9; j++) {
            if(moves[j] > high){
                high = moves[j];
                final_move = j;
            }
        }
        buttons[final_move].setText("O");
    }
    updateMotherBoard();
    if(!(checkResults())) alternate++;
}

public int evaluateBoard() {
    int x = 0;
    if(canSomeoneWin("O") != -1) x += 2;
    if(canSomeoneWin("X") != -1) x -= 2;
    return x;
}

public void updateMotherBoard() {
    for(int i = 0; i < 9; i++) {
        MotherBoard[i] = buttons[i].getText();
    }
}

public int canSomeoneWin(String c) {
    int x = 0, y = 1, z = 2;
    for(int j = 0; j < 3; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x += 3;
        y += 3;
        z += 3;
    }
    x = 0; y = 3; z = 6;
    for(int j = 0; j < 3; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x++;
        y++;
        z++;
    }
    x = 0; y = 4; z = 8;
    for(int j = 0; j < 2; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x = 2; z = 6;
    }
    return -1;

}

public void initializebuttons()
{
    for(int i = 0; i <= 8; i++)
    {
        buttons[i] = new JButton();
        buttons[i].setText("");
        buttons[i].addActionListener(new buttonListener());

        add(buttons[i]);
    }
    buttons[5].setText("X");

}

public class buttonListener implements ActionListener
{

    public void actionPerformed(ActionEvent e)
    {

        JButton buttonClicked = (JButton)e.getSource();

        if((alternate%2 == 0)&&(buttonClicked.getText().equals(""))){
            buttonClicked.setText("X");
            updateMotherBoard();
            if(!(checkResults())) {
                alternate++;
                deepToe();
            }
        }

    }
}

    public boolean checkResults(){
        if(checkForWin())
        {
            if(alternate%2 == 0)
                JOptionPane.showConfirmDialog(null, "Human wins. Great Job!!!");
            else
                JOptionPane.showConfirmDialog(null, "deepToe wins.");
            return true;
        }else{
            if(checkForDraw()){
                JOptionPane.showConfirmDialog(null, "Draw. Good game.");
                return true;
            }
        }
        return false;

    }

    public boolean checkForDraw() {
        boolean yes = true;
        for(int j = 0; j < 9; j++){
            if(buttons[j].getText().equals("")) yes = false;
        }
        return yes;
    }

    public boolean checkForWin()
    {
        if( checkAdjacent(0,1) && checkAdjacent(1,2) ) //no need to put " == true" because the default check is for true
            return true;
        else if( checkAdjacent(3,4) && checkAdjacent(4,5) )
            return true;
        else if ( checkAdjacent(6,7) && checkAdjacent(7,8))
            return true;
        else if ( checkAdjacent(0,3) && checkAdjacent(3,6))
            return true;
        else if ( checkAdjacent(1,4) && checkAdjacent(4,7))
            return true;
        else if ( checkAdjacent(2,5) && checkAdjacent(5,8))
            return true;
        else if ( checkAdjacent(0,4) && checkAdjacent(4,8))
            return true;
        else if ( checkAdjacent(2,4) && checkAdjacent(4,6))
            return true;
        else
            return false;

    }

    public boolean checkAdjacent(int a, int b)
    {
        if ( buttons[a].getText().equals(buttons[b].getText()) && !buttons[a].getText().equals("") )
            return true;
        else
            return false;
    }

}
</code>```

答:
you need just to double click your class and then run the program from where ever you want. you can right click as suggested by kkflf or run it from shortcut key as you used to do.
Hope this will help.</p>

Body:
I have this class called deepToe_2. Whenever I click on the shortcut key for run, eclipse runs another class called TicTacToe which I had previously ran.
I have tried making changes to run cofig but it still does not seem to work.
Here is my code :

package deepToe;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
import deepToe.deepToe_2.buttonListener;

public class deepToe_2 extends JPanel {

JButton buttons[] = new JButton[9];
int alternate = 0;
String MotherBoard[] = {"","","","","","","","",""};
String board[];

public static void main(String[] args) {

    JFrame window = new JFrame("Tic Tac Toe");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().add(new TicTacToe());
    window.setBounds(300,200,300,300);
    window.setVisible(true);
}

public deepToe_2()
{
  setLayout(new GridLayout(3,3));
  initializebuttons();
  toss();
}

public void toss(){
    Random ran = new Random();
    int r = ran.nextInt(2);
    if(r == 1){
        JOptionPane.showMessageDialog(null, "deepToe goes First.");
        alternate++;
        deepToe();
    }
    else {
        JOptionPane.showMessageDialog(null, "deepToe goes First.");
        alternate++;
        deepToe();
    }
}

public void deepToe() {
    if(alternate == 1) {
        buttons[4].setText("O");
    }else {
        int moves[] = {-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000};
        for(int i = 0; i < 9; i++) {
            board = MotherBoard;
            if(board[i] == "") {
                board[i] = "O";
                moves[i] = evaluateBoard();
            }
        }
        int high = -999, final_move = -1;
        for(int j = 0; j < 9; j++) {
            if(moves[j] > high){
                high = moves[j];
                final_move = j;
            }
        }
        buttons[final_move].setText("O");
    }
    updateMotherBoard();
    if(!(checkResults())) alternate++;
}

public int evaluateBoard() {
    int x = 0;
    if(canSomeoneWin("O") != -1) x += 2;
    if(canSomeoneWin("X") != -1) x -= 2;
    return x;
}

public void updateMotherBoard() {
    for(int i = 0; i < 9; i++) {
        MotherBoard[i] = buttons[i].getText();
    }
}

public int canSomeoneWin(String c) {
    int x = 0, y = 1, z = 2;
    for(int j = 0; j < 3; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x += 3;
        y += 3;
        z += 3;
    }
    x = 0; y = 3; z = 6;
    for(int j = 0; j < 3; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x++;
        y++;
        z++;
    }
    x = 0; y = 4; z = 8;
    for(int j = 0; j < 2; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x = 2; z = 6;
    }
    return -1;

}

public void initializebuttons()
{
    for(int i = 0; i <= 8; i++)
    {
        buttons[i] = new JButton();
        buttons[i].setText("");
        buttons[i].addActionListener(new buttonListener());

        add(buttons[i]);
    }
    buttons[5].setText("X");

}

public class buttonListener implements ActionListener
{

    public void actionPerformed(ActionEvent e)
    {

        JButton buttonClicked = (JButton)e.getSource();

        if((alternate%2 == 0)&&(buttonClicked.getText().equals(""))){
            buttonClicked.setText("X");
            updateMotherBoard();
            if(!(checkResults())) {
                alternate++;
                deepToe();
            }
        }

    }
}

    public boolean checkResults(){
        if(checkForWin())
        {
            if(alternate%2 == 0)
                JOptionPane.showConfirmDialog(null, "Human wins. Great Job!!!");
            else
                JOptionPane.showConfirmDialog(null, "deepToe wins.");
            return true;
        }else{
            if(checkForDraw()){
                JOptionPane.showConfirmDialog(null, "Draw. Good game.");
                return true;
            }
        }
        return false;

    }

    public boolean checkForDraw() {
        boolean yes = true;
        for(int j = 0; j < 9; j++){
            if(buttons[j].getText().equals("")) yes = false;
        }
        return yes;
    }

    public boolean checkForWin()
    {
        if( checkAdjacent(0,1) && checkAdjacent(1,2) ) //no need to put " == true" because the default check is for true
            return true;
        else if( checkAdjacent(3,4) && checkAdjacent(4,5) )
            return true;
        else if ( checkAdjacent(6,7) && checkAdjacent(7,8))
            return true;
        else if ( checkAdjacent(0,3) && checkAdjacent(3,6))
            return true;
        else if ( checkAdjacent(1,4) && checkAdjacent(4,7))
            return true;
        else if ( checkAdjacent(2,5) && checkAdjacent(5,8))
            return true;
        else if ( checkAdjacent(0,4) && checkAdjacent(4,8))
            return true;
        else if ( checkAdjacent(2,4) && checkAdjacent(4,6))
            return true;
        else
            return false;

    }

    public boolean checkAdjacent(int a, int b)
    {
        if ( buttons[a].getText().equals(buttons[b].getText()) && !buttons[a].getText().equals("") )
            return true;
        else
            return false;
    }

}


来源: stackexchange

问:
Cmake did not use C++11 flag using CXX_STANDARD?
I'm fairly new to cmake and I'm trying to use the mongodb driver for C++ by using this tutorial: https://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/tutorial/. The tutorial says you need C++11, so I tried the recommended way which is using CXX_STANDARD property. But it didn't work. I finally gave up and used add_definitions() and it worked!

The cmake file shows both approaches I tried. ie, add_definitions and the set property approach in the comment (which I tried first but failed to work).

It works with add_definitions() now, but everywhere I turn people recommend using CXX_STANDARD or let cmake use C++11 automatically by requesting a C++11 feature.

So, will this be a problem later on for some reason? And why didn't it work the first time around?

My cmake file:

```<code>cmake_minimum_required(VERSION 3.2)

project(testproj CXX)

file(GLOB SRC src/*.cpp)

add_library(testproj SHARED ${SRC})

add_definitions(--std=c++11)
#set(TARGET testproj PROPERTY CXX_STANDARD 11)
#set(TARGET testproj PROPERTY CXX_STANDARD_REQUIRED ON)

# include directories
include_directories(/usr/local/include/mongocxx/v_noabi)
include_directories(/usr/local/include/libmongoc-1.0)
include_directories(/usr/local/include/bsoncxx/v_noabi)
include_directories(/usr/local/include/libbson-1.0)

# library path
link_directories(/usr/local/lib)
target_link_libraries(testproj mongocxx bsoncxx)
</code>```

答:
It would be better to define the c++11 flag to the whole project.

To do so, you can use the variable CMAKE_CXX_FLAGS to set it as a global flag, like this :

```<code>set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
</code>```

Since it´s a global call, I recommand you to put it just beneath the project line.

ContentLicense: CC BY-SA 3.0

Body:
I'm fairly new to cmake and I'm trying to use the mongodb driver for C++ by using this tutorial: https://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/tutorial/. The tutorial says you need C++11, so I tried the recommended way which is using CXX_STANDARD property. But it didn't work. I finally gave up and used add_definitions() and it worked!

The cmake file shows both approaches I tried. ie, add_definitions and the set property approach in the comment (which I tried first but failed to work).

It works with add_definitions() now, but everywhere I turn people recommend using CXX_STANDARD or let cmake use C++11 automatically by requesting a C++11 feature.

So, will this be a problem later on for some reason? And why didn't it work the first time around?

My cmake file:

cmake_minimum_required(VERSION 3.2)

project(testproj CXX)

file(GLOB SRC src/*.cpp)

add_library(testproj SHARED ${SRC})

add_definitions(--std=c++11)
#set(TARGET testproj PROPERTY CXX_STANDARD 11)
#set(TARGET testproj PROPERTY CXX_STANDARD_REQUIRED ON)

# include directories
include_directories(/usr/local/include/mongocxx/v_noabi)
include_directories(/usr/local/include/libmongoc-1.0)
include_directories(/usr/local/include/bsoncxx/v_noabi)
include_directories(/usr/local/include/libbson-1.0)

# library path
link_directories(/usr/local/lib)
target_link_libraries(testproj mongocxx bsoncxx)

Body:
It would be better to define the c++11 flag to the whole project.

To do so, you can use the variable CMAKE_CXX_FLAGS to set it as a global flag, like this :

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

Since it´s a global call, I recommand you to put it just beneath the project line.


问:
How to include buttons and map their events within a ListBox?
I have a concept question on how to have a dynamic list displayed by a list box. Within the list box, the items are held within a Stackpanel. Within the stack panel is a string and a button. If I click that button, that entity / item (both the button and the string) is removed from the list box.

1) How do I create new buttons based on the number of entities in the list?

2) How do I connect the idea that this button is related to this item in the listbox?

3) Is this even possible with binding?

Sorry, I am still new to WPF but starting to see that it is quite powerful.

If you can also provide a brief / short example, or direct me to a link that is similar to this, it would be greatly appreciated. Thanks so much! :)

答:
I guess you'll need to change the control template and or the content template of the control. Have a look at the following links
http://mark-dot-net.blogspot.com/2007/07/creating-custom-wpf-button-template-in.html http://msdn.microsoft.com/en-us/magazine/cc163497.aspx

Hope this helps.

ContentLicense: CC BY-SA 2.5


问:
How does java optimisation? Example code
Consider this small class:

```<code>public class Example {
  public int plus(int a){
    int b;
    b = 1;
    return b+a;
  }
}
</code>```

javap says:

```<code>public int plus(int);
  descriptor: (I)I
  flags: ACC_PUBLIC
  Code:
    stack=2, locals=3, args_size=2
     0: iconst_1
     1: istore_2
     2: iload_2
     3: iload_1
     4: iadd
     5: ireturn
  LineNumberTable:
    line 4: 0
    line 5: 2
</code>```

I don't understand why we need line 1&2?

I heard that the Java Runtime environment counts function calls and compiles functions if they exceed a certain number of calls.

Does that mean that the Java compiler leaves all optimisation to the byte code compiler? E.g. Java programs start slow and become faster by time?

Please explain!

答:
First of all, you are looking at the output of the bytecode compiler.  Typical Java bytecode compilers do very little optimization.  The heavy-weight optimization is done by the JIT compiler ... at runtime.

So what you see displayed by javap -c is unoptimized bytecodes.

I don't understand why we need line 1&2?

You are looking at unoptimized bytecodes.  The first 2 instructions assign 1 to the local variable b.  We can see that the local variable could easily be optimized away.  However the bytecode compler (javac) doesn't bother.

I heard that the Java Runtime environment counts function calls and compiles functions if they exceed a certain number of calls.

That's how a typical Hotspot JVM works.

Does that mean that the Java compiler leaves all optimisation to the byte code compiler?

No.  It is the JIT compiler that does the runtime compilation and the associated optimization.

The bytecode compiler compiles Java source code to bytecodes.  The JIT compiler compiles bytecodes to native code ... at runtime.

E.g. Java programs start slow and become faster by time?

That is correct.  The initial bytecode interpretation phase and the JIT compilation are part of what is referred to as "JVM warmup".

(As requested ...)

The reasons that the bytecode compiler doesn't optimize include:

because the JIT compiler does optimize (so it would be wasted effort),

because optimizing the bytecodes could make it harder to optimize in the JIT compiler ("clever" code is harder to optimize than simple code), and

because non-optimized byte codes make it easier for a profiler or debugger to relate code back to source code lines.

And the reasons the the JIT compiler does the optimization include:

because it needs to be done in the step that generates native code to achieve best results,

because it is platform dependent (e.g. the optimal code depends on the target instruction set, and potentially on things like memory cache sizes, number of cores and so on), and

because it allow you to optimize based on the observed behavior of the code as it is executing (e.g. improved branch prediction).

Finally, JIT compilation fits in well with Java's late binding model.

Body:
Consider this small class:

public class Example {
  public int plus(int a){
    int b;
    b = 1;
    return b+a;
  }
}

javap says:

public int plus(int);
  descriptor: (I)I
  flags: ACC_PUBLIC
  Code:
    stack=2, locals=3, args_size=2
     0: iconst_1
     1: istore_2
     2: iload_2
     3: iload_1
     4: iadd
     5: ireturn
  LineNumberTable:
    line 4: 0
    line 5: 2

I don't understand why we need line 1&2?

I heard that the Java Runtime environment counts function calls and compiles functions if they exceed a certain number of calls.

Does that mean that the Java compiler leaves all optimisation to the byte code compiler? E.g. Java programs start slow and become faster by time?

Please explain!


问:
Change value column based on condition
I have a dataframe df with a column that has values ranged between 0 and 1.

I would like to change the values from numerical to ordinal as follows:

```<code>'0-20'  for x <= 0.2
'20-40'  for 0.2 < x <= 0.4
'40-60'  for 0.4 < x <= 0.6
'60-80'  for 0.6 < x <= 0.8
'80-100'  for 0.8 < x <= 1
 I've passed X['Probability'].loc[X['Probability'] <= 0.2] = '0-20'
</code>```

But on next one I get an error saying:

TypeError: unorderable types: str() > float().

How to get pass this ? Thanks !

Title: Change value column based on condition

Body:
I have a dataframe df with a column that has values ranged between 0 and 1.

I would like to change the values from numerical to ordinal as follows:

'0-20'  for x <= 0.2
'20-40'  for 0.2 < x <= 0.4
'40-60'  for 0.4 < x <= 0.6
'60-80'  for 0.6 < x <= 0.8
'80-100'  for 0.8 < x <= 1
 I've passed X['Probability'].loc[X['Probability'] <= 0.2] = '0-20'

But on next one I get an error saying:

TypeError: unorderable types: str() > float().

How to get pass this ? Thanks !

Body:
You can use cut:

bins = [-np.inf, .2, .4, .6, .8, 1]
labels = ["{0} - {1}".format(i, i + 20) for i in range(0, 100, 20)]
#same as
#labels=['0-20','20-40','40-60','60-80','80-100']

df['label'] = pd.cut(df['Probability'], bins=bins, labels=labels)

Sample:

np.random.seed(100)
df = pd.DataFrame(np.random.random((10,1)), columns=['Probability'])
df.loc[0, 'Probability'] = 0
df.loc[8, 'Probability'] = 0.4
df.loc[9, 'Probability'] = 1

bins = [-np.inf, .2, .4, .6, .8, 1]
labels = ["{0} - {1}".format(i, i + 20) for i in range(0, 100, 20)]
df['label'] = pd.cut(df['Probability'], bins=bins, labels=labels)
print (df)
   Probability   label
0     0.000000    0-20
1     0.278369   20-40
2     0.424518   40-60
3     0.844776  80-100
4     0.004719    0-20
5     0.121569    0-20
6     0.670749   60-80
7     0.825853  80-100
8     0.400000   20-40
9     1.000000  80-100


问:
Grok parse error while trying to parse kafka logs
I'm getting a logstash grok parse failure that I can't seem to figure out...

The input looks like this:

```<code>"@timestamp" => 2017-03-30T13:03:41.899Z,
 "tst_field" => "test123avc",
  "@version" => "1",
   "message" => "[group-consumer-master,message-qa,8]::[OffsetMetadata[2,NO_METADATA],CommitTime 1490878047368,ExpirationTime 1490964447368]",
      "tags" => [
    [0] "_grokparsefailure"
]
</code>```

and I've tried the filter part like this:

```<code>filter{
        grok {
                match => {"meessage" => [
                                "\[%{DATA:kafka_consumer_group},%{DATA:kafka_topic},%{NUMBER:kafka_topic_parition}\]::\[OffsetMetadata\[%{NUMBER:kafka_offset_group},%{DATA:message_metadata}\],CommitTime %{NUMBER:commit_time},ExpirationTime %{NUMBER:expiration_time}\]"
                                ]
                         }
        }
}
</code>```

but I keep getting a grok parse error. I've tried this in http://grokdebug.herokuapp.com/ and it seems to work...

here is the error I get in the log file

```<code>Error parsing json {:source=>"message", :raw=>"[group-consumer-master,message-qa,8]::[OffsetMetadata[2,NO_METADATA],CommitTime 1490878047368,ExpirationTime 1490964447368]", :exception=>#<LogStash::Json::ParserError: Unrecognized token 'group': was expecting ('true', 'false' or 'null')
</code>```

----EDIT-------

here is the full config:

```<code>input {
        kafka {
                topics => ["kafka-offsets"]
                bootstrap_servers => "kafka1.domain.com:9092"
                group_id => "logstash_offsets_parser3"
        }

}
filter{
        grok {
                match => {"meessage" => "\[%{DATA:kafka_consumer_group},%{DATA:kafka_topic},%{NUMBER:kafka_topic_parition}\]\:\:\[OffsetMetadata\[%{NUMBER:kafka_offset_group},%{DATA:message_metadata}\],CommitTime\ %{NUMBER:commit_time},ExpirationTime\ %{NUMBER:expiration_time}\]"
                         }
        }
}
output {
  stdout { codec => "rubydebug" }
}
</code>```

--EDIT-----

I spelled message wrong...I spelled in meessage....changed it to message and now its working....

答:
The error message says this:

Error parsing json {:source=>"message" ...

That strongly suggests that somewhere in your filtering pipeline, you have a block that looks like this.

```<code>json {
  source => "message"
}
</code>```

The message field you quoted at the top is not JSON formatted. I suggest you review the conditionals surrounding your json {} block, wherever it is, and make sure that this particular event never hits it.

The grokparsefailure message can be generated by any grok block you have. Check the conditionals around others as well, to ensure this event doesn't hit those inappropriately. If you want to make sure that this grok-block is the one that's failing parsing, I suggest setting tag_on_failure to something unique to that block, to be sure this is the one generating it.

ContentLicense: CC BY-SA 4.0

Body:
I'm getting a logstash grok parse failure that I can't seem to figure out...

The input looks like this:

"@timestamp" => 2017-03-30T13:03:41.899Z,
 "tst_field" => "test123avc",
  "@version" => "1",
   "message" => "[group-consumer-master,message-qa,8]::[OffsetMetadata[2,NO_METADATA],CommitTime 1490878047368,ExpirationTime 1490964447368]",
      "tags" => [
    [0] "_grokparsefailure"
]

and I've tried the filter part like this:

filter{
        grok {
                match => {"meessage" => [
                                "\[%{DATA:kafka_consumer_group},%{DATA:kafka_topic},%{NUMBER:kafka_topic_parition}\]::\[OffsetMetadata\[%{NUMBER:kafka_offset_group},%{DATA:message_metadata}\],CommitTime %{NUMBER:commit_time},ExpirationTime %{NUMBER:expiration_time}\]"
                                ]
                         }
        }
}

but I keep getting a grok parse error. I've tried this in http://grokdebug.herokuapp.com/ and it seems to work...

here is the error I get in the log file

Error parsing json {:source=>"message", :raw=>"[group-consumer-master,message-qa,8]::[OffsetMetadata[2,NO_METADATA],CommitTime 1490878047368,ExpirationTime 1490964447368]", :exception=>#<LogStash::Json::ParserError: Unrecognized token 'group': was expecting ('true', 'false' or 'null')

----EDIT-------

here is the full config:

input {
        kafka {
                topics => ["kafka-offsets"]
                bootstrap_servers => "kafka1.domain.com:9092"
                group_id => "logstash_offsets_parser3"
        }

}
filter{
        grok {
                match => {"meessage" => "\[%{DATA:kafka_consumer_group},%{DATA:kafka_topic},%{NUMBER:kafka_topic_parition}\]\:\:\[OffsetMetadata\[%{NUMBER:kafka_offset_group},%{DATA:message_metadata}\],CommitTime\ %{NUMBER:commit_time},ExpirationTime\ %{NUMBER:expiration_time}\]"
                         }
        }
}
output {
  stdout { codec => "rubydebug" }
}

--EDIT-----

I spelled message wrong...I spelled in meessage....changed it to message and now its working....

Body:
The error message says this:

Error parsing json {:source=>"message" ...

That strongly suggests that somewhere in your filtering pipeline, you have a block that looks like this.

json {
  source => "message"
}

The message field you quoted at the top is not JSON formatted. I suggest you review the conditionals surrounding your json {} block, wherever it is, and make sure that this particular event never hits it.

The grokparsefailure message can be generated by any grok block you have. Check the conditionals around others as well, to ensure this event doesn't hit those inappropriately. If you want to make sure that this grok-block is the one that's failing parsing, I suggest setting tag_on_failure to something unique to that block, to be sure this is the one generating it.


问:
Sharepoint 2007 page without master page
i would like to know how to create a page in sharepoint 2007 that has no masterpage. tks!</p>

答: Open Site in SPD, right click on the root in "Folder List" pane and select "New" and then "ASPX". New aspx page in SharePoint without master page is created. In this page we can perform any of operation that SharePoint supports.</p>


问:
Problems implementing a search filter using LINQ
I'm trying to implement a search filter using LINQ in my ASP.Net application.

However I'm running into problems. Here is my code:

```<code>var result = (from x in db.ContactSet
    select new Models.Contact
    {
        AccountId = x.AccountId,
        FirstName = x.FirstName,
        LastName = x.LastName,
        FullName = x.FullName,
        JobTitle = x.JobTitle,
        ParentCustomerId = x.ParentCustomerId,
        EMailAddress1 = x.EMailAddress1,
        Telephone1 = x.Telephone1,
        MobilePhone = x.MobilePhone,
        Fax = x.Fax,
        GenderCode = x.GenderCode,
        BirthDate = x.BirthDate
    }); //? Gets all rows

result = result
    .Where(x =>
        x.FirstName.Contains(model.searchPhrase) ||
        x.LastName.Contains(model.searchPhrase)); //? Search Filter
</code>```

The Gets all rows code works perfectly in getting all the rows from my database. However I'm having issues with the Search Filter part of the code.

model.searchPhrase is a null-able string.

Every time I run through the Search Filter nothing gets returned (doesn't matter what the input is.

After debugging I noticed that after that block of code runs I get the following Exception Error:

Static members: 'NotSupportedException' is a type, which is not valid in the given context.
  Non-public members: 'new System.Linq.SystemCore_EnumerableDebugView(result).items' thew an exception of type 'System.NotSupportedException'

Any idea what's wrong here?

答:
model.searchPhrase is a null-able string as he written. You cannot compare data type null-able variable with data type (string variable) in LINQ Query. So, it is throwing exception.

Use following code. It worked for me

```<code>string SearchValue="";
try
{SearchValue=model.searchPhrase.Tostring();}catch{}

result = result.Where(x => x.FirstName.Contains(SearchValue) ||
        x.LastName.Contains(SearchValue)).ToList();
</code>```

Body:
I'm trying to implement a search filter using LINQ in my ASP.Net application.

However I'm running into problems. Here is my code:

var result = (from x in db.ContactSet
    select new Models.Contact
    {
        AccountId = x.AccountId,
        FirstName = x.FirstName,
        LastName = x.LastName,
        FullName = x.FullName,
        JobTitle = x.JobTitle,
        ParentCustomerId = x.ParentCustomerId,
        EMailAddress1 = x.EMailAddress1,
        Telephone1 = x.Telephone1,
        MobilePhone = x.MobilePhone,
        Fax = x.Fax,
        GenderCode = x.GenderCode,
        BirthDate = x.BirthDate
    }); //? Gets all rows

result = result
    .Where(x =>
        x.FirstName.Contains(model.searchPhrase) ||
        x.LastName.Contains(model.searchPhrase)); //? Search Filter

The Gets all rows code works perfectly in getting all the rows from my database. However I'm having issues with the Search Filter part of the code.

model.searchPhrase is a null-able string.

Every time I run through the Search Filter nothing gets returned (doesn't matter what the input is.

After debugging I noticed that after that block of code runs I get the following Exception Error:

Static members: 'NotSupportedException' is a type, which is not valid in the given context.
  Non-public members: 'new System.Linq.SystemCore_EnumerableDebugView(result).items' thew an exception of type 'System.NotSupportedException'

Any idea what's wrong here?

Body:
model.searchPhrase is a null-able string as he written. You cannot compare data type null-able variable with data type (string variable) in LINQ Query. So, it is throwing exception.

Use following code. It worked for me

string SearchValue="";
try
{SearchValue=model.searchPhrase.Tostring();}catch{}

result = result.Where(x => x.FirstName.Contains(SearchValue) ||
        x.LastName.Contains(SearchValue)).ToList();


问:
Convert given time into millisecond
I want to convert given time into Milliseconds. My time format is 10:25:10 PM.</p>

答:
You just need to make a Date object and use the getMilliseconds function of that object.

Example:

var d = new Date();
d.setHours(22); //10 PM
d.setMinutes(25);
d.setSeconds(10);

console.log(d.getMilliseconds() + ' milliseconds');```

Title: Convert given time into millisecond


问:
Use a selector to get a child element?
I can use the following to get an element:

```<code>document.getElementById('the-container');
</code>```

Is there a way to get a child (not necessarily an immediate child) of this component.

```<code><div id="the-container">
    <div class="whatever">
       <form>
           .....
</code>```

I'd like to get the form element, without adding an id/class or targeting it via the form tag (might be other forms on page).

No jquery but happy for HTML5.

答:
querySelector is a property of Element objects and takes a selector as its first argument.

```<code>document.getElementById('the-container').querySelector("form");
</code>```

You could also use it directly on the whole document with a more elaborate selector:

```<code>document.querySelector('#the-container form')
</code>```

Title: Use a selector to get a child element?

Body:
I can use the following to get an element:

document.getElementById('the-container');

Is there a way to get a child (not necessarily an immediate child) of this component.

       <form>
           .....

I'd like to get the form element, without adding an id/class or targeting it via the form tag (might be other forms on page).

No jquery but happy for HTML5.

Body:
querySelector is a property of Element objects and takes a selector as its first argument.

document.getElementById('the-container').querySelector("form");

You could also use it directly on the whole document with a more elaborate selector:

document.querySelector('#the-container form')


问:
Xamarin listview outlining issues
I am trying to make a listview in Xamarin with 3 columns, having 1 imageview and 2 textviews. The imageview should be aligned to the left (working), the first textview should be in the middle, all aligned under each other, so that all first letters align. and the 3rd column should be all the way on the right and this is not working, the value of the 3rd column is directly set behind the text of the 2nd column.

The text should be centered verticaly in the row, but this is also not
  working although the android:gravity="center_vertical" is set.

My code :

Listview with everything wrong displayed as shown :

答:
Since there is problems with posting your code sample, I'll post this layout that may be adapted to your situation</p>

```<code><RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/rl_outer"
  android:layout_width="fill_parent"
  android:layout_height="50dip">

  <Button
    android:id="@+id/btn_button1"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"/>

  <RelativeLayout
    android:id="@+id/rl_inner"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
    android:gravity="center">

    <TextView
      android:id="@+id/tv_text1"
      android:layout_width="wrap_content"
      android:layout_height="fill_parent"
      android:gravity="center"/>

    <TextView
      android:id="@+id/tv_text2"
      android:layout_width="wrap_content"
      android:layout_height="fill_parent"
      android:layout_toRightOf="@id/tv_text1"
      android:gravity="right"/>

  </RelativeLayout>
</RelativeLayout>
</code>```

Title: Xamarin listview outlining issues

Body:
Since there is problems with posting your code sample, I'll post this layout that may be adapted to your situation

<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/rl_outer"
  android:layout_width="fill_parent"
  android:layout_height="50dip">

  <Button
    android:id="@+id/btn_button1"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"/>

  <RelativeLayout
    android:id="@+id/rl_inner"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
    android:gravity="center">

    <TextView
      android:id="@+id/tv_text1"
      android:layout_width="wrap_content"
      android:layout_height="fill_parent"
      android:gravity="center"/>

    <TextView
      android:id="@+id/tv_text2"
      android:layout_width="wrap_content"
      android:layout_height="fill_parent"
      android:layout_toRightOf="@id/tv_text1"
      android:gravity="right"/>

  </RelativeLayout>
</RelativeLayout>


问:
For Loop to Count Letters in a Word
I'm just learning python and I came to a problem that required me to put a string as an input in my "count letters function."

The function is supposed to count how many "a"s are in a word given (specifically, a fruit inputed by the user).

The final value is correct, but in my function, it lists me the programs "procedure" if you will by listing how many "a"s are at each index and adding everything that was before.

I just want one final value, not a list.

If I'm not too clear, here is my program and test it out for yourself to see what I mean, and maybe help me come to a solution?

```<code>def count_letters(a):
    count=0
    for char in a:
        if char == 'a':
            count+=1
        print count

a=raw_input("Name a fruit and I will tell you how many letters are in it." + '\n')
print count_letters(a)
</code>```

答:
A simple change makes it work. Just replace the print by return and remove one indentation level to get it of of the loop.

```<code>def count_letters(a):
    count=0
    for char in a:
        if char == 'a':
            count+=1
    return count
</code>```

In general, it is considered more pythonic to avoid for loops. While not the shortest solution (see comment by Eric Duminil) to your problem, this might give an idea how to use list comprehension instead:

```<code>def count_a(text):
    return len([x for x in text if x=='a'])

print count_a("banana")
</code>```

Title: For Loop to Count Letters in a Word

Body:
I'm just learning python and I came to a problem that required me to put a string as an input in my "count letters function."

The function is supposed to count how many "a"s are in a word given (specifically, a fruit inputed by the user).

The final value is correct, but in my function, it lists me the programs "procedure" if you will by listing how many "a"s are at each index and adding everything that was before.

I just want one final value, not a list.

If I'm not too clear, here is my program and test it out for yourself to see what I mean, and maybe help me come to a solution?

def count_letters(a):
    count=0
    for char in a:
        if char == 'a':
            count+=1
        print count

a=raw_input("Name a fruit and I will tell you how many letters are in it." + '\n')
print count_letters(a)

Body:
A simple change makes it work. Just replace the print by return and remove one indentation level to get it of of the loop.

def count_letters(a):
    count=0
    for char in a:
        if char == 'a':
            count+=1
    return count

In general, it is considered more pythonic to avoid for loops. While not the shortest solution (see comment by Eric Duminil) to your problem, this might give an idea how to use list comprehension instead:

def count_a(text):
    return len([x for x in text if x=='a'])

print count_a("banana")


问:
ng-Idle KeepaliveProvider.http .success is not a function
I’m using ng-Idle and getting an error when I populate KeepaliveProvider.http(…). For the most part I am using the code taken straight from the example given here http://hackedbychinese.github.io/ng-idle/

Here is my controller:

```<code>function timeoutCtrl(modelData, $scope, Idle, $log, $uibModal) {
var vm = this;
vm.config = {};

(function () {
    vm.config = modelData;
    Idle.watch();
}());

function closeModals() {
    if (vm.warning) {
        vm.warning.close();
        vm.warning = null;
    }
}

$scope.$on('IdleStart', function () {
    $log.debug('IdleStart');
    closeModals();

    vm.warning = $uibModal.open({
        templateUrl: 'timeout-warning-dialog.html',
        controller: 'TimeoutWarningController as timeoutWarning'
    });
});

$scope.$on('IdleEnd', function () {
    $log.debug('IdleEnd');
    closeModals();
});

$scope.$on('IdleTimeout', function () {
    $log.debug('IdleTimeout');
    window.location = '/Session/Timeout/' + vm.config.paxCode;
});
</code>```

}

```<code>app.controller('TimeoutController', ['modelData', '$scope', 'Idle', '$log', '$uibModal', timeoutCtrl])
.config(['timeoutData', 'IdleProvider', 'KeepaliveProvider', function (timeoutData, IdleProvider, KeepaliveProvider) {
    IdleProvider.idle(timeoutData.timeoutIdleSeconds);
    IdleProvider.timeout(timeoutData.timeoutWarningSeconds);
    KeepaliveProvider.interval(timeoutData.keepAliveSeconds);
    KeepaliveProvider.http('/api/session/keepalive');
}]);
</code>```

But after IdleStart opens the modal dialog, then any mouse move causes this error:
enter image description here

$http(...).success is not a function

If I comment out the line that sets the KeepaliveProvider.http(…) then the error does not occur. But then my server session is not kept alive too.

I’ve Googled allot on this and most examples do not set the  KeepaliveProvider.http(…). And the ones that do are doing the same thing I’m doing. Is there some configuration that must be done that is not in the example?

I'm using ng-Idle 1.2.2

答:
I figured out the issue here. I got AngularJS 1.6.1 via Nuget package. So, .success and .error are deprecated.

But somehow I got ahold of an older version of ng-Ilde version 1.2.2 which is using .success. Need to download the newest version of ng-Idle.

Body:
I’m using ng-Idle and getting an error when I populate KeepaliveProvider.http(…). For the most part I am using the code taken straight from the example given here http://hackedbychinese.github.io/ng-idle/

Here is my controller:

function timeoutCtrl(modelData, $scope, Idle, $log, $uibModal) {
var vm = this;
vm.config = {};

(function () {
    vm.config = modelData;
    Idle.watch();
}());

function closeModals() {
    if (vm.warning) {
        vm.warning.close();
        vm.warning = null;
    }
}

$scope.$on('IdleStart', function () {
    $log.debug('IdleStart');
    closeModals();

    vm.warning = $uibModal.open({
        templateUrl: 'timeout-warning-dialog.html',
        controller: 'TimeoutWarningController as timeoutWarning'
    });
});

$scope.$on('IdleEnd', function () {
    $log.debug('IdleEnd');
    closeModals();
});

$scope.$on('IdleTimeout', function () {
    $log.debug('IdleTimeout');
    window.location = '/Session/Timeout/' + vm.config.paxCode;
});

}

app.controller('TimeoutController', ['modelData', '$scope', 'Idle', '$log', '$uibModal', timeoutCtrl])
.config(['timeoutData', 'IdleProvider', 'KeepaliveProvider', function (timeoutData, IdleProvider, KeepaliveProvider) {
    IdleProvider.idle(timeoutData.timeoutIdleSeconds);
    IdleProvider.timeout(timeoutData.timeoutWarningSeconds);
    KeepaliveProvider.interval(timeoutData.keepAliveSeconds);
    KeepaliveProvider.http('/api/session/keepalive');
}]);

But after IdleStart opens the modal dialog, then any mouse move causes this error:
enter image description here

$http(...).success is not a function

If I comment out the line that sets the KeepaliveProvider.http(…) then the error does not occur. But then my server session is not kept alive too.

I’ve Googled allot on this and most examples do not set the  KeepaliveProvider.http(…). And the ones that do are doing the same thing I’m doing. Is there some configuration that must be done that is not in the example?

I'm using ng-Idle 1.2.2


问:
Issue with MYSQL lc_time_names
I want to the retrieve the time as '3:30 م' instead of '3:30 PM' from Mysql (like CultureInfo in .NET)

By setting the lc_time_names = 'ar_EG' it still the same.

Here what i did

```<code>SET lc_time_names = 'ar_EG';
SELECT TIME_FORMAT(NOW(),'%h:%i %p') AS 'Time';
</code>```

https://dev.mysql.com/doc/refman/5.7/en/locale-support.html

I don't know why 0 rows is affected ? Any help is highly appreciated.

答:
In the MySQL Server Locale Support link you've shared we can read:

The locale indicated by the lc_time_names system variable controls the language used to display day and month names and abbreviations. This variable affects the output from the DATE_FORMAT(), DAYNAME(), and MONTHNAME() functions.

It says nothing about TIME_FORMAT() or AM/PM. Since it does not seem to work, I presume it's just not supported:

```<code>SET lc_time_names = 'ar_EG';
SELECT DATE_FORMAT(NOW(), '%l %p, %r, %a, %b');
</code>```

4 PM, 04:28:06 PM, خ, مار
```

Title: Issue with MYSQL lc_time_names

Body:
I want to the retrieve the time as '3:30 م' instead of '3:30 PM' from Mysql (like CultureInfo in .NET)

By setting the lc_time_names = 'ar_EG' it still the same.

Here what i did

SET lc_time_names = 'ar_EG';
SELECT TIME_FORMAT(NOW(),'%h:%i %p') AS 'Time';

https://dev.mysql.com/doc/refman/5.7/en/locale-support.html

I don't know why 0 rows is affected ? Any help is highly appreciated.

Body:
In the MySQL Server Locale Support link you've shared we can read:

The locale indicated by the lc_time_names system variable controls the language used to display day and month names and abbreviations. This variable affects the output from the DATE_FORMAT(), DAYNAME(), and MONTHNAME() functions.

It says nothing about TIME_FORMAT() or AM/PM. Since it does not seem to work, I presume it's just not supported:

SET lc_time_names = 'ar_EG';
SELECT DATE_FORMAT(NOW(), '%l %p, %r, %a, %b');

4 PM, 04:28:06 PM, خ, مار


答:
This is a simple example of how you can do this. First, the source class for the ListBox. A simple class that implements the INotifyPropertyChanged interface and one string property.

```<code>public class MyClass : INotifyPropertyChanged
{
    public MyClass(string myString)
    {
        MyString = myString;
    }
    private string m_myString;
    public string MyString
    {
        get
        {
            return m_myString;
        }
        set
        {
            m_myString = value;
            OnPropertyChanged("MyString");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
</code>```

The MainWindow has an ObservableCollection of MyClass. We set the DataContext for the Window to itself (this), this will make the ListBox inherit the DataContext so we can Bind its ItemsSource to MyClasses.

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        MyClasses = new ObservableCollection<MyClass>();
        MyClasses.Add(new MyClass("My String 1"));
        MyClasses.Add(new MyClass("My String 2"));
        MyClasses.Add(new MyClass("My String 3"));
        this.DataContext = this;
    }

    public ObservableCollection<MyClass> MyClasses
    {
        get;
        private set;
    }
}
</code>```

In xaml we have the ListBox that's binding to MyClasses. The ItemTemplate is for each ListBoxItem in the ListBox, each item binding to its instance of MyClass, presenting the MyString property and a "Remove Button". The DataContext for each ListBoxItem will be an instance of MyClass.

```<code><ListBox ItemsSource="{Binding MyClasses}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding MyString}" Margin="6"/>
                <Button Content="Remove"
                        Click="RemoveListBoxItem_Click"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
</code>```

Finally, we add the code behind EventHanlder for RemoveListBoxItem_Click in MainWindow.xaml.cs.

```<code>private void RemoveListBoxItem_Click(object sender, RoutedEventArgs e)
{
    // The clicked Button
    Button button = sender as Button;
    // The DataContext of the Button will be its instance of MyClass
    MyClass selectedItem = button.DataContext as MyClass;
    if (selectedItem != null)
    {
        // Remove the MyClass item from the collection
        MyClasses.Remove(selectedItem);
    }
}
</code>```

Title: How to include buttons and map their events within a ListBox?

Body:
I have a concept question on how to have a dynamic list displayed by a list box. Within the list box, the items are held within a Stackpanel. Within the stack panel is a string and a button. If I click that button, that entity / item (both the button and the string) is removed from the list box.

1) How do I create new buttons based on the number of entities in the list?

2) How do I connect the idea that this button is related to this item in the listbox?

3) Is this even possible with binding?

Sorry, I am still new to WPF but starting to see that it is quite powerful.

If you can also provide a brief / short example, or direct me to a link that is similar to this, it would be greatly appreciated. Thanks so much! :)

Body:
This is a simple example of how you can do this. First, the source class for the ListBox. A simple class that implements the INotifyPropertyChanged interface and one string property.

public class MyClass : INotifyPropertyChanged
{
    public MyClass(string myString)
    {
        MyString = myString;
    }
    private string m_myString;
    public string MyString
    {
        get
        {
            return m_myString;
        }
        set
        {
            m_myString = value;
            OnPropertyChanged("MyString");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

The MainWindow has an ObservableCollection of MyClass. We set the DataContext for the Window to itself (this), this will make the ListBox inherit the DataContext so we can Bind its ItemsSource to MyClasses.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        MyClasses = new ObservableCollection<MyClass>();
        MyClasses.Add(new MyClass("My String 1"));
        MyClasses.Add(new MyClass("My String 2"));
        MyClasses.Add(new MyClass("My String 3"));
        this.DataContext = this;
    }

    public ObservableCollection<MyClass> MyClasses
    {
        get;
        private set;
    }
}

In xaml we have the ListBox that's binding to MyClasses. The ItemTemplate is for each ListBoxItem in the ListBox, each item binding to its instance of MyClass, presenting the MyString property and a "Remove Button". The DataContext for each ListBoxItem will be an instance of MyClass.

<ListBox ItemsSource="{Binding MyClasses}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding MyString}" Margin="6"/>
                <Button Content="Remove"
                        Click="RemoveListBoxItem_Click"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Finally, we add the code behind EventHanlder for RemoveListBoxItem_Click in MainWindow.xaml.cs.

private void RemoveListBoxItem_Click(object sender, RoutedEventArgs e)
{
    // The clicked Button
    Button button = sender as Button;
    // The DataContext of the Button will be its instance of MyClass
    MyClass selectedItem = button.DataContext as MyClass;
    if (selectedItem != null)
    {
        // Remove the MyClass item from the collection
        MyClasses.Remove(selectedItem);
    }
}


问:
Is this a legal if sentance?
I just started coding and can't get this "Heater" object to work. It just prompts the if else statement "its too hot" when trying to give temp a higher value and it does not stop/ goes below the min temp value when calling the "colder" method. Thanks</p>

```<code>public class Heater {
    private double temp;
    private double min;
    private double max;
    private double increment;

    public Heater(double min, double max) {
        temp = 15;
        increment = 5;
    }

    public void Warmer() {
        if(temp + increment <= max) {
            temp = temp + increment;
        } else if(temp + increment > max) {
            System.out.println("Too hot");
        }
    }

    public void Colder() {
        if(temp - increment >= min){
            temp = temp - increment;
        } else if (temp - increment < min){
            System.out.println("Too cold");
        }
    }

    public double getTemp() {
        return temp;
    }
}
</code>```

答:
You are using Caps for method names. Caps are for Class names.

You aren't setting min. It's at a value of zero.

You don't need the else if condition - just use else instead.

```<code> public void colder() { // method name, make lower case.
    if(temp - increment >= min){
       temp = temp - increment;
    } else {
       System.out.println("Too cold");
    }
  }
</code>```

Title: Is this a legal if sentance?

Body:
I just started coding and can't get this "Heater" object to work. It just prompts the if else statement "its too hot" when trying to give temp a higher value and it does not stop/ goes below the min temp value when calling the "colder" method. Thanks

public class Heater {
    private double temp;
    private double min;
    private double max;
    private double increment;

    public Heater(double min, double max) {
        temp = 15;
        increment = 5;
    }

    public void Warmer() {
        if(temp + increment <= max) {
            temp = temp + increment;
        } else if(temp + increment > max) {
            System.out.println("Too hot");
        }
    }

    public void Colder() {
        if(temp - increment >= min){
            temp = temp - increment;
        } else if (temp - increment < min){
            System.out.println("Too cold");
        }
    }

    public double getTemp() {
        return temp;
    }
}

Body:
You are using Caps for method names. Caps are for Class names.

You aren't setting min. It's at a value of zero.

You don't need the else if condition - just use else instead.

 public void colder() { // method name, make lower case.
    if(temp - increment >= min){
       temp = temp - increment;
    } else {
       System.out.println("Too cold");
    }
  }