问:
Validate Sharepoint 2007 Web Part form field in C#
I am creating a very simple web part that accepts entry on a form text field and then does something with it.  Before doing this, I want to validate the content of the text field.  It must exist, and it must be less than 250 characters.  I know I could probably write some custom code to do this, but Sharepoint includes Validation features, so why reinvent the wheel.

However, after an hour searching for some documentation on what I want to achieve, I have found plenty that explains how to do this if I am writing ASP.NET code, but very little if writing the web part in C# in Visual Studio 2008. The only bit remaining is the validation.

So, my question is how to validate a field on a form.

My field is called txtMessage.  Here is the code I wrote:

```<code>// Add the form field to the web part
tc = new TableCell();
tc.VerticalAlign = VerticalAlign.Top;
txtMessage = new TextBox();
txtMessage.ID = "txtFormField";
txtMessage.Width = Unit.Pixel(300);
txtMessage.MaxLength = 250;
tc.Controls.Add(txtMessage);**strong text**

// Validate form field - required field
RequiredFieldValidator messageRequiredValidator = new RequiredFieldValidator();
messageRequiredValidator.ControlToValidate = txtMessage.ID;
messageRequiredValidator.ErrorMessage = "You must enter text";
messageRequiredValidator.Display = ValidatorDisplay.Dynamic;
messageRequiredValidator.Text = "<img src=\"/_layouts/images/CNSCA16.gif\"/>";

 // Send Message button
 tc = new TableCell();
 btnSendMessage = new Button();
 btnSendMessage.Text = "Send";
 btnSendMessage.Click += new EventHandler(btnSendMessage_Click);
 tc.Controls.Add(btnSendMessage);
 tr.Controls.Add(tc);
</code>```

All I really need to know is how to trigger validation of the field when clicking on the button.  Do I need to add a new EventHandler that calls the validation, or something else?

答:
Doh - now I realise that I have to add this as a separate control to the page.</p>

```<code>tc.Controls.Add(messageRequiredValidator);
</code>```

Body:
I am creating a very simple web part that accepts entry on a form text field and then does something with it.  Before doing this, I want to validate the content of the text field.  It must exist, and it must be less than 250 characters.  I know I could probably write some custom code to do this, but Sharepoint includes Validation features, so why reinvent the wheel.

However, after an hour searching for some documentation on what I want to achieve, I have found plenty that explains how to do this if I am writing ASP.NET code, but very little if writing the web part in C# in Visual Studio 2008. The only bit remaining is the validation.

So, my question is how to validate a field on a form.

My field is called txtMessage.  Here is the code I wrote:

// Add the form field to the web part
tc = new TableCell();
tc.VerticalAlign = VerticalAlign.Top;
txtMessage = new TextBox();
txtMessage.ID = "txtFormField";
txtMessage.Width = Unit.Pixel(300);
txtMessage.MaxLength = 250;
tc.Controls.Add(txtMessage);**strong text**

// Validate form field - required field
RequiredFieldValidator messageRequiredValidator = new RequiredFieldValidator();
messageRequiredValidator.ControlToValidate = txtMessage.ID;
messageRequiredValidator.ErrorMessage = "You must enter text";
messageRequiredValidator.Display = ValidatorDisplay.Dynamic;
messageRequiredValidator.Text = "";

 // Send Message button
 tc = new TableCell();
 btnSendMessage = new Button();
 btnSendMessage.Text = "Send";
 btnSendMessage.Click += new EventHandler(btnSendMessage_Click);
 tc.Controls.Add(btnSendMessage);
 tr.Controls.Add(tc);

All I really need to know is how to trigger validation of the field when clicking on the button.  Do I need to add a new EventHandler that calls the validation, or something else?

Body:
Doh - now I realise that I have to add this as a separate control to the page.

tc.Controls.Add(messageRequiredValidator);


来源: stackexchange

问:
Invert an array of booleans in JavaScript
I am trying to invert the values of a string of boolean values so that instead  of

inverted([true, false, true, false, true])

it is  [false, true, false, true, false]

So far I have come up with this:

```<code>function inverted(bools) {
    var inversion = [];
    var string= [];
    while(!bools) {
      string.push(bools);
    }
    return inversion;
}
</code>```

But my code is not working, any and all help will be much appreciated!

答:
```<code>function inverted(bools) {
  for(var i = 0; i < bools.length; i++) {
     bools[i] = !bools[i];
   }
  return bools;
}
</code>```

Use it as

```<code>var bools = [true, false, true];
bools = inverted(bools);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to invert the values of a string of boolean values so that instead  of

inverted([true, false, true, false, true])

it is  [false, true, false, true, false]

So far I have come up with this:

function inverted(bools) {
    var inversion = [];
    var string= [];
    while(!bools) {
      string.push(bools);
    }
    return inversion;
}

But my code is not working, any and all help will be much appreciated!

Body:
function inverted(bools) {
  for(var i = 0; i < bools.length; i++) {
     bools[i] = !bools[i];
   }
  return bools;
}

Use it as

var bools = [true, false, true];
bools = inverted(bools);


问:
NSObject has no subscript members
I am having an issue with trying to retrieve data from firebase. I keep getting an error which says NSObject has no subscript members when trying to append? Currently firebase is holding a Question, an array of different answers and a correct answer.

```<code>class QuestionList
{
//properties
public static var Username: String = ""
private static var quiz = [Question]()

static func getDummyQuestions()->[Question]
{
    //create some dummy data for the model
    var ref: FIRDatabaseReference!
    var refHandle: UInt!
    ref = FIRDatabase.database().reference() //reference

    refHandle = ref.child("Questions").child("Q1").observe(.value, with: { (snapshot)in
        let dataDict = snapshot.value as? NSObject

        //let value = snapshot.value as? NSDictionary
        //let quest = value?["Question"] as! String
        //let Answers = value?["Answers"] as! String
        //let Correct = value?["Correct"] as! String

        //quiz.append(Question(q: quest, a:[Answers], c: Correct))

        quiz.append(Question(q: dataDict["Question"], a: dataDict["Answers"], c: dataDict["Correct"]))

        //quiz.append(Question(q: "hello", a: ["short long", "short char", "short float", "short int"], c: 2 ))
        //quiz.append(Question(q: "bye", a: ["short short", "short int", "short float", "short int"], c: 2 ))

      print (dataDict)
    })
    return quiz
}
</code>```

}

```<code>class Question
{
var quest:String
var answers:[String]
var correct:Int

init(q: String, a:[String], c:Int)
{
    quest = q
    answers = a
    correct = c
}

func isCorrectQuestion(itemSelected: String)->Bool {
    if (itemSelected == answers[correct]) {
        return true
    } else {
        return false
    }
}
</code>```

}
//}

答:
Let cast snapshot to a dictionary: let dataDict = snapshot.value as? [String: Any]

```<code>refHandle = ref.child("Questions").child("Q1").observe(.value, with: { (snapshot)in
    if let dataDict = snapshot.value as? [String: Any] {

        if let quest = dataDict["Question"] as? String,
            let Answers = dataDict["Answers"] as? [String],
            let Correct = dataDict["Correct"] as? Int {
            quiz.append(Question(q: quest, a: Answers, c: Correct))
        }
    }

    print (dataDict)
})
</code>```

Title: NSObject has no subscript members

Body:
I am having an issue with trying to retrieve data from firebase. I keep getting an error which says NSObject has no subscript members when trying to append? Currently firebase is holding a Question, an array of different answers and a correct answer.

class QuestionList
{
//properties
public static var Username: String = ""
private static var quiz = [Question]()

static func getDummyQuestions()->[Question]
{
    //create some dummy data for the model
    var ref: FIRDatabaseReference!
    var refHandle: UInt!
    ref = FIRDatabase.database().reference() //reference

    refHandle = ref.child("Questions").child("Q1").observe(.value, with: { (snapshot)in
        let dataDict = snapshot.value as? NSObject

        //let value = snapshot.value as? NSDictionary
        //let quest = value?["Question"] as! String
        //let Answers = value?["Answers"] as! String
        //let Correct = value?["Correct"] as! String

        //quiz.append(Question(q: quest, a:[Answers], c: Correct))

        quiz.append(Question(q: dataDict["Question"], a: dataDict["Answers"], c: dataDict["Correct"]))

        //quiz.append(Question(q: "hello", a: ["short long", "short char", "short float", "short int"], c: 2 ))
        //quiz.append(Question(q: "bye", a: ["short short", "short int", "short float", "short int"], c: 2 ))

      print (dataDict)
    })
    return quiz
}

}

class Question
{
var quest:String
var answers:[String]
var correct:Int

init(q: String, a:[String], c:Int)
{
    quest = q
    answers = a
    correct = c
}

func isCorrectQuestion(itemSelected: String)->Bool {
    if (itemSelected == answers[correct]) {
        return true
    } else {
        return false
    }
}

}
//}

Body:
Let cast snapshot to a dictionary: let dataDict = snapshot.value as? [String: Any]

refHandle = ref.child("Questions").child("Q1").observe(.value, with: { (snapshot)in
    if let dataDict = snapshot.value as? [String: Any] {

        if let quest = dataDict["Question"] as? String,
            let Answers = dataDict["Answers"] as? [String],
            let Correct = dataDict["Correct"] as? Int {
            quiz.append(Question(q: quest, a: Answers, c: Correct))
        }
    }

    print (dataDict)
})


问:
Debugging array related error (core dumped)
I was working to implement the rod cutting problem and I encountered this error:

```<code>a.out: malloc.c:2392: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted (core dumped)
</code>```

The dashed comment block is where I suspect the error is coming from, but I'm not sure why. Trying to run under gdb I am having hard time pin-pointing it (seems to be crashing at i = 7) (compiling using: g++)

```<code>#include <iostream>
#include <cstdlib>

using namespace std;

int max_from(int * arr, int n)
{
    int maxval = arr[1];
    for(size_t i = 2; i < n; ++i)
        if(arr[i] > maxval) maxval = arr[i];

    return maxval;
}

int main()
{
    int n = 11;

    int * V = new int[n]; // given arr, price at(i)
    int * C = new int[n]; // optimal at length(i)

    V[0] = 0; // non-affecting value, using 1 as starting point

    V[1] = 1;
    V[2] = 5;
    V[3] = 8;
    V[4] = 9;
    V[5] = 10;
    V[6] = 17;
    V[7] = 17;
    V[8] = 20;
    V[9] = 24;
    V[10] = 30;

    C[0] = 0;

    // --------------------------------------------------

    for(size_t i = 1; i < n; ++i)
    {
        int * arr = new int[i];
        for(size_t k = 1; k <= i; ++k)
        {
            arr[k] = V[k] + C[i-k];
        }

        C[i] = max_from(arr, n);

        delete [ ] arr;
    }

    cout << max_from(C, n) << '\n'; // maximized cost
    // --------------------------------------------------

    delete [ ] V;
    delete [ ] C;
}
</code>```

答:
```<code>int* arr = new int[i];
for(size_t k = 1; k <= i; ++k)
    arr[k] ....
</code>```

Here is out-of-bound error. Shouldn't it be new int[i + 1]?

Also, I highly recommend you never to use raw new/free. std::vector is the right thing for this.

Body:
I was working to implement the rod cutting problem and I encountered this error:

a.out: malloc.c:2392: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted (core dumped)

The dashed comment block is where I suspect the error is coming from, but I'm not sure why. Trying to run under gdb I am having hard time pin-pointing it (seems to be crashing at i = 7) (compiling using: g++)

#include <iostream>
#include <cstdlib>

using namespace std;

int max_from(int * arr, int n)
{
    int maxval = arr[1];
    for(size_t i = 2; i < n; ++i)
        if(arr[i] > maxval) maxval = arr[i];

    return maxval;
}

int main()
{
    int n = 11;

    int * V = new int[n]; // given arr, price at(i)
    int * C = new int[n]; // optimal at length(i)

    V[0] = 0; // non-affecting value, using 1 as starting point

    V[1] = 1;
    V[2] = 5;
    V[3] = 8;
    V[4] = 9;
    V[5] = 10;
    V[6] = 17;
    V[7] = 17;
    V[8] = 20;
    V[9] = 24;
    V[10] = 30;

    C[0] = 0;

    // --------------------------------------------------

    for(size_t i = 1; i < n; ++i)
    {
        int * arr = new int[i];
        for(size_t k = 1; k <= i; ++k)
        {
            arr[k] = V[k] + C[i-k];
        }

        C[i] = max_from(arr, n);

        delete [ ] arr;
    }

    cout << max_from(C, n) << '\n'; // maximized cost
    // --------------------------------------------------

    delete [ ] V;
    delete [ ] C;
}

Body:
int* arr = new int[i];
for(size_t k = 1; k <= i; ++k)
    arr[k] ....

Here is out-of-bound error. Shouldn't it be new int[i + 1]?

Also, I highly recommend you never to use raw new/free. std::vector is the right thing for this.


问:
Split column using awk or sed
I have a file containing  the following text.

dog

  aa  6469

  bb  5946

  cc  715

cat

  aa  5692

Bird

  aa  3056

  bb  2893

  cc  1399

  dd  33

I need the following output:

A-Z   ,aa ,bb,    cc, dd

    dog,    6469,   5946    ,715,   0

    cat ,5692,  0,  0,  0

    Bird    ,3056,  2893,   1399,   33

I tried:
awk '{$1=$1}1' OFS="," RS=
But is not giving the format I need.

Thanks in advance for your help.

Cris

答:
awk to the rescue!

```<code>awk -v OFS=, 'NF==1 {h[++c]=$1}
              NF==2 {v[c,$1]=$2; ks[$1]}
              END   {printf "%s", "A-Z";
                     for(k in ks) printf "%s", OFS k;
                     print "";
                     for(i=1;i<=c;i++)
                       {printf "%s", h[i];
                        for(k in ks) printf "%s", OFS v[i,k]+0;
                        print ""}}' file'
</code>```

order of the columns will be random.

Title: Split column using awk or sed

Body:
awk to the rescue!

awk -v OFS=, 'NF==1 {h[++c]=$1}
              NF==2 {v[c,$1]=$2; ks[$1]}
              END   {printf "%s", "A-Z";
                     for(k in ks) printf "%s", OFS k;
                     print "";
                     for(i=1;i<=c;i++)
                       {printf "%s", h[i];
                        for(k in ks) printf "%s", OFS v[i,k]+0;
                        print ""}}' file'

order of the columns will be random.


问:
How to send an html page as email in nodejs
I recently started programming my first node.js. I can't find any modules from node that is able to send html page as email. please help, thanks!</p>

答:
You can use nodemailer and nodemailer-express-handlebars modules do this:

```<code>var nodemailer = require('nodemailer');
var mailerhbs = require('nodemailer-express-handlebars');

var mailer = nodemailer.createTransport({
    service: Gmail,  // More at https://nodemailer.com/smtp/well-known/#supported-services
    auth: {
        user: [USERNAME@gmail.com], // Your email id
        pass: [PASSWORD] // Your password
    }
});

mailer.use('compile', mailerhbs({
    viewPath: 'templates/default/emails', //Path to email template folder
    extName: '.hbs' //extendtion of email template
}));
</code>```

In router post you can use:

```<code>mailer.sendMail({
            from: 'Your name username@domain.com',
            to: user.local.email,
            subject: 'Reset your password',
            template: 'password_reset', //Name email file template
            context: { // pass variables to template
                hostUrl: req.headers.host,
                customeName: user.info.firstname + ' ' + user.info.lastname,
                resetUrl: req.headers.host + '/users/recover/' + token,
                resetCode: token
            }
        }, function (err, response) {
            if (err) {
                res.send('Error send email, please contact administrator to best support.');
            }
            res.send('Email send successed to you email' + req.body.email + '.');
            done(err, 'done');
        });
</code>```

In hbs template you can use variables:

```<code>{{var from context}}
</code>```

hope blocks of code to help you.

Body:
You can use nodemailer and nodemailer-express-handlebars modules do this:

var nodemailer = require('nodemailer');
var mailerhbs = require('nodemailer-express-handlebars');

var mailer = nodemailer.createTransport({
    service: Gmail,  // More at https://nodemailer.com/smtp/well-known/#supported-services
    auth: {
        user: [USERNAME@gmail.com], // Your email id
        pass: [PASSWORD] // Your password
    }
});

mailer.use('compile', mailerhbs({
    viewPath: 'templates/default/emails', //Path to email template folder
    extName: '.hbs' //extendtion of email template
}));

In router post you can use:

mailer.sendMail({
            from: 'Your name username@domain.com',
            to: user.local.email,
            subject: 'Reset your password',
            template: 'password_reset', //Name email file template
            context: { // pass variables to template
                hostUrl: req.headers.host,
                customeName: user.info.firstname + ' ' + user.info.lastname,
                resetUrl: req.headers.host + '/users/recover/' + token,
                resetCode: token
            }
        }, function (err, response) {
            if (err) {
                res.send('Error send email, please contact administrator to best support.');
            }
            res.send('Email send successed to you email' + req.body.email + '.');
            done(err, 'done');
        });

In hbs template you can use variables:

{{var from context}}

hope blocks of code to help you.


问:
Python curve fit with change point
As I'm really struggleing to get from R-code, to Python code, I would like to ask some help. The code I want to use has been provided to my from withing the mathematics forum of stackexchange.

https://math.stackexchange.com/questions/2205573/curve-fitting-on-dataset

I do understand what is going on. But I'm really having a hard time trying to solve the R-code, as I have never seen anything of it. I have written the function to return the sum of squares. But I'm stuck at how I could use a function similar to the optim function. And also I don't really like the guesswork at the initial values. I would like it better to run and re-run a type of optim function untill I get the wanted result, because my needs for a nearly perfect curve fit are really high.

```<code>def model (par,x):
    n = len(x)
    res = []
    for i in range(1,n):
        A0 = par[3] + (par[4]-par[1])*par[6] + (par[5]-par[2])*par[6]**2
        if(x[i] == par[6]):
            res[i] = A0 + par[1]*x[i] + par[2]*x[i]**2
        else:
            res[i] = par[3] + par[4]*x[i] + par[5]*x[i]**2
    return res
</code>```

This is my model function...

```<code>def sum_squares (par, x, y):
    ss = sum((y-model(par,x))^2)
    return ss
</code>```

And this is the sum of squares

But I have no idea on how to convert this:

```<code> #I found these initial values with a few minutes of guess and check.
 par0 <- c(7,-1,-395,70,-2.3,10)
 sol <- optim(par= par0, fn=sqerror, x=x, y=y)$par
</code>```

To Python code...

答:
I think that the range of x values [0, 360] and y values (which you say is ~0.2) is probably not the problem.   Getting good initial values for the parameters is probably much more important.

In Python with numpy / scipy, you would definitely want to not loop over values of x but do something more like

```<code>def model(par,x):
    res = par[2] + par[3]*x + par[4]*x**2
    A0  = par[2] + (par[3]-par[0])*par[5] + (par[4]-par[1])*par[5]**2
    res[np.where(x <= par[5])] = A0 + par[0]*x + par[1]*x**2
    return res
</code>```

It's not clear to me that that form is really what you want:  why should A0 (a value independent of x added to a portion of the model) be so complicated and interdependent on the other parameters?

More importantly, your sum_of_squares() function is actually not what least_squares() wants: you should return the residual array, you should not do the sum of squares yourself.  So, that should be

```<code>def sum_of_squares(par, x, y):
    return (y - model(par, x))
</code>```

But most importantly, there is a conceptual problem that is probably going to plague this model:   Your par[5] is meant to represent a breakpoint where the model changes form.  This is going to be very hard for these optimization routines to find. These routines generally make a very small change to each parameter value to estimate to derivative of the residual array with respect to that variable in order to figure out how to change that variable.  With a parameter that is essentially used as an integer, the small change in the initial value will have no effect at all, and the algorithm will not be able to determine the value for this parameter. With some of the scipy.optimize algorithms (notably, leastsq) you can specify a scale for the relative change to make.   With leastsq that is called epsfcn.  You may need to set this as high as 0.3 or 1.0 for fitting the breakpoint to work. Unfortunately, this cannot be set per variable, only per fit. You might need to experiment with this and other options to least_squares or leastsq.

Title: Python curve fit with change point

Body:
As I'm really struggleing to get from R-code, to Python code, I would like to ask some help. The code I want to use has been provided to my from withing the mathematics forum of stackexchange.

https://math.stackexchange.com/questions/2205573/curve-fitting-on-dataset

I do understand what is going on. But I'm really having a hard time trying to solve the R-code, as I have never seen anything of it. I have written the function to return the sum of squares. But I'm stuck at how I could use a function similar to the optim function. And also I don't really like the guesswork at the initial values. I would like it better to run and re-run a type of optim function untill I get the wanted result, because my needs for a nearly perfect curve fit are really high.

def model (par,x):
    n = len(x)
    res = []
    for i in range(1,n):
        A0 = par[3] + (par[4]-par[1])*par[6] + (par[5]-par[2])*par[6]**2
        if(x[i] == par[6]):
            res[i] = A0 + par[1]*x[i] + par[2]*x[i]**2
        else:
            res[i] = par[3] + par[4]*x[i] + par[5]*x[i]**2
    return res

This is my model function...

def sum_squares (par, x, y):
    ss = sum((y-model(par,x))^2)
    return ss

And this is the sum of squares

But I have no idea on how to convert this:

 #I found these initial values with a few minutes of guess and check.
 par0 <- c(7,-1,-395,70,-2.3,10)
 sol <- optim(par= par0, fn=sqerror, x=x, y=y)$par

To Python code...

Body:
I think that the range of x values [0, 360] and y values (which you say is ~0.2) is probably not the problem.   Getting good initial values for the parameters is probably much more important.

In Python with numpy / scipy, you would definitely want to not loop over values of x but do something more like

def model(par,x):
    res = par[2] + par[3]*x + par[4]*x**2
    A0  = par[2] + (par[3]-par[0])*par[5] + (par[4]-par[1])*par[5]**2
    res[np.where(x <= par[5])] = A0 + par[0]*x + par[1]*x**2
    return res

It's not clear to me that that form is really what you want:  why should A0 (a value independent of x added to a portion of the model) be so complicated and interdependent on the other parameters?

More importantly, your sum_of_squares() function is actually not what least_squares() wants: you should return the residual array, you should not do the sum of squares yourself.  So, that should be

def sum_of_squares(par, x, y):
    return (y - model(par, x))

But most importantly, there is a conceptual problem that is probably going to plague this model:   Your par[5] is meant to represent a breakpoint where the model changes form.  This is going to be very hard for these optimization routines to find. These routines generally make a very small change to each parameter value to estimate to derivative of the residual array with respect to that variable in order to figure out how to change that variable.  With a parameter that is essentially used as an integer, the small change in the initial value will have no effect at all, and the algorithm will not be able to determine the value for this parameter. With some of the scipy.optimize algorithms (notably, leastsq) you can specify a scale for the relative change to make.   With leastsq that is called epsfcn.  You may need to set this as high as 0.3 or 1.0 for fitting the breakpoint to work. Unfortunately, this cannot be set per variable, only per fit. You might need to experiment with this and other options to least_squares or leastsq.


问:
hive jdbc connection time out
I install hive2.2 on server node25,and tried to access hiveserver2 using jdbc with  a single query test“select * from mytest limit 5”, most time it result in exception:

.....

Caused by: java.net.ConnectException: Connection timed out: connect
    at org.apache.thrift.transport.TSocket.open(TSocket.java:221)

it success very occassionally, but it has no problem using beeline .

here is my hiveserver2 log:

```<code>2017-03-28T09:59:28,347 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslServerTransport: transport map does not contain key
2017-03-28T09:59:28,347 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: opening transport org.apache.thrift.transport.TSaslServerTransport@4568f03
2017-03-28T09:59:28,464 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: SERVER: Received message with status START and payload length 5
2017-03-28T09:59:28,464 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslServerTransport: Received start message with status START
2017-03-28T09:59:28,464 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslServerTransport: Received mechanism name 'PLAIN'
2017-03-28T09:59:28,465 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: SERVER: Start message handled
2017-03-28T09:59:28,465 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: SERVER: Received message with status COMPLETE and payload length 10
2017-03-28T09:59:28,569 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: SERVER: Writing message with status COMPLETE and payload length 0
2017-03-28T09:59:28,569 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: SERVER: Main negotiation loop complete
2017-03-28T09:59:28,570 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslServerTransport: transport map does contain key org.apache.thrift.transport.TSocket@a916021
2017-03-28T09:59:28,858 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: SERVER: reading data length: 114
2017-03-28T09:59:28,858  INFO [HiveServer2-Handler-Pool: Thread-133] thrift.ThriftCLIService: Client protocol version: HIVE_CLI_SERVICE_PROTOCOL_V9
2017-03-28T09:59:28,858 DEBUG [HiveServer2-Handler-Pool: Thread-133] thrift.ThriftCLIService: Client's IP Address: 192.168.190.168
2017-03-28T09:59:28,858 DEBUG [HiveServer2-Handler-Pool: Thread-133] thrift.ThriftCLIService: Client's username: hive
2017-03-28T09:59:28,858 DEBUG [HiveServer2-Handler-Pool: Thread-133] thrift.ThriftCLIService: Client's IP Address: 192.168.190.168
2017-03-28T09:59:28,860 DEBUG [HiveServer2-Handler-Pool: Thread-133] session.SessionState: SessionState user: hive
2017-03-28T09:59:28,862 DEBUG [HiveServer2-Handler-Pool: Thread-133] hdfs.BlockReaderLocal: dfs.client.use.legacy.blockreader.local = false
2017-03-28T09:59:28,862 DEBUG [HiveServer2-Handler-Pool: Thread-133] hdfs.BlockReaderLocal: dfs.client.read.shortcircuit = false
2017-03-28T09:59:28,862 DEBUG [HiveServer2-Handler-Pool: Thread-133] hdfs.BlockReaderLocal: dfs.client.domain.socket.data.traffic = false
2017-03-28T09:59:28,862 DEBUG [HiveServer2-Handler-Pool: Thread-133] hdfs.BlockReaderLocal: dfs.domain.socket.path =
2017-03-28T09:59:28,863 DEBUG [HiveServer2-Handler-Pool: Thread-133] retry.RetryUtils: multipleLinearRandomRetry = null
2017-03-28T09:59:28,864 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.Client: getting client out of cache: org.apache.hadoop.ipc.Client@78d39a69
2017-03-28T09:59:28,864 DEBUG [HiveServer2-Handler-Pool: Thread-133] sasl.DataTransferSaslUtil: DataTransferProtocol not using SaslPropertiesResolver, no QOP found in configuration for dfs.data.transfer.protection
2017-03-28T09:59:28,865 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.Client: The ping interval is 60000 ms.
2017-03-28T09:59:28,865 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.Client: Connecting to node25/192.168.156.25:9000
2017-03-28T09:59:28,866 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive: starting, having connections 1
2017-03-28T09:59:28,868 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #47
2017-03-28T09:59:28,883 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #47
2017-03-28T09:59:28,883 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: getFileInfo took 18ms
2017-03-28T09:59:28,884 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #48
2017-03-28T09:59:28,885 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #48
2017-03-28T09:59:28,886 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: getFileInfo took 2ms
2017-03-28T09:59:28,886 DEBUG [HiveServer2-Handler-Pool: Thread-133] session.SessionState: HDFS root scratch dir: /tmp/hive with schema null, permission: rwx-wx-wx
2017-03-28T09:59:28,886 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #49
2017-03-28T09:59:28,887 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #49
2017-03-28T09:59:28,888 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: getFileInfo took 1ms
2017-03-28T09:59:28,889 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #50
2017-03-28T09:59:28,890 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #50
2017-03-28T09:59:28,890 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: getFileInfo took 1ms
2017-03-28T09:59:28,890 DEBUG [HiveServer2-Handler-Pool: Thread-133] hdfs.DFSClient: /tmp/hive/hive/d67b7df6-60fc-483b-888e-94c08c430980: masked=rwx------
2017-03-28T09:59:28,891 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #51
2017-03-28T09:59:28,901 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #51
2017-03-28T09:59:28,901 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: mkdirs took 10ms
2017-03-28T09:59:28,901  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Created HDFS directory: /tmp/hive/hive/d67b7df6-60fc-483b-888e-94c08c430980
2017-03-28T09:59:28,902 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #52
2017-03-28T09:59:28,902 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #52
2017-03-28T09:59:28,903 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: getFileInfo took 1ms
2017-03-28T09:59:28,910  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Created local directory: /root/yuxh/app/apache-hive-2.2.0-SNAPSHOT-bin/scratchdir/d67b7df6-60fc-483b-888e-94c08c430980
2017-03-28T09:59:28,911 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #53
2017-03-28T09:59:28,912 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #53
2017-03-28T09:59:28,912 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: getFileInfo took 1ms
2017-03-28T09:59:28,913 DEBUG [HiveServer2-Handler-Pool: Thread-133] hdfs.DFSClient: /tmp/hive/hive/d67b7df6-60fc-483b-888e-94c08c430980/_tmp_space.db: masked=rwx------
2017-03-28T09:59:28,913 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #54
2017-03-28T09:59:28,918 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #54
2017-03-28T09:59:28,919 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: mkdirs took 6ms
2017-03-28T09:59:28,919  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Created HDFS directory: /tmp/hive/hive/d67b7df6-60fc-483b-888e-94c08c430980/_tmp_space.db
2017-03-28T09:59:28,920 DEBUG [HiveServer2-Handler-Pool: Thread-133] session.HiveSessionImpl: Global init file /root/yuxh/app/apache-hive-2.2.0-SNAPSHOT-bin/apache-hive-2.2.0-SNAPSHOT-bin/conf does not exist
2017-03-28T09:59:28,920 DEBUG [HiveServer2-Handler-Pool: Thread-133] conf.VariableSubstitution: Substitution is on: hive
2017-03-28T09:59:28,920  INFO [HiveServer2-Handler-Pool: Thread-133] session.HiveSessionImpl: Operation log session directory is created: /root/yuxh/app/apache-hive-2.2.0-SNAPSHOT-bin/apache-hive-2.2.0-SNAPSHOT-bin/bin/${system:java.io.tmpdir}/${system:user.name}/operation_logs/d67b7df6-60fc-483b-888e-94c08c430980
2017-03-28T09:59:28,921  INFO [HiveServer2-Handler-Pool: Thread-133] service.CompositeService: Session opened, SessionHandle [d67b7df6-60fc-483b-888e-94c08c430980], current sessions:2
2017-03-28T09:59:28,921 DEBUG [HiveServer2-Handler-Pool: Thread-133] cli.CLIService: SessionHandle [d67b7df6-60fc-483b-888e-94c08c430980]: openSession()
2017-03-28T09:59:28,921 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: writing data length: 169
2017-03-28T09:59:38,914 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive: closed
2017-03-28T09:59:38,914 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive: stopped, remaining connections 0
2017-03-28T09:59:50,241 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: SERVER: reading data length: 83
2017-03-28T09:59:50,241  INFO [HiveServer2-Handler-Pool: Thread-133] service.CompositeService: Session closed, SessionHandle [d67b7df6-60fc-483b-888e-94c08c430980], current sessions:1
2017-03-28T09:59:50,242  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Updating thread name to d67b7df6-60fc-483b-888e-94c08c430980 HiveServer2-Handler-Pool: Thread-133
2017-03-28T09:59:50,243  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Resetting thread name to  HiveServer2-Handler-Pool: Thread-133
2017-03-28T09:59:50,243  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Updating thread name to d67b7df6-60fc-483b-888e-94c08c430980 HiveServer2-Handler-Pool: Thread-133
2017-03-28T09:59:50,244  INFO [HiveServer2-Handler-Pool: Thread-133] session.HiveSessionImpl: Operation log session directory is deleted: /root/yuxh/app/apache-hive-2.2.0-SNAPSHOT-bin/apache-hive-2.2.0-SNAPSHOT-bin/bin/${system:java.io.tmpdir}/${system:user.name}/operation_logs/d67b7df6-60fc-483b-888e-94c08c430980
2017-03-28T09:59:50,244  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Resetting thread name to  HiveServer2-Handler-Pool: Thread-133
2017-03-28T09:59:50,244 DEBUG [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Removing resource dir /root/yuxh/app/apache-hive-2.2.0-SNAPSHOT-bin/resources/d67b7df6-60fc-483b-888e-94c08c430980_resources
2017-03-28T09:59:50,245 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.Client: The ping interval is 60000 ms.
2017-03-28T09:59:50,246 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.Client: Connecting to node25/192.168.156.25:9000
2017-03-28T09:59:50,247 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive: starting, having connections 1
2017-03-28T09:59:50,247 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #55
2017-03-28T09:59:50,259 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #55
2017-03-28T09:59:50,260 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: delete took 14ms
2017-03-28T09:59:50,260  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Deleted directory: /tmp/hive/hive/d67b7df6-60fc-483b-888e-94c08c430980 on fs with scheme hdfs
2017-03-28T09:59:50,261  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Deleted directory: /root/yuxh/app/apache-hive-2.2.0-SNAPSHOT-bin/scratchdir/d67b7df6-60fc-483b-888e-94c08c430980 on fs with scheme file
2017-03-28T09:59:50,263 DEBUG [HiveServer2-Handler-Pool: Thread-133] metastore.ObjectStore: Cleared ClassLoaderResolverImpl: 0,0,0
2017-03-28T09:59:50,264 DEBUG [HiveServer2-Handler-Pool: Thread-133] metastore.ObjectStore: Removed cached classloaders from DataNucleus NucleusContext
2017-03-28T09:59:50,264 DEBUG [HiveServer2-Handler-Pool: Thread-133] metadata.Hive: Closing current thread's connection to Hive Metastore.
2017-03-28T09:59:50,264 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.Client: stopping client from cache: org.apache.hadoop.ipc.Client@78d39a69
2017-03-28T09:59:50,265 DEBUG [HiveServer2-Handler-Pool: Thread-133] cli.CLIService: SessionHandle [d67b7df6-60fc-483b-888e-94c08c430980]: closeSession()
2017-03-28T09:59:50,265 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: writing data length: 40
2017-03-28T10:00:00,249 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive: closed
2017-03-28T10:00:00,249 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive: stopped, remaining connections 0
</code>```

It seems it doesn't even trigger the query,I think there is some configurations in hive to set.

答: I think it must be network problem(my local pc connect the cluster network with vpn),it's ok after I run the program within one of the cluster  node.</p>

Title: hive jdbc connection time out

Body:
I install hive2.2 on server node25,and tried to access hiveserver2 using jdbc with  a single query test“select * from mytest limit 5”, most time it result in exception:

.....

Caused by: java.net.ConnectException: Connection timed out: connect
    at org.apache.thrift.transport.TSocket.open(TSocket.java:221)

it success very occassionally, but it has no problem using beeline .

here is my hiveserver2 log:

2017-03-28T09:59:28,347 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslServerTransport: transport map does not contain key
2017-03-28T09:59:28,347 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: opening transport org.apache.thrift.transport.TSaslServerTransport@4568f03
2017-03-28T09:59:28,464 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: SERVER: Received message with status START and payload length 5
2017-03-28T09:59:28,464 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslServerTransport: Received start message with status START
2017-03-28T09:59:28,464 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslServerTransport: Received mechanism name 'PLAIN'
2017-03-28T09:59:28,465 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: SERVER: Start message handled
2017-03-28T09:59:28,465 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: SERVER: Received message with status COMPLETE and payload length 10
2017-03-28T09:59:28,569 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: SERVER: Writing message with status COMPLETE and payload length 0
2017-03-28T09:59:28,569 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: SERVER: Main negotiation loop complete
2017-03-28T09:59:28,570 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslServerTransport: transport map does contain key org.apache.thrift.transport.TSocket@a916021
2017-03-28T09:59:28,858 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: SERVER: reading data length: 114
2017-03-28T09:59:28,858  INFO [HiveServer2-Handler-Pool: Thread-133] thrift.ThriftCLIService: Client protocol version: HIVE_CLI_SERVICE_PROTOCOL_V9
2017-03-28T09:59:28,858 DEBUG [HiveServer2-Handler-Pool: Thread-133] thrift.ThriftCLIService: Client's IP Address: 192.168.190.168
2017-03-28T09:59:28,858 DEBUG [HiveServer2-Handler-Pool: Thread-133] thrift.ThriftCLIService: Client's username: hive
2017-03-28T09:59:28,858 DEBUG [HiveServer2-Handler-Pool: Thread-133] thrift.ThriftCLIService: Client's IP Address: 192.168.190.168
2017-03-28T09:59:28,860 DEBUG [HiveServer2-Handler-Pool: Thread-133] session.SessionState: SessionState user: hive
2017-03-28T09:59:28,862 DEBUG [HiveServer2-Handler-Pool: Thread-133] hdfs.BlockReaderLocal: dfs.client.use.legacy.blockreader.local = false
2017-03-28T09:59:28,862 DEBUG [HiveServer2-Handler-Pool: Thread-133] hdfs.BlockReaderLocal: dfs.client.read.shortcircuit = false
2017-03-28T09:59:28,862 DEBUG [HiveServer2-Handler-Pool: Thread-133] hdfs.BlockReaderLocal: dfs.client.domain.socket.data.traffic = false
2017-03-28T09:59:28,862 DEBUG [HiveServer2-Handler-Pool: Thread-133] hdfs.BlockReaderLocal: dfs.domain.socket.path =
2017-03-28T09:59:28,863 DEBUG [HiveServer2-Handler-Pool: Thread-133] retry.RetryUtils: multipleLinearRandomRetry = null
2017-03-28T09:59:28,864 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.Client: getting client out of cache: org.apache.hadoop.ipc.Client@78d39a69
2017-03-28T09:59:28,864 DEBUG [HiveServer2-Handler-Pool: Thread-133] sasl.DataTransferSaslUtil: DataTransferProtocol not using SaslPropertiesResolver, no QOP found in configuration for dfs.data.transfer.protection
2017-03-28T09:59:28,865 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.Client: The ping interval is 60000 ms.
2017-03-28T09:59:28,865 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.Client: Connecting to node25/192.168.156.25:9000
2017-03-28T09:59:28,866 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive: starting, having connections 1
2017-03-28T09:59:28,868 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #47
2017-03-28T09:59:28,883 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #47
2017-03-28T09:59:28,883 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: getFileInfo took 18ms
2017-03-28T09:59:28,884 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #48
2017-03-28T09:59:28,885 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #48
2017-03-28T09:59:28,886 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: getFileInfo took 2ms
2017-03-28T09:59:28,886 DEBUG [HiveServer2-Handler-Pool: Thread-133] session.SessionState: HDFS root scratch dir: /tmp/hive with schema null, permission: rwx-wx-wx
2017-03-28T09:59:28,886 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #49
2017-03-28T09:59:28,887 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #49
2017-03-28T09:59:28,888 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: getFileInfo took 1ms
2017-03-28T09:59:28,889 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #50
2017-03-28T09:59:28,890 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #50
2017-03-28T09:59:28,890 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: getFileInfo took 1ms
2017-03-28T09:59:28,890 DEBUG [HiveServer2-Handler-Pool: Thread-133] hdfs.DFSClient: /tmp/hive/hive/d67b7df6-60fc-483b-888e-94c08c430980: masked=rwx------
2017-03-28T09:59:28,891 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #51
2017-03-28T09:59:28,901 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #51
2017-03-28T09:59:28,901 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: mkdirs took 10ms
2017-03-28T09:59:28,901  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Created HDFS directory: /tmp/hive/hive/d67b7df6-60fc-483b-888e-94c08c430980
2017-03-28T09:59:28,902 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #52
2017-03-28T09:59:28,902 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #52
2017-03-28T09:59:28,903 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: getFileInfo took 1ms
2017-03-28T09:59:28,910  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Created local directory: /root/yuxh/app/apache-hive-2.2.0-SNAPSHOT-bin/scratchdir/d67b7df6-60fc-483b-888e-94c08c430980
2017-03-28T09:59:28,911 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #53
2017-03-28T09:59:28,912 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #53
2017-03-28T09:59:28,912 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: getFileInfo took 1ms
2017-03-28T09:59:28,913 DEBUG [HiveServer2-Handler-Pool: Thread-133] hdfs.DFSClient: /tmp/hive/hive/d67b7df6-60fc-483b-888e-94c08c430980/_tmp_space.db: masked=rwx------
2017-03-28T09:59:28,913 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #54
2017-03-28T09:59:28,918 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #54
2017-03-28T09:59:28,919 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: mkdirs took 6ms
2017-03-28T09:59:28,919  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Created HDFS directory: /tmp/hive/hive/d67b7df6-60fc-483b-888e-94c08c430980/_tmp_space.db
2017-03-28T09:59:28,920 DEBUG [HiveServer2-Handler-Pool: Thread-133] session.HiveSessionImpl: Global init file /root/yuxh/app/apache-hive-2.2.0-SNAPSHOT-bin/apache-hive-2.2.0-SNAPSHOT-bin/conf does not exist
2017-03-28T09:59:28,920 DEBUG [HiveServer2-Handler-Pool: Thread-133] conf.VariableSubstitution: Substitution is on: hive
2017-03-28T09:59:28,920  INFO [HiveServer2-Handler-Pool: Thread-133] session.HiveSessionImpl: Operation log session directory is created: /root/yuxh/app/apache-hive-2.2.0-SNAPSHOT-bin/apache-hive-2.2.0-SNAPSHOT-bin/bin/${system:java.io.tmpdir}/${system:user.name}/operation_logs/d67b7df6-60fc-483b-888e-94c08c430980
2017-03-28T09:59:28,921  INFO [HiveServer2-Handler-Pool: Thread-133] service.CompositeService: Session opened, SessionHandle [d67b7df6-60fc-483b-888e-94c08c430980], current sessions:2
2017-03-28T09:59:28,921 DEBUG [HiveServer2-Handler-Pool: Thread-133] cli.CLIService: SessionHandle [d67b7df6-60fc-483b-888e-94c08c430980]: openSession()
2017-03-28T09:59:28,921 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: writing data length: 169
2017-03-28T09:59:38,914 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive: closed
2017-03-28T09:59:38,914 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive: stopped, remaining connections 0
2017-03-28T09:59:50,241 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: SERVER: reading data length: 83
2017-03-28T09:59:50,241  INFO [HiveServer2-Handler-Pool: Thread-133] service.CompositeService: Session closed, SessionHandle [d67b7df6-60fc-483b-888e-94c08c430980], current sessions:1
2017-03-28T09:59:50,242  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Updating thread name to d67b7df6-60fc-483b-888e-94c08c430980 HiveServer2-Handler-Pool: Thread-133
2017-03-28T09:59:50,243  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Resetting thread name to  HiveServer2-Handler-Pool: Thread-133
2017-03-28T09:59:50,243  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Updating thread name to d67b7df6-60fc-483b-888e-94c08c430980 HiveServer2-Handler-Pool: Thread-133
2017-03-28T09:59:50,244  INFO [HiveServer2-Handler-Pool: Thread-133] session.HiveSessionImpl: Operation log session directory is deleted: /root/yuxh/app/apache-hive-2.2.0-SNAPSHOT-bin/apache-hive-2.2.0-SNAPSHOT-bin/bin/${system:java.io.tmpdir}/${system:user.name}/operation_logs/d67b7df6-60fc-483b-888e-94c08c430980
2017-03-28T09:59:50,244  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Resetting thread name to  HiveServer2-Handler-Pool: Thread-133
2017-03-28T09:59:50,244 DEBUG [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Removing resource dir /root/yuxh/app/apache-hive-2.2.0-SNAPSHOT-bin/resources/d67b7df6-60fc-483b-888e-94c08c430980_resources
2017-03-28T09:59:50,245 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.Client: The ping interval is 60000 ms.
2017-03-28T09:59:50,246 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.Client: Connecting to node25/192.168.156.25:9000
2017-03-28T09:59:50,247 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive: starting, having connections 1
2017-03-28T09:59:50,247 DEBUG [IPC Parameter Sending Thread #4] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive sending #55
2017-03-28T09:59:50,259 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive got value #55
2017-03-28T09:59:50,260 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.ProtobufRpcEngine: Call: delete took 14ms
2017-03-28T09:59:50,260  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Deleted directory: /tmp/hive/hive/d67b7df6-60fc-483b-888e-94c08c430980 on fs with scheme hdfs
2017-03-28T09:59:50,261  INFO [HiveServer2-Handler-Pool: Thread-133] session.SessionState: Deleted directory: /root/yuxh/app/apache-hive-2.2.0-SNAPSHOT-bin/scratchdir/d67b7df6-60fc-483b-888e-94c08c430980 on fs with scheme file
2017-03-28T09:59:50,263 DEBUG [HiveServer2-Handler-Pool: Thread-133] metastore.ObjectStore: Cleared ClassLoaderResolverImpl: 0,0,0
2017-03-28T09:59:50,264 DEBUG [HiveServer2-Handler-Pool: Thread-133] metastore.ObjectStore: Removed cached classloaders from DataNucleus NucleusContext
2017-03-28T09:59:50,264 DEBUG [HiveServer2-Handler-Pool: Thread-133] metadata.Hive: Closing current thread's connection to Hive Metastore.
2017-03-28T09:59:50,264 DEBUG [HiveServer2-Handler-Pool: Thread-133] ipc.Client: stopping client from cache: org.apache.hadoop.ipc.Client@78d39a69
2017-03-28T09:59:50,265 DEBUG [HiveServer2-Handler-Pool: Thread-133] cli.CLIService: SessionHandle [d67b7df6-60fc-483b-888e-94c08c430980]: closeSession()
2017-03-28T09:59:50,265 DEBUG [HiveServer2-Handler-Pool: Thread-133] transport.TSaslTransport: writing data length: 40
2017-03-28T10:00:00,249 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive: closed
2017-03-28T10:00:00,249 DEBUG [IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive] ipc.Client: IPC Client (1279469670) connection to node25/192.168.156.25:9000 from hive: stopped, remaining connections 0

It seems it doesn't even trigger the query,I think there is some configurations in hive to set.


问:
How to configure log4j for a Spark program running inside of Intellij?
I've tried all possible suggestion on google but I still get spark log with INFO level which is too verbose. </p>

```<code>import org.apache.log4j.{Level, LogManager, Logger}
import org.apache.spark.sql.SparkSession

object  tmp {

  def main(args: Array[String]): Unit = {
    val spark =  SparkSession.builder()
      .master("local[*]")
      .getOrCreate()

    spark.sparkContext.setLogLevel("ERROR")

    LogManager.getRootLogger.setLevel(Level.ERROR)
    val rootLogger = Logger.getRootLogger()
    rootLogger.setLevel(Level.ERROR)

    Logger.getLogger("org").setLevel(Level.OFF)
    Logger.getLogger("akka").setLevel(Level.OFF)

    spark.read.json("/home/white/wk/tmp/people.json").show
  }
}
</code>```

答:
Here's a log4j.properties file you might want to use:

```<code>#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy tpInputOf the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# Set everything to be logged to the console
log4j.rootCategory=WARN, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{1}: %m%n

# Set the default spark-shell log level to WARN. When running the spark-shell, the
# log level for this class is used to overwrite the root logger's log level, so that
# the user can have different defaults for the shell and regular Spark apps.
log4j.logger.org.apache.spark.repl.Main=WARN

# Settings to quiet third party logs that are too verbose
log4j.logger.org.spark_project.jetty=WARN
log4j.logger.org.spark_project.jetty.util.component.AbstractLifeCycle=ERROR
log4j.logger.org.apache.spark.repl.SparkIMain$exprTyper=INFO
log4j.logger.org.apache.spark.repl.SparkILoop$SparkILoopInterpreter=INFO
log4j.logger.org.apache.parquet=ERROR
log4j.logger.parquet=ERROR

# SPARK-9183: Settings to avoid annoying messages when looking up nonexistent UDFs in SparkSQL with Hive support
log4j.logger.org.apache.hadoop.hive.metastore.RetryingHMSHandler=FATAL
log4j.logger.org.apache.hadoop.hive.ql.exec.FunctionRegistry=ERROR
</code>```

It sets the log4j.rootCategory to WARN. You can use ERROR if you want less messages. Put this file in the root of your classpath. If you have a Maven project, that would be src/main/resources.

Body:
I've tried all possible suggestion on google but I still get spark log with INFO level which is too verbose.

import org.apache.log4j.{Level, LogManager, Logger}
import org.apache.spark.sql.SparkSession

object  tmp {

  def main(args: Array[String]): Unit = {
    val spark =  SparkSession.builder()
      .master("local[*]")
      .getOrCreate()

    spark.sparkContext.setLogLevel("ERROR")

    LogManager.getRootLogger.setLevel(Level.ERROR)
    val rootLogger = Logger.getRootLogger()
    rootLogger.setLevel(Level.ERROR)

    Logger.getLogger("org").setLevel(Level.OFF)
    Logger.getLogger("akka").setLevel(Level.OFF)

    spark.read.json("/home/white/wk/tmp/people.json").show
  }
}

Body:
Here's a log4j.properties file you might want to use:

#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy tpInputOf the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# Set everything to be logged to the console
log4j.rootCategory=WARN, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{1}: %m%n

# Set the default spark-shell log level to WARN. When running the spark-shell, the
# log level for this class is used to overwrite the root logger's log level, so that
# the user can have different defaults for the shell and regular Spark apps.
log4j.logger.org.apache.spark.repl.Main=WARN

# Settings to quiet third party logs that are too verbose
log4j.logger.org.spark_project.jetty=WARN
log4j.logger.org.spark_project.jetty.util.component.AbstractLifeCycle=ERROR
log4j.logger.org.apache.spark.repl.SparkIMain$exprTyper=INFO
log4j.logger.org.apache.spark.repl.SparkILoop$SparkILoopInterpreter=INFO
log4j.logger.org.apache.parquet=ERROR
log4j.logger.parquet=ERROR

# SPARK-9183: Settings to avoid annoying messages when looking up nonexistent UDFs in SparkSQL with Hive support
log4j.logger.org.apache.hadoop.hive.metastore.RetryingHMSHandler=FATAL
log4j.logger.org.apache.hadoop.hive.ql.exec.FunctionRegistry=ERROR

It sets the log4j.rootCategory to WARN. You can use ERROR if you want less messages. Put this file in the root of your classpath. If you have a Maven project, that would be src/main/resources.


答:
Your code is just one big mistake. You do not understand basic principles of working with arrays. Do not just use my solution, please read some articles about iterating and getting an element from an array. This one should work:</p>

```<code>function inverted(bools) {
  var i, _i, inversion = [];

  for(i = 0, _i = bools.length; i < _i; i++){
    inversion[i] = !bools[i];
  }
  return inversion;
}
</code>```

Title: Invert an array of booleans in JavaScript

Body:
Your code is just one big mistake. You do not understand basic principles of working with arrays. Do not just use my solution, please read some articles about iterating and getting an element from an array. This one should work:

function inverted(bools) {
  var i, _i, inversion = [];

  for(i = 0, _i = bools.length; i < _i; i++){
    inversion[i] = !bools[i];
  }
  return inversion;
}


问:
System design: whether to normalize the departments or not
I'm working with two consultants in one project. The thing is we reached a point where both of them cannot get into an agreement and each offer a different approach.

The thing is we have a store with four departments and we want to find the best approach for working with all of them in the same database.

Each department sell different products: Cars, Boats, Jetskies and Motorbikes.

When the data is inserted or updated in each department there are some triggers to be fires so different workflows will begin, when adding a new car there are certain requirements that needs to be checked as well as the details of the car that are completely different than a boat. Also, regarding the data there are not many fields there are in common, I would say so far only the brand, color, model and year, everything else is specific for each deparment due to the different products and how they work with them..

Consultant one says:

Create one table for all the departments and use a column to identify what department the row belongs to, this way you will have only one trigger and inside the trigger you will then call the function/mehod you need for each record type.

Reason: you only have one table (with over 200 fields) and one trigger, is easier to maintain. Also if you need to report you just need to query one table and filter based on the record type. If you need to report for all the items you don't need to have multiple joins.

Consultant two says:

Create one table for each deparment and a trigger for each table.

Reason: you will have smaller tables (aprox 50 fields each) and is more flexible and you have it all separated. If you want to report you need to join the tables as you want to include data from different places.

I see the advantages of having everything in one place but if I want to expand or change anything I have the feeling I will bre creating a beast table as the data grows.

On the other side keep it separated look more appealing but will need to setup everything for each different table.

What would you say is the best approach?

答:
You should probably listen to consultant number two.

The thing is, all design is trade-offs.  You need to assess the pros and cons of each approach and you need to think about the risks that each design entails.

What happens when your design grows?  (department 5, more details per product type,...)

What happens when the system scales up to higher transaction volumes?

What happens when your business rules change?

I've been doing this for a long time and I've seen some pendulums swing back and forth when it comes to what is "in fashion" as far as database and software best practices.

I'd say right now the prevailing wisdom is that separation of concerns is innately good.  This means you should keep your program logic (trigger code) separate for each department.  This makes sense because your logic will vary from one product type to the next since they mostly have distinct columns.

This second point is also important, because your stake in the ground for a transactional system should always be start with third normal form (or higher, if necessary).  Sometimes you can get away without it, but four different types of objects with 40 or more distinct attributes each doesn't sound like a good candidate for jamming everything into one table.  How do you keep track of which columns belong to which type of product, for example?  A separate table for each product type keeps this clean and simple - and importantly - easy for your support programmers to understand.

Contrary to what consultant one is saying, having one trigger instead of four is not likely to be easier to maintain if that one trigger is a big bowl of spaghetti, or even four tidy, well written subroutines joined together with a switch type statement.

These days, programmers favour short, atomic, single-purpose functions (triggers, in your case).

If there is enough common data and common business logic that doing it four times seems awkward, then maybe you have a good candidate for a super-type / sub-type design.


问:
Debugging with Gdb in RISCV (spike: unrecognized option --gdb-port)
After building the RISCV tools and GCC (cloned from lowrisc, isa-sim and not riscv-tools), i'm stuck in the debugging with Gdb phase here.

In the second terminal target remote in gdb times out.

In the first terminal when i run spike --gdb-port 9824 pk tests/debug or spike --gdb-port 9824 pk hello.c it yields:

```<code>spike: unrecognized option --gdb-port
usage: spike [host options] <target program> [target options]
Host Options:
  -p <n>             Simulate <n> processors
  -m <n>             Provide <n> MB of target memory
  -d                 Interactive debug mode
  -g                 Track histogram of PCs
  -h                 Print this help message
  --ic=<S>:<W>:<B>   Instantiate a cache model with S sets,
  --dc=<S>:<W>:<B>     W ways, and B-byte blocks (with S and
  --l2=<S>:<W>:<B>     B both powers of 2).
  --extension=<name> Specify RoCC Extension
  --extlib=<name>    Shared library to load
</code>```

I don't know if it has to do with configuring gdb on its own ? Or is it built and configured when i ran ./build.sh for the riscv tools.

If not, could you please correct the --gdb-port command (I'm new to linux) I've tried --gdb-port=9824 or --gdb-port:9824 and it's the same.

Thank you

答:
Message spike: unrecognized option --gdb-port says that spike, not gdb can't recognize option. Spike is from riscv-isa-sim, not from riscv-tools. And LowRisc variant of Spike - https://github.com/lowRISC/riscv-isa-sim is many commits behind master:

This branch is 3 commits ahead, 172 commits behind riscv:master.
  Latest commit e220bc4  on May 19, 2016 @wsong83 wsong83 Merge commit '0d084d5' into update

One of not ported commit added gdb support to spike from https://github.com/riscv/riscv-isa-sim (and documented it in https://github.com/riscv/riscv-isa-sim#debugging-with-gdb), but it is not pulled to https://github.com/lowRISC/riscv-isa-sim (and not documented at https://github.com/lowRISC/riscv-isa-sim). gdb-related commits were from Oct 2016, Jun 2016, May 2016, and the --gdb-port was added in  d1d8863086c57f04236418f21ef8a7fbfc184b0b (Mar 19, 2016) https://github.com/riscv/riscv-isa-sim/commit/d1d8863086c57f04236418f21ef8a7fbfc184b0b

```<code>+  fprintf(stderr, "  --gdb-port=<port>  Listen on <port> for gdb to connect\n");
+  parser.option(0, "gdb-port", 1, [&](const char* s){gdb_port = atoi(s);});
</code>```

You can try merging changes between isa sims or ask lowRisc authors to merge or just try to use spike from riscv...

Body:
After building the RISCV tools and GCC (cloned from lowrisc, isa-sim and not riscv-tools), i'm stuck in the debugging with Gdb phase here.

In the second terminal target remote in gdb times out.

In the first terminal when i run spike --gdb-port 9824 pk tests/debug or spike --gdb-port 9824 pk hello.c it yields:

spike: unrecognized option --gdb-port
usage: spike [host options] <target program> [target options]
Host Options:
  -p <n>             Simulate <n> processors
  -m <n>             Provide <n> MB of target memory
  -d                 Interactive debug mode
  -g                 Track histogram of PCs
  -h                 Print this help message
  --ic=<S>:<W>:   Instantiate a cache model with S sets,
  --dc=<S>:<W>:     W ways, and B-byte blocks (with S and
  --l2=<S>:<W>:     B both powers of 2).
  --extension=<name> Specify RoCC Extension
  --extlib=<name>    Shared library to load

I don't know if it has to do with configuring gdb on its own ? Or is it built and configured when i ran ./build.sh for the riscv tools.

If not, could you please correct the --gdb-port command (I'm new to linux) I've tried --gdb-port=9824 or --gdb-port:9824 and it's the same.

Thank you

Body:
Message spike: unrecognized option --gdb-port says that spike, not gdb can't recognize option. Spike is from riscv-isa-sim, not from riscv-tools. And LowRisc variant of Spike - https://github.com/lowRISC/riscv-isa-sim is many commits behind master:

This branch is 3 commits ahead, 172 commits behind riscv:master.
  Latest commit e220bc4  on May 19, 2016 @wsong83 wsong83 Merge commit '0d084d5' into update

One of not ported commit added gdb support to spike from https://github.com/riscv/riscv-isa-sim (and documented it in https://github.com/riscv/riscv-isa-sim#debugging-with-gdb), but it is not pulled to https://github.com/lowRISC/riscv-isa-sim (and not documented at https://github.com/lowRISC/riscv-isa-sim). gdb-related commits were from Oct 2016, Jun 2016, May 2016, and the --gdb-port was added in  d1d8863086c57f04236418f21ef8a7fbfc184b0b (Mar 19, 2016) https://github.com/riscv/riscv-isa-sim/commit/d1d8863086c57f04236418f21ef8a7fbfc184b0b

+  fprintf(stderr, "  --gdb-port=<port>  Listen on <port> for gdb to connect\n");
+  parser.option(0, "gdb-port", 1, [&](const char* s){gdb_port = atoi(s);});

You can try merging changes between isa sims or ask lowRisc authors to merge or just try to use spike from riscv...


问:
Inconsistent behavior in JavaScript's conditional checking
I want to build an object obj1 with property obj2, which is another object.  To avoid redeclaring obj1 and obj2, I use the following code:

```<code>if (!obj1) obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1
</code>```

Assume, obj1 and obj1.obj2 aren't defined yet, the code causes the browser to report the error "obj1 is not defined".

If I change the code to:

```<code>if (typeof obj1==='undefined') obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1
</code>```

Then there's no error, while I think it should report "obj2 is not defined".  I'm puzzled as to why the JavaScript treats the short-hand falsy check of a reference and a property differently.  Can anyone shed a light on that?

答:
If you would do:

```<code>if (!window.obj1) window.obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
</code>```

You will find the code works as you expect.

obj1 isn't even a reference when you check it's existance; it's nothing. It doesn't exist because you haven't declared it (neither have you initialized it).

```<code>var obj1;

if (!obj1) obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
</code>```

This will also work because you've declared the existance of obj1; you just haven't initialized it.

All properties of an object that haven't been set hold the value undefined; which is why it responds to your short hand !obj1.obj2

```<code>var obj1 = {};
obj1.a === undefined // true;
</code>```

Variables however, must be defined before you can access them.

ContentLicense: CC BY-SA 2.5

Body:
I want to build an object obj1 with property obj2, which is another object.  To avoid redeclaring obj1 and obj2, I use the following code:

if (!obj1) obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1

Assume, obj1 and obj1.obj2 aren't defined yet, the code causes the browser to report the error "obj1 is not defined".

If I change the code to:

if (typeof obj1==='undefined') obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1

Then there's no error, while I think it should report "obj2 is not defined".  I'm puzzled as to why the JavaScript treats the short-hand falsy check of a reference and a property differently.  Can anyone shed a light on that?

Body:
If you would do:

if (!window.obj1) window.obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};

You will find the code works as you expect.

obj1 isn't even a reference when you check it's existance; it's nothing. It doesn't exist because you haven't declared it (neither have you initialized it).

var obj1;

if (!obj1) obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};

This will also work because you've declared the existance of obj1; you just haven't initialized it.

All properties of an object that haven't been set hold the value undefined; which is why it responds to your short hand !obj1.obj2

var obj1 = {};
obj1.a === undefined // true;

Variables however, must be defined before you can access them.


问:
Transform pivot not working, Incorrect Syntax near 'Sequence'
I'm new in ms access, version is 2005 when i try to test select query its working It display all the column name and its value.

```<code>$results = odbc_exec($connection, "SELECT TOP 5 Sequence
                     ,StoreId
                    ,Timestamp
                    ,BusinessDate
                    ,TerminalId
                    ,TerminalName
                    ,DrawerNumber
                    ,TransactionType
                    FROM [Site5].[dbo].[Transactions]
                    where [TransactionType] in ('eod','sod') and
                    businessdate = '2016-12-28' ORDER BY  Timestamp asc ");
</code>```

Now I trying to convert the TerminalId Column values into row but its not working here is my code

```<code>    $transform = odbc_exec($connection, "
        TRANSFORM MAX(Sequence)
        SELECT StoreId
        FROM Transactions
        GROUP BY StoreId
        PIVOT TerminalId
        ");
</code>```

Warning: odbc_exec(): SQL error: [Microsoft][SQL Server Native Client
  10.0][SQL Server]Line 2: Incorrect syntax near 'Sequence'., SQL state 37000

答:
fully qualified tables

```<code>$transform = odbc_exec($connection, "
        TRANSFORM MAX(Transactions.Sequence) As Seq
        SELECT Transactions.StoreId
        FROM Transactions
        GROUP BY Transactions.StoreId
        PIVOT Transactions.TerminalId
        ");
</code>```

or

```<code>$transform = odbc_exec($connection, "
        TRANSFORM MAX(Transactions.Sequence) As Seq
        SELECT Transactions.StoreId
        FROM [Site5].[dbo].Transactions
        GROUP BY Transactions.StoreId
        PIVOT Transactions.TerminalId
        ");
</code>```

Body:
I'm new in ms access, version is 2005 when i try to test select query its working It display all the column name and its value.

$results = odbc_exec($connection, "SELECT TOP 5 Sequence
                     ,StoreId
                    ,Timestamp
                    ,BusinessDate
                    ,TerminalId
                    ,TerminalName
                    ,DrawerNumber
                    ,TransactionType
                    FROM [Site5].[dbo].[Transactions]
                    where [TransactionType] in ('eod','sod') and
                    businessdate = '2016-12-28' ORDER BY  Timestamp asc ");

Now I trying to convert the TerminalId Column values into row but its not working here is my code

    $transform = odbc_exec($connection, "
        TRANSFORM MAX(Sequence)
        SELECT StoreId
        FROM Transactions
        GROUP BY StoreId
        PIVOT TerminalId
        ");

Warning: odbc_exec(): SQL error: [Microsoft][SQL Server Native Client
  10.0][SQL Server]Line 2: Incorrect syntax near 'Sequence'., SQL state 37000

Body:
fully qualified tables

$transform = odbc_exec($connection, "
        TRANSFORM MAX(Transactions.Sequence) As Seq
        SELECT Transactions.StoreId
        FROM Transactions
        GROUP BY Transactions.StoreId
        PIVOT Transactions.TerminalId
        ");

or

$transform = odbc_exec($connection, "
        TRANSFORM MAX(Transactions.Sequence) As Seq
        SELECT Transactions.StoreId
        FROM [Site5].[dbo].Transactions
        GROUP BY Transactions.StoreId
        PIVOT Transactions.TerminalId
        ");


问:
Referencing objects in java
In java, what is the difference between following 2 usage,

```<code>Employee e1 = new Employee();
1.Employee e2 = (Employee)e1.clone();
2.Employee e2 = e1;
</code>```

In second case, I think e2 reference to the object that e1 also reference. So, they have the same same object with different reference number(may be memory address).

How about first case? Do e1 and e2 have both different object and reference?

答:
The first creates a new object by cloning the data of the original object - the class must implement the Clonable interface (a good example is java.util.Calendar).

The second is merely another reference to the same object.

Title: Referencing objects in java

Body:
In java, what is the difference between following 2 usage,

Employee e1 = new Employee();
1.Employee e2 = (Employee)e1.clone();
2.Employee e2 = e1;

In second case, I think e2 reference to the object that e1 also reference. So, they have the same same object with different reference number(may be memory address).

How about first case? Do e1 and e2 have both different object and reference?


问:
Redux - how to call an action creator from inside another action creator?
I have the following action creator:

```<code>export function foo(param) {
    ...
}
</code>```

and I want to call it from an adjacent action creator (in the same file) like this:

```<code>export function bar(param){
    return (dispatch, getState) => {
        dispatch({
            type: ATYPE.SET_DO_THIS_BEFORE_FOO,
            payload: param
        });

        foo(param);
    }
}
</code>```

but the foo action creator is not firing from inside bar. Is there any way to do this?

答:
According to your example, it seems that you're already using redux-thunk. If that's the case, the only thing that you're forgetting is to dispatch the action created by your action creator:

```<code>dispatch(foo(param));
</code>```

Body:
I have the following action creator:

export function foo(param) {
    ...
}

and I want to call it from an adjacent action creator (in the same file) like this:

export function bar(param){
    return (dispatch, getState) => {
        dispatch({
            type: ATYPE.SET_DO_THIS_BEFORE_FOO,
            payload: param
        });

        foo(param);
    }
}

but the foo action creator is not firing from inside bar. Is there any way to do this?

Body:
According to your example, it seems that you're already using redux-thunk. If that's the case, the only thing that you're forgetting is to dispatch the action created by your action creator:

dispatch(foo(param));


问:
VSCode: Open file from file explorer with Enter key on Mac OSX
When using VSCode on Windows, I can navigate the file explorer and hit Enter on the focused file and the file will open in the editor. On my Mac, however, when I do this, VSCode will open the rename input as follows:

I'm not sure why it does this.  Even in other text editors (e.g. Atom), the default behavior is to open the file on Enter. Is there any way to change this behavior so that the file opens on Enter? The only workaround I've found so far is CTRL+Enter, which opens the file in a new pane, but with a 3 pane limit in VSCode, this is quite limiting.

答:
cmd+down does NOT work for me using VSCode 1.10.2 on Mac 10.10.5.

However, cmd+enter does work for me.

Or if you want to set your own keybinding to open a file from File Explorer, add these lines to your keybindings.json:

```<code>// open file from File Explorer
{ "key": "enter", "command": "list.select",
                     "when": "explorerViewletVisible && filesExplorerFocus" },
</code>```

(Of course, you can change enter to any key combination you want).

Body:
cmd+down does NOT work for me using VSCode 1.10.2 on Mac 10.10.5.

However, cmd+enter does work for me.

Or if you want to set your own keybinding to open a file from File Explorer, add these lines to your keybindings.json:

// open file from File Explorer
{ "key": "enter", "command": "list.select",
                     "when": "explorerViewletVisible && filesExplorerFocus" },

(Of course, you can change enter to any key combination you want).


问:
How to create a multiple selection list?
Basically for part of my university project I want to ask students their availability for a study buddy app. I want them to be able to have multiple options which they can select as well.

Below is the current code I have -

```<code>chosen =""
chosen_list=[]
available_list = ['Monday Morning', 'Monday Afternoon', 'Monday Evening', 'Tuesday Morning', 'Tuesday Afternoon', 'Tuesday Evening']
print ('What is your availability?')
while chosen !="0":
    print ('Available times:' + available_list)
    chosen = input('Choose a time or 0 to quit')
    if chosen in available_list:
        chosen_list.append(chosen)
        print (chosen_list)
</code>```

But I'm coming up with this error:

Traceback (most recent call last):

File "G:/University/Intro to Programming/Assessment Project/Step
  1/.idea/step1new.py", line 132, in  What is enter code
  hereyour availability?
      print ('Available times:' + available_list) TypeError: Can't convert 'list' object to str implicitly

Process finished with exit code 1

Can someone please advise me on this?

答:
The  error says TypeError: Can't convert 'list' object to str
  implicitly

You can try this

```<code>print ('Available times: ' + " ,".join(available_list))
</code>```

" ,".join(list) will convert a list in a string object as a result:

```<code>'Available times: Monday Morning, Monday Afternoon, Monday Evening, Tuesday Morning, Tuesday Afternoon, Tuesday Evening'
</code>```

Body:
Basically for part of my university project I want to ask students their availability for a study buddy app. I want them to be able to have multiple options which they can select as well.

Below is the current code I have -

chosen =""
chosen_list=[]
available_list = ['Monday Morning', 'Monday Afternoon', 'Monday Evening', 'Tuesday Morning', 'Tuesday Afternoon', 'Tuesday Evening']
print ('What is your availability?')
while chosen !="0":
    print ('Available times:' + available_list)
    chosen = input('Choose a time or 0 to quit')
    if chosen in available_list:
        chosen_list.append(chosen)
        print (chosen_list)

But I'm coming up with this error:

Traceback (most recent call last):

File "G:/University/Intro to Programming/Assessment Project/Step
  1/.idea/step1new.py", line 132, in  What is enter code
  hereyour availability?
      print ('Available times:' + available_list) TypeError: Can't convert 'list' object to str implicitly

Process finished with exit code 1

Can someone please advise me on this?

Body:
The  error says TypeError: Can't convert 'list' object to str
  implicitly

You can try this

print ('Available times: ' + " ,".join(available_list))

" ,".join(list) will convert a list in a string object as a result:

'Available times: Monday Morning, Monday Afternoon, Monday Evening, Tuesday Morning, Tuesday Afternoon, Tuesday Evening'


问:
Procedure for cloning Git repos that use subtree
I'm using Git's subtree command to pull a couple of libraries in to a project.

If I then clone the project in the normal way, I end up with all the code that I need, but I lose the subtree relationships - in the clone there is no remote for each of the libraries, and there is no -push branch for either of them.

What's the best way to re-establish this connection?

Is it sufficient to do

```<code>git remote add <lib> <remote-url>
git fetch <lib>
</code>```

If I was adding the library for the first time I'd follow that with:

```<code>git subtree add -P <local/lib> --squash "<lib>/master"
</code>```

This doesn't work when the local directory already exists though, which of course it will when you've cloned a project that has already had the library added to it.

Is there anything else that one should do in this situation, to ensure that subsequent git subtree merge and git subtree split commands to the expected thing?

答:
I ran across this question while migrating a project from using submodules to subtrees and ended up using neither (at least not directly, anyway) - I am now using the git-subrepo tool.

It solves this problem by adding a .gitrepo file at the root of each subtree. The .gitrepo file contains tracking information, including the remote URL, and is then included in subsequent clones. This really simplifies things and the only complication is that git-subrepo has to be separately installed on each development machine (though the repository is still usable without it).

Body:
I'm using Git's subtree command to pull a couple of libraries in to a project.

If I then clone the project in the normal way, I end up with all the code that I need, but I lose the subtree relationships - in the clone there is no remote for each of the libraries, and there is no -push branch for either of them.

What's the best way to re-establish this connection?

Is it sufficient to do

git remote add <lib> <remote-url>
git fetch <lib>

If I was adding the library for the first time I'd follow that with:

git subtree add -P <local/lib> --squash "<lib>/master"

This doesn't work when the local directory already exists though, which of course it will when you've cloned a project that has already had the library added to it.

Is there anything else that one should do in this situation, to ensure that subsequent git subtree merge and git subtree split commands to the expected thing?


问:
Memory Bandwidth Usage
How do you calculate memory (RAM) bandwidth used? Which performance counters are required?

I came across a tool that was able to do it, the "Rightmark multi-threaded memory test". But unlike the rest of Rightmark's tests, I haven't found the source code for it, just the binaries

答:
If your code can run on Linux, use Cachegrind:

Cachegrind is a cache profiler. It
  performs detailed simulation of the
  I1, D1 and L2 caches in your CPU and
  so can accurately pinpoint the sources
  of cache misses in your code. It
  identifies the number of cache misses,
  memory references and instructions
  executed for each line of source code,
  with per-function, per-module and
  whole-program summaries. It is useful
  with programs written in any language.
  Cachegrind runs programs about
  20--100x slower than normal.

You may want to use the KCacheGrind GUI.

Title: Memory Bandwidth Usage


问:
SWIFT - How to get Stream for Server
On client we can use CFStreamCreatePairWithSocketToHost to get ReadStream and WriteStream.

After the server got clientSocket how can we got ReadStream and WriteStreaam?

答:
```<code>import UIKit

class Connection: NSObject, NSStreamDelegate {
    var inputStream: NSInputStream!
    var outputStream: NSOutputStream!

    func connect() {
        var readStream:  Unmanaged<CFReadStream>?
        var writeStream: Unmanaged<CFWriteStream>?

        CFStreamCreatePairWithSocketToHost(nil, "193.10.1.22", 17, &readStream, &writeStream)

        self.inputStream = readStream!.takeRetainedValue()
        self.outputStream = writeStream!.takeRetainedValue()

        self.inputStream.delegate = self
        self.outputStream.delegate = self

        self.inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
        self.outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)

        self.inputStream.open()
        self.outputStream.open()
    }
}
</code>```

Title: SWIFT - How to get Stream for Server


问:
Taging and conditional autocomplete
I'm using http://aehlke.github.io/tag-it/ for taging and autocomplete. As of right now, I can autocomplete for a single term:

Console:

```<code>GET .../source.php?term=value01
</code>```

Javascript:

```<code>$("#input-newsearch-2").tagit({
singleField: true,
singleFieldDelimiter: ",",
allowSpaces: true,
autocomplete: ({
  source: function( request, response ) {
    //var tagterm = $('#input-newsearch-2').val();
    $.ajax({
      url: "source.php",
      dataType: "json",
      data: {
        //term: tagterm
        //term: $('#input-newsearch-2').val()
        term: request.term
      },
      //data: JSON.stringify({ term: $('#input-newsearch-2').val() }),
      success: function( data ) {
        response( data );
      }
    });
    console.log( request.term );
  },
    minLength: 3,
    select: function(event,ui){

    }

})

});
</code>```

... when hitting key enter the value gets tagged ( alert($('#input-newsearch-2').val() = value01) ) and I can search for the next term.

But when entering the next term, autocomplete searches the whole database each time again. I would like to filter the database considering the previous tags (AND WHERE)? How is this possible?

This is my html:

```<code><input id="input-newsearch-2" autocomplete="off" type="text">
// created by tagit
<ul class="tagit ui-widget ui-widget-content ui-corner-all">
<li class="tagit-choice ui-widget-content ui-state-default ui-corner-all tagit-choice-editable">
<li class="tagit-new">
    <input class="ui-widget-content ui-autocomplete-input" autocomplete="off" type="text">
</li>
</ul>
</code>```

... when I've tagged multiple values #input-newsearch-2 looks like:

```<code>$('#input-newsearch-2').val() = value01,value02,value03
</code>```

答:
Do you mean, you want to concatenate the new entered value to the previous entered value(s)?

You could concatenate the new entry to a globally declared variable.

```<code>// before/outside of tagit()...
var terms="";
</code>```

If the global variable has a length>0, then add a comma then the new entry, otherwise don't add the comma.

```<code>// concatenate when you wish:
if(terms.length>0){
    terms+=',';
}
$terms+=$('#input-newsearch-2').val();
</code>```

Then just add the global variable to ajax's data object, and the csv string should be delivered.

```<code>  data: {
    term: terms
  },
</code>```

Alternatively, you could concatenate new entries to an <input name="termstorage" type="hidden" value=""> element, and just have your ajax's collect that value.

I suppose in either instance, you'd also want to offer the ability to clear previous entries from memory.

Here is the php query build part...

I am making the assumption from your other recent/associated question that you are filtering against db columns: name & code

Also, any values entered by the user containing a comma will impact the query. Always, always sanitize user input.

This code uses a loop purely to demonstrate how three different inputs will generate different queries.  The loop will not be necessary in your actual case since your input is a single string.

Code: (Demo)

```<code>$mock_GET_term[]="";
$mock_GET_term[]="value01";
$mock_GET_term[]="value01,value02,value03";

foreach($mock_GET_term as $csv){
    $query="SELECT * FROM `accounts`";
    if(strlen($csv)>0){
        $where_cond=str_replace(',',"%' OR `name` LIKE '%",$csv);
        $query.=" WHERE (`name` LIKE '%{$where_cond}%'";
        $query.=" OR `code` LIKE '%{$where_cond}%')";
    }
    echo "Query = $query\n\n";
}
</code>```

Output:

```<code>Query = SELECT * FROM `accounts`

Query = SELECT * FROM `accounts` WHERE (`name` LIKE '%value01%' OR `code` LIKE '%value01%')

Query = SELECT * FROM `accounts` WHERE (`name` LIKE '%value01%' OR `name` LIKE '%value02%' OR `name` LIKE '%value03%' OR `code` LIKE '%value01%' OR `name` LIKE '%value02%' OR `name` LIKE '%value03%')
</code>```

Title: Taging and conditional autocomplete

Body:
I'm using http://aehlke.github.io/tag-it/ for taging and autocomplete. As of right now, I can autocomplete for a single term:

Console:

GET .../source.php?term=value01

Javascript:

$("#input-newsearch-2").tagit({
singleField: true,
singleFieldDelimiter: ",",
allowSpaces: true,
autocomplete: ({
  source: function( request, response ) {
    //var tagterm = $('#input-newsearch-2').val();
    $.ajax({
      url: "source.php",
      dataType: "json",
      data: {
        //term: tagterm
        //term: $('#input-newsearch-2').val()
        term: request.term
      },
      //data: JSON.stringify({ term: $('#input-newsearch-2').val() }),
      success: function( data ) {
        response( data );
      }
    });
    console.log( request.term );
  },
    minLength: 3,
    select: function(event,ui){

    }

})

});

... when hitting key enter the value gets tagged ( alert($('#input-newsearch-2').val() = value01) ) and I can search for the next term.

But when entering the next term, autocomplete searches the whole database each time again. I would like to filter the database considering the previous tags (AND WHERE)? How is this possible?

This is my html:

<input id="input-newsearch-2" autocomplete="off" type="text">
// created by tagit

    <input class="ui-widget-content ui-autocomplete-input" autocomplete="off" type="text">

... when I've tagged multiple values #input-newsearch-2 looks like:

$('#input-newsearch-2').val() = value01,value02,value03

Body:
Do you mean, you want to concatenate the new entered value to the previous entered value(s)?

You could concatenate the new entry to a globally declared variable.

// before/outside of tagit()...
var terms="";

If the global variable has a length>0, then add a comma then the new entry, otherwise don't add the comma.

// concatenate when you wish:
if(terms.length>0){
    terms+=',';
}
$terms+=$('#input-newsearch-2').val();

Then just add the global variable to ajax's data object, and the csv string should be delivered.

  data: {
    term: terms
  },

Alternatively, you could concatenate new entries to an <input name="termstorage" type="hidden" value=""> element, and just have your ajax's collect that value.

I suppose in either instance, you'd also want to offer the ability to clear previous entries from memory.

Here is the php query build part...

I am making the assumption from your other recent/associated question that you are filtering against db columns: name & code

Also, any values entered by the user containing a comma will impact the query. Always, always sanitize user input.

This code uses a loop purely to demonstrate how three different inputs will generate different queries.  The loop will not be necessary in your actual case since your input is a single string.

Code: (Demo)

$mock_GET_term[]="";
$mock_GET_term[]="value01";
$mock_GET_term[]="value01,value02,value03";

foreach($mock_GET_term as $csv){
    $query="SELECT * FROM `accounts`";
    if(strlen($csv)>0){
        $where_cond=str_replace(',',"%' OR `name` LIKE '%",$csv);
        $query.=" WHERE (`name` LIKE '%{$where_cond}%'";
        $query.=" OR `code` LIKE '%{$where_cond}%')";
    }
    echo "Query = $query\n\n";
}

Output:

Query = SELECT * FROM `accounts`

Query = SELECT * FROM `accounts` WHERE (`name` LIKE '%value01%' OR `code` LIKE '%value01%')

Query = SELECT * FROM `accounts` WHERE (`name` LIKE '%value01%' OR `name` LIKE '%value02%' OR `name` LIKE '%value03%' OR `code` LIKE '%value01%' OR `name` LIKE '%value02%' OR `name` LIKE '%value03%')


问:
Should you fork your own Project and submit pull request?
Hi I started a project on github with other people contributing, should I fork my own project and do updates via pull request. I've only been pushing changes to branches so far, and I am wondering if that is a bad practice.

What is the Git etiquette here?

答:
Of cause you can do that. But there is a more efficient way to that.

Since you have permission to push on your repo, so you can create a branch from which you are working and do your works on the new created branch. After finish working, push it to github and create a PR to merge this branch into your contribute branch.


问:
Why don't Info level messages get logged when minimum level is Debug?
I have the following code in my C# application using Nlog. The messages with 'Debug' get logged, but 'Info' do not. I had assumed that since minLevel is set to 'Debug' in app.config, the 'Info' messages will also get logged, since Debug has higher priority over 'Info'. But they do not get logged. Where am i wrong ?

Thanks.

```<code>if (logger.IsDebugEnabled) logger.Debug(logMessage) else if (logger.IsInfoEnabled)log.Info(logMessage);
</code>```

This is the app.config setting

```<code><nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<targets>
  <target name="file" xsi:type="File" fileName="E:/Logoutputs/Remissol-Nlog.txt" />
</targets>

<rules>
  <logger name="*" minlevel="Debug" writeTo="file" />
</rules>
</code>```

答:
Your problem lies with the nested if statements in your example. Both Debug and Info log levels are enabled according to your config file. The first if statement is then evaluated and its block executed because the condition is true. The else block is therefore never reached and your Info message is never logged.

I suggest that you split your nested if statements into 2 separate statements if you want to log the message for Debug and Info levels.

Body:
I have the following code in my C# application using Nlog. The messages with 'Debug' get logged, but 'Info' do not. I had assumed that since minLevel is set to 'Debug' in app.config, the 'Info' messages will also get logged, since Debug has higher priority over 'Info'. But they do not get logged. Where am i wrong ?

Thanks.

if (logger.IsDebugEnabled) logger.Debug(logMessage) else if (logger.IsInfoEnabled)log.Info(logMessage);

This is the app.config setting

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<targets>
  <target name="file" xsi:type="File" fileName="E:/Logoutputs/Remissol-Nlog.txt" />
</targets>

<rules>
  <logger name="*" minlevel="Debug" writeTo="file" />
</rules>