问:
Create Balanced Binary Search Tree from Sorted linked list
What's the best way to create a balanced binary search tree from a sorted singly linked list?</p>

答:
Trick question!

The best way is to use the STL, and advantage yourself of the fact that the sorted associative container ADT, of which set is an implementation, demands insertion of sorted ranges have amortized linear time.  Any passable set of core data structures for any language should offer a similar guarantee.  For a real answer, see the quite clever solutions others have provided.

What's that? I should offer something useful?

Hum...

How about this?

The smallest possible meaningful tree in a balanced binary tree is 3 nodes.
A parent, and two children.  The very first instance of such a tree is the first three elements.  Child-parent-Child.  Let's now imagine this as a single node.  Okay, well, we no longer have a tree. But we know that the shape we want is Child-parent-Child.

Done for a moment with our imaginings, we want to keep a pointer to the parent in that initial triumvirate.  But it's singly linked!

We'll want to have four pointers, which I'll call A, B, C, and D.  So, we move A to 1, set B equal to A and advance it one.  Set C equal to B, and advance it two.  The node under B already points to its right-child-to-be.  We build our initial tree.  We leave B at the parent of Tree one.  C is sitting at the node that will have our two minimal trees as children.  Set A equal to C, and advance it one. Set D equal to A, and advance it one.  We can now build our next minimal tree.  D points to the root of that tree, B points to the root of the other, and C points to the... the new root from which we will hang our two minimal trees.

How about some pictures?

```<code>[A][B][-][C]
</code>```

With our image of a minimal tree as a node...

```<code>[B = Tree][C][A][D][-]
</code>```

And then

```<code>[Tree A][C][Tree B]
</code>```

Except we have a problem. The node two after D is our next root.

```<code>[B = Tree A][C][A][D][-][Roooooot?!]
</code>```

It would be a lot easier on us if we could simply maintain a pointer to it instead of to it and C.  Turns out, since we know it will point to C, we can go ahead and start constructing the node in the binary tree that will hold it, and as part of this we can enter C into it as a left-node.  How can we do this elegantly?

Set the pointer of the Node under C to the node Under B.

It's cheating in every sense of the word, but by using this trick, we free up B.

Alternatively, you can be sane, and actually start building out the node structure.  After all, you really can't reuse the nodes from the SLL, they're probably POD structs.

So now...

```<code>[TreeA]<-[C][A][D][-][B]
[TreeA]<-[C]->[TreeB][B]
</code>```

And... Wait a sec.  We can use this same trick to free up C, if we just let ourselves think of it as a single node instead of a tree.  Because after all, it really is just a single node.

```<code>[TreeC]<-[B][A][D][-][C]
</code>```

We can further generalize our tricks.

```<code>[TreeC]<-[B][TreeD]<-[C][-]<-[D][-][A]
[TreeC]<-[B][TreeD]<-[C]->[TreeE][A]
[TreeC]<-[B]->[TreeF][A]
[TreeG]<-[A][B][C][-][D]
[TreeG]<-[A][-]<-[C][-][D]
[TreeG]<-[A][TreeH]<-[D][B][C][-]
[TreeG]<-[A][TreeH]<-[D][-]<-[C][-][B]
[TreeG]<-[A][TreeJ]<-[B][-]<-[C][-][D]
[TreeG]<-[A][TreeJ]<-[B][TreeK]<-[D][-]<-[C][-]
[TreeG]<-[A][TreeJ]<-[B][TreeK]<-[D][-]<-[C][-]
</code>```

We are missing a critical step!

```<code>[TreeG]<-[A]->([TreeJ]<-[B]->([TreeK]<-[D][-]<-[C][-]))
</code>```

Becomes :

```<code>[TreeG]<-[A]->[TreeL->([TreeK]<-[D][-]<-[C][-])][B]
[TreeG]<-[A]->[TreeL->([TreeK]<-[D]->[TreeM])][B]
[TreeG]<-[A]->[TreeL->[TreeN]][B]
[TreeG]<-[A]->[TreeO][B]
[TreeP]<-[B]
</code>```

Obviously, the algorithm can be cleaned up considerably, but I thought it would be interesting to demonstrate how one can optimize as you go by iteratively designing your algorithm.  I think this kind of process is what a good employer should be looking for more than anything.

The trick, basically, is that each time we reach the next midpoint, which we know is a parent-to-be, we know that its left subtree is already finished.  The other trick is that we are done with a node once it has two children and something pointing to it, even if all of the sub-trees aren't finished.  Using this, we can get what I am pretty sure is a linear time solution, as each element is touched only 4 times at most.  The problem is that this relies on being given a list that will form a truly balanced binary search tree.  There are, in other words, some hidden constraints that may make this solution either much harder to apply, or impossible.  For example, if you have an odd number of elements, or if there are a lot of non-unique values, this starts to produce a fairly silly tree.

Considerations:

Render the element unique.

Insert a dummy element at the end if the number of nodes is odd.

Sing longingly for a more naive implementation.

Use a deque to keep the roots of completed subtrees and the midpoints in, instead of mucking around with my second trick.

Body:
Trick question!

The best way is to use the STL, and advantage yourself of the fact that the sorted associative container ADT, of which set is an implementation, demands insertion of sorted ranges have amortized linear time.  Any passable set of core data structures for any language should offer a similar guarantee.  For a real answer, see the quite clever solutions others have provided.

What's that? I should offer something useful?

Hum...

How about this?

The smallest possible meaningful tree in a balanced binary tree is 3 nodes.
A parent, and two children.  The very first instance of such a tree is the first three elements.  Child-parent-Child.  Let's now imagine this as a single node.  Okay, well, we no longer have a tree. But we know that the shape we want is Child-parent-Child.

Done for a moment with our imaginings, we want to keep a pointer to the parent in that initial triumvirate.  But it's singly linked!

We'll want to have four pointers, which I'll call A, B, C, and D.  So, we move A to 1, set B equal to A and advance it one.  Set C equal to B, and advance it two.  The node under B already points to its right-child-to-be.  We build our initial tree.  We leave B at the parent of Tree one.  C is sitting at the node that will have our two minimal trees as children.  Set A equal to C, and advance it one. Set D equal to A, and advance it one.  We can now build our next minimal tree.  D points to the root of that tree, B points to the root of the other, and C points to the... the new root from which we will hang our two minimal trees.

How about some pictures?

[A][B][-][C]

With our image of a minimal tree as a node...

[B = Tree][C][A][D][-]

And then

[Tree A][C][Tree B]

Except we have a problem. The node two after D is our next root.

[B = Tree A][C][A][D][-][Roooooot?!]

It would be a lot easier on us if we could simply maintain a pointer to it instead of to it and C.  Turns out, since we know it will point to C, we can go ahead and start constructing the node in the binary tree that will hold it, and as part of this we can enter C into it as a left-node.  How can we do this elegantly?

Set the pointer of the Node under C to the node Under B.

It's cheating in every sense of the word, but by using this trick, we free up B.

Alternatively, you can be sane, and actually start building out the node structure.  After all, you really can't reuse the nodes from the SLL, they're probably POD structs.

So now...

[TreeA]<-[C][A][D][-][B]
[TreeA]<-[C]->[TreeB][B]

And... Wait a sec.  We can use this same trick to free up C, if we just let ourselves think of it as a single node instead of a tree.  Because after all, it really is just a single node.

[TreeC]<-[B][A][D][-][C]

We can further generalize our tricks.

[TreeC]<-[B][TreeD]<-[C][-]<-[D][-][A]
[TreeC]<-[B][TreeD]<-[C]->[TreeE][A]
[TreeC]<-[B]->[TreeF][A]
[TreeG]<-[A][B][C][-][D]
[TreeG]<-[A][-]<-[C][-][D]
[TreeG]<-[A][TreeH]<-[D][B][C][-]
[TreeG]<-[A][TreeH]<-[D][-]<-[C][-][B]
[TreeG]<-[A][TreeJ]<-[B][-]<-[C][-][D]
[TreeG]<-[A][TreeJ]<-[B][TreeK]<-[D][-]<-[C][-]
[TreeG]<-[A][TreeJ]<-[B][TreeK]<-[D][-]<-[C][-]

We are missing a critical step!

[TreeG]<-[A]->([TreeJ]<-[B]->([TreeK]<-[D][-]<-[C][-]))

Becomes :

[TreeG]<-[A]->[TreeL->([TreeK]<-[D][-]<-[C][-])][B]
[TreeG]<-[A]->[TreeL->([TreeK]<-[D]->[TreeM])][B]
[TreeG]<-[A]->[TreeL->[TreeN]][B]
[TreeG]<-[A]->[TreeO][B]
[TreeP]<-[B]

Obviously, the algorithm can be cleaned up considerably, but I thought it would be interesting to demonstrate how one can optimize as you go by iteratively designing your algorithm.  I think this kind of process is what a good employer should be looking for more than anything.

The trick, basically, is that each time we reach the next midpoint, which we know is a parent-to-be, we know that its left subtree is already finished.  The other trick is that we are done with a node once it has two children and something pointing to it, even if all of the sub-trees aren't finished.  Using this, we can get what I am pretty sure is a linear time solution, as each element is touched only 4 times at most.  The problem is that this relies on being given a list that will form a truly balanced binary search tree.  There are, in other words, some hidden constraints that may make this solution either much harder to apply, or impossible.  For example, if you have an odd number of elements, or if there are a lot of non-unique values, this starts to produce a fairly silly tree.

Considerations:

Render the element unique.

Insert a dummy element at the end if the number of nodes is odd.

Sing longingly for a more naive implementation.

Use a deque to keep the roots of completed subtrees and the midpoints in, instead of mucking around with my second trick.


来源: stackexchange

问:
How do I add a authorization rule to IIS that allows Paypal IPN to send notifications back to the listener?
When I have the authorization rule in IIS under-.net authorization rules-set to deny anonymous users both the IPN simulator and the IPN I have set in my sandbox fail. When I remove the rule it works fine. Is there a way I can create a rule that will allow incoming notifications from paypal to my IIS server?</p>

答:
Just to give every one an update- I have resolved this issue partially by creating two rules-in the web.config file- one that denies read access to the website for anonymous users- and another which allows them to post messages to the listener-

```<code> <authorization> <!--change authorization here-->
  <deny users="?" verbs="GET" />
  <allow users="?" verbs="POST" />
  </authorization>
</code>```

Ideally I would like to create a rule that only allows POSTs from a ip address domain reserved explicitly by Paypal. If anyone has any ideas on how to go about doing this- I would greatly appreciate some input.

ContentLicense: CC BY-SA 3.0

Body:
Just to give every one an update- I have resolved this issue partially by creating two rules-in the web.config file- one that denies read access to the website for anonymous users- and another which allows them to post messages to the listener-

 <authorization> <!--change authorization here-->
  <deny users="?" verbs="GET" />
  <allow users="?" verbs="POST" />
  </authorization>

Ideally I would like to create a rule that only allows POSTs from a ip address domain reserved explicitly by Paypal. If anyone has any ideas on how to go about doing this- I would greatly appreciate some input.


问:
MAX with Inner join VS rank() over
I am trying to fetch maximum balance for given account

```<code>ACCT_BALANCE table:
ACCOUNT_JOIN,BALANCE_UPDATE_DATE,ACCT_VALUE
1   11:49 AM 3/21/2017  1000
1   10:49 AM 5/29/2017  2121
2   11:49 AM 3/29/2017  3332
2   13:21 AM 3/33/2017  110
3   11:50 AM 4/4/2017   888
4   10:49 AM 3/29/2017  66
4   11:50 AM 3/3/2017   57000
4   10:49 AM 2/29/2017  2265
4   13:21 AM 3/2/2017   555
4   11:50 AM 8/9/2017   555
</code>```

for example, max balance for account join 1 is  2121 from 5/29/2017

Performance wise what will be better? using MAX with Inner join or rank() over?

```<code>CREATE OR REPLACE VIEW MAX_VAL_VIEW
AS
SELECT ACCT_VALUE,ACCOUNT_JOIN
  FROM (
        SELECT ACCT_VALUE,ACCOUNT_JOIN,
           rank() over (partition by ACCOUNT_JOIN order by BALANCE_UPDATE_DATE desc) rnk
        FROM ACCT_BALANCE
      )
 WHERE rnk = 1
/

CREATE OR REPLACE VIEW MAX_VAL_VIEW
AS
              SELECT A.ACCT_VALUE ,A.ACCOUNT_JOIN
              FROM ACCT_BALANCE A
                WHERE A.BALANCE_UPDATE_DATE = (
                    SELECT max(B.BALANCE_UPDATE_DATE)
                    FROM ACCT_BALANCE B
                    WHERE B.ACCOUNT_JOIN = A.ACCOUNT_JOIN
        )
/
</code>```

答:
You could also use the last function:

```<code>select max(acct_value) keep (dense_rank last order by balance_update_date) as acct_value,
  account_join
from acct_balance
group by account_join;

ACCT_VALUE ACCOUNT_JOIN
---------- ------------
      2121            1
       110            2
       888            3
       555            4
</code>```

(using modified date/times to make them all valid).

Either that or the rank() approach should beat the max(B.BALANCE_UPDATE_DATE) approach, as they only hit the table once. You can look at the execution plans for all three queries to see how the optimiser treats them - which indexes (if any) they use, how many full table scans, etc.

Title: MAX with Inner join VS rank() over

Body:
I am trying to fetch maximum balance for given account

ACCT_BALANCE table:
ACCOUNT_JOIN,BALANCE_UPDATE_DATE,ACCT_VALUE
1   11:49 AM 3/21/2017  1000
1   10:49 AM 5/29/2017  2121
2   11:49 AM 3/29/2017  3332
2   13:21 AM 3/33/2017  110
3   11:50 AM 4/4/2017   888
4   10:49 AM 3/29/2017  66
4   11:50 AM 3/3/2017   57000
4   10:49 AM 2/29/2017  2265
4   13:21 AM 3/2/2017   555
4   11:50 AM 8/9/2017   555

for example, max balance for account join 1 is  2121 from 5/29/2017

Performance wise what will be better? using MAX with Inner join or rank() over?

CREATE OR REPLACE VIEW MAX_VAL_VIEW
AS
SELECT ACCT_VALUE,ACCOUNT_JOIN
  FROM (
        SELECT ACCT_VALUE,ACCOUNT_JOIN,
           rank() over (partition by ACCOUNT_JOIN order by BALANCE_UPDATE_DATE desc) rnk
        FROM ACCT_BALANCE
      )
 WHERE rnk = 1
/

CREATE OR REPLACE VIEW MAX_VAL_VIEW
AS
              SELECT A.ACCT_VALUE ,A.ACCOUNT_JOIN
              FROM ACCT_BALANCE A
                WHERE A.BALANCE_UPDATE_DATE = (
                    SELECT max(B.BALANCE_UPDATE_DATE)
                    FROM ACCT_BALANCE B
                    WHERE B.ACCOUNT_JOIN = A.ACCOUNT_JOIN
        )
/

Body:
You could also use the last function:

select max(acct_value) keep (dense_rank last order by balance_update_date) as acct_value,
  account_join
from acct_balance
group by account_join;

ACCT_VALUE ACCOUNT_JOIN
---------- ------------
      2121            1
       110            2
       888            3
       555            4

(using modified date/times to make them all valid).

Either that or the rank() approach should beat the max(B.BALANCE_UPDATE_DATE) approach, as they only hit the table once. You can look at the execution plans for all three queries to see how the optimiser treats them - which indexes (if any) they use, how many full table scans, etc.


问:
To show only file name without the entire directory path
ls /home/user/new/*.txt prints all txt files in that directory. However it prints the output as follows:

```<code>[me@comp]$ ls /home/user/new/*.txt
/home/user/new/file1.txt    /home/user/new/file2.txt    /home/user/new/file3.txt
</code>```

and so on.

I want to run the ls command not from the /home/user/new/ directory thus I have to give the full directory name, yet I want the output to be only as

```<code>[me@comp]$ ls /home/user/new/*.txt
file1.txt    file2.txt    file3.txt
</code>```

I don't want the entire path. Only filename is needed. This issues has to be solved using ls command, as its output is meant for another program.

答:
just hoping to be helpful to someone as old problems seem to come back every now and again and I always find good tips here.

My problem was to list in a text file all the names of the "*.txt" files in a certain directory without path and without extension from a Datastage 7.5 sequence.

The solution we used is:

```<code>ls /home/user/new/*.txt | xargs -n 1 basename | cut -d '.' -f1 > name_list.txt
</code>```

Body:
ls /home/user/new/*.txt prints all txt files in that directory. However it prints the output as follows:

[me@comp]$ ls /home/user/new/*.txt
/home/user/new/file1.txt    /home/user/new/file2.txt    /home/user/new/file3.txt

and so on.

I want to run the ls command not from the /home/user/new/ directory thus I have to give the full directory name, yet I want the output to be only as

[me@comp]$ ls /home/user/new/*.txt
file1.txt    file2.txt    file3.txt

I don't want the entire path. Only filename is needed. This issues has to be solved using ls command, as its output is meant for another program.

Body:
just hoping to be helpful to someone as old problems seem to come back every now and again and I always find good tips here.

My problem was to list in a text file all the names of the "*.txt" files in a certain directory without path and without extension from a Datastage 7.5 sequence.

The solution we used is:

ls /home/user/new/*.txt | xargs -n 1 basename | cut -d '.' -f1 > name_list.txt


问:
Java Sockets. Server-Client communication
I am trying to connect a client with gui with a server withoout gui. Connection is being done, but i cant see any messages between these two apps.
(i should get SERVER HERE in client, and CLIENT HERE in server)

Client Connection Code:

```<code>@Override
public void ClientRunning(){
    try {
       connectToServer();
        setStreams();
        ClientRun();

    }catch(EOFException oefException){
        showMessage("\n Client terminated the connection\n");
    }catch(IOException ioException){
        ioException.printStackTrace();
    }finally{
        close();
    }
}

public void connectToServer() throws IOException{
    showMessage("Attempting Connection... \n");
    connection = new Socket(InetAddress.getByName(serverIP),6789);
    showMessage("Connected to: "+ connection.getInetAddress().getHostName());
}

public void setStreams() throws IOException{
   output = new PrintWriter(connection.getOutputStream(),true);
   output.flush();
   input= new BufferedReader(new InputStreamReader(connection.getInputStream()));

    showMessage("\n Streams are now set. \n");
}

public void close(){
    showMessage("\n closing...");
    try{
      output.close();
      input.close();
      connection.close();

    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}
public void showMessage(final String text){
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            cwindow.append(text);
        }
    });
}

public void sendMessage(String message){
    output.write("CLIENT - "+message);
    output.flush();
    showMessage("\nCLIENT - "+message);
}

private void ClientRun() throws IOException{
    String message="CLIENT HERE!";
    sendMessage(message);
    do{
        try{
            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");
    }
</code>```

(input and output are defined in GUI class in which this Client class is extended to. Defined as "protected BufferedReader input;
protected PrintWriter output;")

Also, servers code:

```<code>public class ServerClass {

private ServerSocket server;
private Socket connection;
private BufferedReader input;
private BufferedWriter output;

public void startServer(){
    try{
        server=new ServerSocket(6789,100);
        while(true){
            try{
                waitForConnection();
                setStreams();
                ServerRunning();
            }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");

            }finally{
            close();

        }
        }

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

private void waitForConnection() throws IOException{
    showMessage("Waiting for someone to connect... \n");
    connection=server.accept();
    showMessage("Now connected to "+ connection.getInetAddress().getHostName());
}

private void setStreams() throws IOException{
   output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
   output.flush();
   input= new BufferedReader(new InputStreamReader(connection.getInputStream()));

    showMessage("\n Streams are now set. \n");
}
public void ServerRunning() throws IOException{
    String message="SERVER HERE!";
    sendMessage(message);
    do{
        try{

            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");

  }
private void close(){
    showMessage("\n Closing connections... \n");
    try{
        output.close();
        input.close();
        connection.close();

}catch(IOException ioException){
    ioException.printStackTrace();
}
}
private void showMessage(String text){
    System.out.println(text);
}

private void sendMessage(String message){
    try{
       output.write("SERVER - "+message);
        output.flush();
        showMessage(message);
    }catch(IOException ioException){
        System.out.println("\n ERROR!");
    }
}
</code>```

Connection seems to be ok, so i don't get whats wrong. Any help would be appreciated.

PS: i also tried PrintWriter in server as well and also tried a try catch in stream statement, the problem remains.

答:
After compairing this code with some I have written in the past using sockets , I noticed you are using output.write(string) and input.readline() - These do not mix well, readline() expects a newline and write does not give one.

Replace write() with println().

Body:
I am trying to connect a client with gui with a server withoout gui. Connection is being done, but i cant see any messages between these two apps.
(i should get SERVER HERE in client, and CLIENT HERE in server)

Client Connection Code:

@Override
public void ClientRunning(){
    try {
       connectToServer();
        setStreams();
        ClientRun();

    }catch(EOFException oefException){
        showMessage("\n Client terminated the connection\n");
    }catch(IOException ioException){
        ioException.printStackTrace();
    }finally{
        close();
    }
}

public void connectToServer() throws IOException{
    showMessage("Attempting Connection... \n");
    connection = new Socket(InetAddress.getByName(serverIP),6789);
    showMessage("Connected to: "+ connection.getInetAddress().getHostName());
}

public void setStreams() throws IOException{
   output = new PrintWriter(connection.getOutputStream(),true);
   output.flush();
   input= new BufferedReader(new InputStreamReader(connection.getInputStream()));

    showMessage("\n Streams are now set. \n");
}

public void close(){
    showMessage("\n closing...");
    try{
      output.close();
      input.close();
      connection.close();

    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}
public void showMessage(final String text){
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            cwindow.append(text);
        }
    });
}

public void sendMessage(String message){
    output.write("CLIENT - "+message);
    output.flush();
    showMessage("\nCLIENT - "+message);
}

private void ClientRun() throws IOException{
    String message="CLIENT HERE!";
    sendMessage(message);
    do{
        try{
            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");
    }

(input and output are defined in GUI class in which this Client class is extended to. Defined as "protected BufferedReader input;
protected PrintWriter output;")

Also, servers code:

public class ServerClass {

private ServerSocket server;
private Socket connection;
private BufferedReader input;
private BufferedWriter output;

public void startServer(){
    try{
        server=new ServerSocket(6789,100);
        while(true){
            try{
                waitForConnection();
                setStreams();
                ServerRunning();
            }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");

            }finally{
            close();

        }
        }

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

private void waitForConnection() throws IOException{
    showMessage("Waiting for someone to connect... \n");
    connection=server.accept();
    showMessage("Now connected to "+ connection.getInetAddress().getHostName());
}

private void setStreams() throws IOException{
   output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
   output.flush();
   input= new BufferedReader(new InputStreamReader(connection.getInputStream()));

    showMessage("\n Streams are now set. \n");
}
public void ServerRunning() throws IOException{
    String message="SERVER HERE!";
    sendMessage(message);
    do{
        try{

            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");

  }
private void close(){
    showMessage("\n Closing connections... \n");
    try{
        output.close();
        input.close();
        connection.close();

}catch(IOException ioException){
    ioException.printStackTrace();
}
}
private void showMessage(String text){
    System.out.println(text);
}

private void sendMessage(String message){
    try{
       output.write("SERVER - "+message);
        output.flush();
        showMessage(message);
    }catch(IOException ioException){
        System.out.println("\n ERROR!");
    }
}

Connection seems to be ok, so i don't get whats wrong. Any help would be appreciated.

PS: i also tried PrintWriter in server as well and also tried a try catch in stream statement, the problem remains.


问:
Errors creating a string in c++
Whenever I try to create a string in my header file I get the error: 'string' is not a member of 'std'. I am using the Microsoft Visual c++ express 2010 compiler. Here is my header file:

```<code>using namespace std;

class Person
{
private:
 string name;
 string p_number;

public:
 Person();
 Person(string, string);
 string get_number();
 string get_name();
};
</code>```

I am a decent java programmer who just started  learning c++

答:
Put

```<code>#include <string>
</code>```

at the top of the file.

ContentLicense: CC BY-SA 2.5

Title: Errors creating a string in c++

Body:
Whenever I try to create a string in my header file I get the error: 'string' is not a member of 'std'. I am using the Microsoft Visual c++ express 2010 compiler. Here is my header file:

using namespace std;

class Person
{
private:
 string name;
 string p_number;

public:
 Person();
 Person(string, string);
 string get_number();
 string get_name();
};

I am a decent java programmer who just started  learning c++

Body:
Put

#include <string>

at the top of the file.


问:
How to set selected ngfor ionic2
I want to set selected but I tried this below it's not work
How to set selected ngfor ionic2
I tried

```<code><ion-item>
      <ion-label>Source</ion-label>
      <ion-select [(ngModel)]="filter" >
        <ion-option value={{item.val}} *ngFor="let item of options" selected="item.val == 'pencil'">{{item.name}}</ion-option>
      </ion-select>
    </ion-item>
</code>```

it's not work ,not show selected this to default

ts

```<code>public options =  [
        {
            "name": "Pencils",
            "val" : "pencil"
          }
             .
             .
             .

        ];
</code>```

答:
[selected] instead of selected and [value] instead of value :

```<code>  <ion-option [value]="item.val" *ngFor="let item of options" [selected]="item.val == 'pencil'">{{item.name}}</ion-option>
      </ion-select>
</code>```

note :

use property when bind to static value ex: value="someValue"

use [property] when bind to a variable or expression ex: [value]="getSomeValue()".

Title: How to set selected ngfor ionic2

Body:
I want to set selected but I tried this below it's not work
How to set selected ngfor ionic2
I tried

<ion-item>
      <ion-label>Source</ion-label>
      <ion-select [(ngModel)]="filter" >
        <ion-option value={{item.val}} *ngFor="let item of options" selected="item.val == 'pencil'">{{item.name}}</ion-option>
      </ion-select>
    </ion-item>

it's not work ,not show selected this to default

ts

public options =  [
        {
            "name": "Pencils",
            "val" : "pencil"
          }
             .
             .
             .

        ];

Body:
[selected] instead of selected and [value] instead of value :

  <ion-option [value]="item.val" *ngFor="let item of options" [selected]="item.val == 'pencil'">{{item.name}}</ion-option>
      </ion-select>

note :

use property when bind to static value ex: value="someValue"

use [property] when bind to a variable or expression ex: [value]="getSomeValue()".


问:
How to access an array of dictionaries?
I want to use an array of dictionaries to store all the content of an Excel workbook to later process it and make operations in memory.

I have defined that the first row of the Excel workbook is the key and the rest of rows are content. As I have one key for many values, I need to store them in a different container (this would be the array).

A sample of the content

```
Code Name Surname
1    a     b
2    c     d
```

The code:

```<code>For Each rcell In ws.UsedRange.Cells
   If rcell.Row > 1 Then
        ReDim Preserve aRows(rcell.Row - 2)
        'Set aRows(rcell.Row - 2) = CreateObject("scripting.dictionary")
        Set pInfo = New Scripting.Dictionary
        pInfo.Add Key:=Cells(1, rcell.Column).Value, Item:=rcell.Value
        'aRows(rcell.Row - 2).Add Key:=Cells(1, rcell.Column).Value, Item:=rcell.Value
        Set aRows(rcell.Row - 2) = pInfo
    End If
Next rcell
</code>```

This code creates an array of dictionaries.

When I try to access the data I get an error.

I know that at least it is storing values because when I use:

```<code>debug.print(ubound(aRows))
</code>```

I am getting the value (1) in this case.

I tried accessing the content with

```<code>for each row in aRows
    debug.print(row.key)
next row
</code>```

However, this is not accepted. How do I access the data?

An alternative or something more simple would be great.

答:
May be this?</p>

```<code>Dim d, k
For Each d in aRows
    For Each k in d.keys
        Debug.Print k, d(k),
    Next
    Debug.Print vbCrLf
Next
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to access an array of dictionaries?

Body:
I want to use an array of dictionaries to store all the content of an Excel workbook to later process it and make operations in memory.

I have defined that the first row of the Excel workbook is the key and the rest of rows are content. As I have one key for many values, I need to store them in a different container (this would be the array).

A sample of the content

Code Name Surname
1    a     b
2    c     d

The code:

For Each rcell In ws.UsedRange.Cells
   If rcell.Row > 1 Then
        ReDim Preserve aRows(rcell.Row - 2)
        'Set aRows(rcell.Row - 2) = CreateObject("scripting.dictionary")
        Set pInfo = New Scripting.Dictionary
        pInfo.Add Key:=Cells(1, rcell.Column).Value, Item:=rcell.Value
        'aRows(rcell.Row - 2).Add Key:=Cells(1, rcell.Column).Value, Item:=rcell.Value
        Set aRows(rcell.Row - 2) = pInfo
    End If
Next rcell

This code creates an array of dictionaries.

When I try to access the data I get an error.

I know that at least it is storing values because when I use:

debug.print(ubound(aRows))

I am getting the value (1) in this case.

I tried accessing the content with

for each row in aRows
    debug.print(row.key)
next row

However, this is not accepted. How do I access the data?

An alternative or something more simple would be great.

Body:
May be this?

Dim d, k
For Each d in aRows
    For Each k in d.keys
        Debug.Print k, d(k),
    Next
    Debug.Print vbCrLf
Next


问:
Rotate and Resize image
I use JSF 2 , primefaces 5.3 and i try to use rotate and resize images like Jpg, png or any other image format. But this error occurs.
 Unable to attach behavior to non-ClientBehaviorHolder parent jsf - file preview

here is my code.

```<code>                    <pe:imageAreaSelect id="areaSelect"
                                        for="myImage"
                                        widgetVar="areaSelectWidget"
                                        autoHide="true"
                                        handles="false"
                                        movable="false"
                                        persistent="false"
                                        resizable="false"
                                        parentSelector="#imageWrapper">
                        <p:ajax event="selectEnd" listener="#{fileViewer.selectEndListener}" update="growl"/>
                    </pe:imageAreaSelect>

                    <pe:imageRotateAndResize id="rotateAndResize" for="myImage" widgetVar="rotateAndResizeWidget">
                        <p:ajax event="rotate" listener="#{fileViewer.rotateListener}"
                                update="growl" oncomplete="PF('areaSelectWidget').reload();"/>
                        <pe:javascript event="resize" execute="PF('areaSelectWidget').reload();"/>
                    </pe:imageRotateAndResize>

                    <p:commandButton type="button" icon="ui-icon-arrowreturnthick-1-w"
                                     value="Rotate" onclick="PF('rotateAndResizeWidget').rotateLeft(90);
                                             return false;"/>
                    <p:commandButton type="button" icon="ui-icon-arrowreturnthick-1-e"
                                     value="Rotate" onclick="PF('rotateAndResizeWidget').rotateRight(90);
                                             return false;"/>
                    <p:commandButton type="button" icon="ui-icon-zoomin"
                                     value="+"  onclick="PF('rotateAndResizeWidget').scale(1.05);
                                             return false;"/>
                    <p:commandButton type="button" icon="ui-icon-zoomout"
                                     value="-" onclick="PF('rotateAndResizeWidget').scale(0.95);
                                             return false;"/>
                </p:panelGrid>
</code>```

public void rotateListener(final RotateEvent e) {
        final FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Image rotated",  + e.getDegree() + " Degree:");

```<code>    FacesContext.getCurrentInstance().addMessage(null, msg);
}

public void resizeListener(final ResizeEvent e) {
    final FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Image resized", "Width:" + e.getWidth() + ", Height: " + e.getHeight());

    FacesContext.getCurrentInstance().addMessage(null, msg);
}

public void selectEndListener(final ImageAreaSelectEvent e) {
    final FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Area selected",
            "X1: " + e.getX1()
            + ", X2: " + e.getX2()
            + ", Y1: " + e.getY1()
            + ", Y2: " + e.getY2()
            + ", Image width: " + e.getImgWidth()
            + ", Image height: " + e.getImgHeight());

    FacesContext.getCurrentInstance().addMessage(null, msg);
}
</code>```

How can I solve it?

答:
Could it be that you didn't include PrimeFaces Extensions? AFAIR you need 4.0.0 which should be compatible with PF 5.3.

Otherwise i don't the exception comes from this snippet.

Title: Rotate and Resize image

Body:
I use JSF 2 , primefaces 5.3 and i try to use rotate and resize images like Jpg, png or any other image format. But this error occurs.
 Unable to attach behavior to non-ClientBehaviorHolder parent jsf - file preview

here is my code.

                    <pe:imageAreaSelect id="areaSelect"
                                        for="myImage"
                                        widgetVar="areaSelectWidget"
                                        autoHide="true"
                                        handles="false"
                                        movable="false"
                                        persistent="false"
                                        resizable="false"
                                        parentSelector="#imageWrapper">

                    </pe:imageAreaSelect>

                    <pe:imageRotateAndResize id="rotateAndResize" for="myImage" widgetVar="rotateAndResizeWidget">

                        <pe:javascript event="resize" execute="PF('areaSelectWidget').reload();"/>
                    </pe:imageRotateAndResize>

public void rotateListener(final RotateEvent e) {
        final FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Image rotated",  + e.getDegree() + " Degree:");

    FacesContext.getCurrentInstance().addMessage(null, msg);
}

public void resizeListener(final ResizeEvent e) {
    final FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Image resized", "Width:" + e.getWidth() + ", Height: " + e.getHeight());

    FacesContext.getCurrentInstance().addMessage(null, msg);
}

public void selectEndListener(final ImageAreaSelectEvent e) {
    final FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Area selected",
            "X1: " + e.getX1()
            + ", X2: " + e.getX2()
            + ", Y1: " + e.getY1()
            + ", Y2: " + e.getY2()
            + ", Image width: " + e.getImgWidth()
            + ", Image height: " + e.getImgHeight());

    FacesContext.getCurrentInstance().addMessage(null, msg);
}

How can I solve it?


答:
Since you have ngModel, you should set the filter to the selected item initially:

```<code>public filter = this.options[0].val;
</code>```

Title: How to set selected ngfor ionic2

Body:
Since you have ngModel, you should set the filter to the selected item initially:

public filter = this.options[0].val;


问:
Brighten black pixels in a BufferedImage
I'm using RescaleOp to brighten my image, my problem is, if I use black(0,0,0) and white(255,255,255) they come back exactly the same.

I can guess why, 0(black RGB values) x 1.3 (brightness factor) = 0, and the white pixels can't go higher than 255 so they remain the same, and I'm satisfied with the white pixels remaining the same.

On the other end, if I darken the image, I get desired results because the white pixels get darker, 255(white RGB values) * .8 (brightness factor) =/= 255, and the black pixels can't go lower than 0 so they remain the same.

How do I make the black pixels get lighter in the same way the white pixels get darker with a BufferedImageOp?

Here is the rescale operation

```<code>        float scale = 1.3f;//This is the aformentioned "Brightness Factor"
        RescaleOp op = new RescaleOp(new float[] {scale,scale,scale, 1}, new float[4], null);
        BufferedImage brightImage = op.filter(...);
</code>```

Thanks for the current answers, but I don't see how to apply them to my problem.

答:
Options:

Write a custom RasterOp that extends RescaleOp to provide the behavior you want (in particular, if value = 0 && scale factor > 1, new value = 1 * scale factor = scale factor)

Use two RasterOps in serial.  The first will have a scale factor of 1 and an offset of 1 (making everything slightly brighter).  The second will be the existing RasterOp you've already defined.  It's messier and probably slower than the first, but could be simpler to implement.

Body:
I'm using RescaleOp to brighten my image, my problem is, if I use black(0,0,0) and white(255,255,255) they come back exactly the same.

I can guess why, 0(black RGB values) x 1.3 (brightness factor) = 0, and the white pixels can't go higher than 255 so they remain the same, and I'm satisfied with the white pixels remaining the same.

On the other end, if I darken the image, I get desired results because the white pixels get darker, 255(white RGB values) * .8 (brightness factor) =/= 255, and the black pixels can't go lower than 0 so they remain the same.

How do I make the black pixels get lighter in the same way the white pixels get darker with a BufferedImageOp?

Here is the rescale operation

        float scale = 1.3f;//This is the aformentioned "Brightness Factor"
        RescaleOp op = new RescaleOp(new float[] {scale,scale,scale, 1}, new float[4], null);
        BufferedImage brightImage = op.filter(...);

Thanks for the current answers, but I don't see how to apply them to my problem.


问:
Is it possible to get a core dump of a running process and its symbol table?
Is it possible to get gdb or use some other tools to create a core dump of a running process and it's symbol table?  It would be great if there's a way to do this without terminating the process.

If this is possible, what commands would you use?  (I'm trying to do this on a Linux box)

答: You can used generate-core-file command in gdb to generate core dump of running process.

OwnerDisplayName: Tim


问:
Get name from only date and ID matched with people list
I have rawdata with only ID's and dates of transactions. Then I have a list of people; their ID, their hire date and their name.

What I want is a column in the rawdata that gives me the persons name. The problem is, that the ID is re-used if the person quits, and another one starts.

Since I have the transaction date, I figure it should be possible to check:

IF the transaction matches the period they were hired, then get the right name.

Is this possible, and then how?

```<code>Rawdata:
Column A = Transaction date
Column B = ID
Column C = Here I want their name

People list:
Column A = ID
Column B = Name
Column C = Hire date
</code>```

Example (Excel Online - can be edited):
https://1drv.ms/x/s!AjWVkb2UBexjhzAKMy-YiE5EoKwc

Screenshot:

答:
Make sure your reference table is ordered in chronological order oldest to newest:

```<code>=INDEX(F:F,AGGREGATE(14,6,ROW($G$8:INDEX(G:G,MATCH(1E+99,E:E)))/(($E$8:INDEX(E:E,MATCH(1E+99,E:E))=B8)*($G$8:INDEX(G:G,MATCH(1E+99,E:E))<A8)),1))
</code>```

Body:
I have rawdata with only ID's and dates of transactions. Then I have a list of people; their ID, their hire date and their name.

What I want is a column in the rawdata that gives me the persons name. The problem is, that the ID is re-used if the person quits, and another one starts.

Since I have the transaction date, I figure it should be possible to check:

IF the transaction matches the period they were hired, then get the right name.

Is this possible, and then how?

Rawdata:
Column A = Transaction date
Column B = ID
Column C = Here I want their name

People list:
Column A = ID
Column B = Name
Column C = Hire date

Example (Excel Online - can be edited):
https://1drv.ms/x/s!AjWVkb2UBexjhzAKMy-YiE5EoKwc

Screenshot:

Body:
Make sure your reference table is ordered in chronological order oldest to newest:

=INDEX(F:F,AGGREGATE(14,6,ROW($G$8:INDEX(G:G,MATCH(1E+99,E:E)))/(($E$8:INDEX(E:E,MATCH(1E+99,E:E))=B8)*($G$8:INDEX(G:G,MATCH(1E+99,E:E))<A8)),1))


问:
How can I make certain parts of my html not selectable?
How can I make certain parts of my html not selectable?

I have some absolutely positioned divs that keep getting selected if a user tries to select the content of my page.

Is there a way to make it so certain elements (such as those divs) aren't selectable?

EDIT: The main issue is when someone copies these absolute div's and then pastes them into the rich text editor on my site, the rich text editor breaks on IE.

答:
If you want to just hide selection rectangle, you can use

```<code>element::selection { background: transparent }
</code>```

and it's counterpart for Gecko

```<code>element::-moz-selection { background: transparent }
</code>```

If you want to help your users select right text to copy to clipboard, you can move the element away. Usually browsers retain order of elements as they are defined in HTML when selecting. While it is not perfect solution, you can place the element's code in HTML either at the very beginning or very end of  tag. This way, if user selects something in the middle of the page, the element will be too "far away" to interfere.

Body:
If you want to just hide selection rectangle, you can use

element::selection { background: transparent }

and it's counterpart for Gecko

element::-moz-selection { background: transparent }

If you want to help your users select right text to copy to clipboard, you can move the element away. Usually browsers retain order of elements as they are defined in HTML when selecting. While it is not perfect solution, you can place the element's code in HTML either at the very beginning or very end of <body> tag. This way, if user selects something in the middle of the page, the element will be too "far away" to interfere.


问:
RegEx to get section of URL after string in Javascript
I have the following URL:

```<code>http://data.test.com/api/v1/entity/1231
</code>```

And I need to get the text that is after v1/ and before / (between the slashes), in this case the word entity. I'm using the following regex, but what I get back is entity/1231 on group 1:

```<code>/^[^\#\?]+\/v1\/([^\?]+).*$/
</code>```

Any idea on how to get rid of 1231 or anything that comes after entity?

Body:
I have the following URL:

http://data.test.com/api/v1/entity/1231

And I need to get the text that is after v1/ and before / (between the slashes), in this case the word entity. I'm using the following regex, but what I get back is entity/1231 on group 1:

/^[^\#\?]+\/v1\/([^\?]+).*$/

Any idea on how to get rid of 1231 or anything that comes after entity?

Body:
try this:

^[^\#\?]+\/v1\/([^\?]+).*(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/1231)$


问:
How to include specific folder in the Maven generated jar?
I have the following Maven project structure:

```<code>${basedir}/
  - pom.xml
  - lib/
    - dependency1.jar
    - dependency2.jar
    - ...
  - src/
    - main/..
    - test/..
  - target/
    - classes/..
    - blah/
    - uggh/
</code>```

How can I modify the pom file in order to include the entire lib folder (with its content) in the generated output jar?

This folder includes third parties jars that can not be part of the Maven repository.

答:
Use maven-jar-plugin to copy the dependencies from lib into your fat jar

```<code>            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>

                  <archive>
                    <manifest>
                    <addClasspath>true</addClasspath>
                    <mainClass>your.main.class</mainClass>
                    <classpathPrefix>lib/</classpathPrefix>
                    </manifest>
                  </archive>
                </configuration>
            </plugin>
</code>```

Body:
I have the following Maven project structure:

${basedir}/
  - pom.xml
  - lib/
    - dependency1.jar
    - dependency2.jar
    - ...
  - src/
    - main/..
    - test/..
  - target/
    - classes/..
    - blah/
    - uggh/

How can I modify the pom file in order to include the entire lib folder (with its content) in the generated output jar?

This folder includes third parties jars that can not be part of the Maven repository.

Body:
Use maven-jar-plugin to copy the dependencies from lib into your fat jar

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>

                  <archive>
                    <manifest>
                    <addClasspath>true</addClasspath>
                    <mainClass>your.main.class</mainClass>
                    <classpathPrefix>lib/</classpathPrefix>
                    </manifest>
                  </archive>
                </configuration>
            </plugin>


问:
Building msbuild 15 project programmatically

I'm trying to build a simple C# 7 class library project created with VS2017.

MSBuild from framework assemblies is outdated, so I'm referencing Microsoft.Build, Microsoft.Build.Engine and Microsoft.Build.Framework from MSBuild folder within visual studio (C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin).

Still, when I do this:

using (var collection = new ProjectCollection())
{
    var proj = collection.LoadProject(@"c:\projects\Sample\Sample.csproj"); // <-- exception
    proj.Build(new[] {new ConsoleLogger()});
}
```

I'm getting InvalidProjectFileException: The tools version "15.0" is unrecognized. Available tools versions are "4.0", "2.0".

Is there programmatic way to invoke build using the latest build tools and C# 7 compiler?

答:
I had exactly the same issues in my project.

In my case I want to build an SSDT project programmatically but I tried other project types as well.

Interestingly, it worked perfectly fine in build 26228.04 of VS2017 (which was the Release build) and stopped working in build 26228.09.

Yesterday build 26228.10 was released, so I decided to give it another go.

Surprisingly the following worked for me:

Update to the latest VS2017 build 26228.10 using the Visual Studio Installer.

I was never able to get collection.LoadProject(...) to work without getting some weird error but you can use this code to do the build:

```<code>BuildResult result = null;

using (var pc = new ProjectCollection())
    result = BuildManager.DefaultBuildManager.Build(
        new BuildParameters(pc) { Loggers = new[] { new ConsoleLogger() } },
        // Change this path to your .sln file instead of the .csproj.
        // (It won't work with the .csproj.)
        new BuildRequestData(@"c:\projects\Sample.sln",
            // Change the parameters as you need them,
            // e.g. if you want to just Build the Debug (not Rebuild the Release).
            new Dictionary<string, string>
            {
                { "Configuration", "Release" },
                { "Platform", "Any CPU" }
            }, null, new[] { "Rebuild" }, null));

if (result.OverallResult == BuildResultCode.Failure)
    // Something bad happened...
</code>```

Ensure that you have copied all the MSBuild assembly binding redirections to your .config file.

If you haven't already done this, open the file C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MSBuild.exe.config and copy the whole <runtime> element to the <configuration> element of your own .config file in the project that uses MSBuild programmatically.

If you don't redirect the MSBuild assembly versions, you will get some pretty strange error messages from MSBuild which will vary based on your MSBuild version.

But it's sure to say: It will definitely not work without the assembly binding redirections.

One additional step if you want to build an SSDT project:

Change the following two lines in your .sqlproj file from

```<code><VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">11.0</VisualStudioVersion>
<VisualStudioVersion Condition="'$(SSDTExists)' == ''">11.0</VisualStudioVersion>
</code>```

to

```<code><VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
<VisualStudioVersion Condition="'$(SSDTExists)' == ''">15.0</VisualStudioVersion>
</code>```

I'm not 100% sure why, but these steps worked perfectly for me!

But because MSBuild is a bit "difficult" to use programmatically (in my opinion it's sometimes as stable as a weather forecast), chances are that my approach won't work in your case.

Body:
I'm trying to build a simple C# 7 class library project created with VS2017.

MSBuild from framework assemblies is outdated, so I'm referencing Microsoft.Build, Microsoft.Build.Engine and Microsoft.Build.Framework from MSBuild folder within visual studio (C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin).

Still, when I do this:

using (var collection = new ProjectCollection())
{
    var proj = collection.LoadProject(@"c:\projects\Sample\Sample.csproj"); // <-- exception
    proj.Build(new[] {new ConsoleLogger()});
}

I'm getting InvalidProjectFileException: The tools version "15.0" is unrecognized. Available tools versions are "4.0", "2.0".

Is there programmatic way to invoke build using the latest build tools and C# 7 compiler?

Body:
I had exactly the same issues in my project.

In my case I want to build an SSDT project programmatically but I tried other project types as well.

Interestingly, it worked perfectly fine in build 26228.04 of VS2017 (which was the Release build) and stopped working in build 26228.09.

Yesterday build 26228.10 was released, so I decided to give it another go.

Surprisingly the following worked for me:

Update to the latest VS2017 build 26228.10 using the Visual Studio Installer.

I was never able to get collection.LoadProject(...) to work without getting some weird error but you can use this code to do the build:

BuildResult result = null;

using (var pc = new ProjectCollection())
    result = BuildManager.DefaultBuildManager.Build(
        new BuildParameters(pc) { Loggers = new[] { new ConsoleLogger() } },
        // Change this path to your .sln file instead of the .csproj.
        // (It won't work with the .csproj.)
        new BuildRequestData(@"c:\projects\Sample.sln",
            // Change the parameters as you need them,
            // e.g. if you want to just Build the Debug (not Rebuild the Release).
            new Dictionary<string, string>
            {
                { "Configuration", "Release" },
                { "Platform", "Any CPU" }
            }, null, new[] { "Rebuild" }, null));

if (result.OverallResult == BuildResultCode.Failure)
    // Something bad happened...

Ensure that you have copied all the MSBuild assembly binding redirections to your .config file.

If you haven't already done this, open the file C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MSBuild.exe.config and copy the whole <runtime> element to the <configuration> element of your own .config file in the project that uses MSBuild programmatically.

If you don't redirect the MSBuild assembly versions, you will get some pretty strange error messages from MSBuild which will vary based on your MSBuild version.

But it's sure to say: It will definitely not work without the assembly binding redirections.

One additional step if you want to build an SSDT project:

Change the following two lines in your .sqlproj file from

<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">11.0</VisualStudioVersion>
<VisualStudioVersion Condition="'$(SSDTExists)' == ''">11.0</VisualStudioVersion>

to

<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
<VisualStudioVersion Condition="'$(SSDTExists)' == ''">15.0</VisualStudioVersion>

I'm not 100% sure why, but these steps worked perfectly for me!

But because MSBuild is a bit "difficult" to use programmatically (in my opinion it's sometimes as stable as a weather forecast), chances are that my approach won't work in your case.


问:
Why do we need an 'arbiter' in MongoDB replication?
Assume we setup a MongoDB replication without arbiter, If the primary is unavailable, the replica set will elect a secondary to be primary. So I think it's kind of implicit arbiter, since the replica will elect a primary automatically.

So I am wondering why do we need a dedicated arbiter node? Thanks!

答:
I created a spreadsheet to better illustrate the effect of Arbiter nodes in a Replica Set.

It basically comes down to these points:

With an RS of 2 data nodes, losing 1 server brings you below your voting minimum (which is "greater than N/2"). An arbiter solves this.

With an RS of even numbered data nodes, adding an Arbiter increases your fault tolerance by 1 without making it possible to have 2 voting clusters due to a split.

With an RS of odd numbered data nodes, adding an Arbiter would allow a split to create 2 isolated clusters with "greater than N/2" votes and therefore a split brain scenario.

Elections are explained [in poor] detail here. In that document it states that an RS can have 50 members (even number) and 7 voting members. I emphasize "states" because it does not explain how it works. To me it seems that if you have a split happen with 4 members (all voting) on one side and 46 members (3 voting) on the other, you'd rather have the 46 elect a primary and the 4 to be a read-only cluster. But, that's exactly what "limited voting" prevents. In that situation you will actually have a 4 member cluster with a primary and a 46 member cluster that is read only. Explaining how that makes sense is out of the scope of this question and beyond my knowledge.


问:
SSRS - Major/minor gridlines spacing
I have an SSRS report with a bar chart with multiple series by CountryName Category group.  What I want to do is have gridlines which split each country like below:

However in SSRS the major gridlines seem to interval with the line in the middle of the country name when the grid interval is set to 1 like below:

Can someone point me in the right direction into how to rectify this?

Also is there a way of adding the X axis in SSRS to start from zero like I have in my first graph?

Thanks

答:
You can do it, there is an offset property on the grid lines (horizontal and vertical are separate). Click one one of the gridlines and look in the properties pane. Change the offset to 0.5.

Gives you this.

I'm not sure what you meant about starting from zero on the X-Axis, you have negative values so you'll start from a negative number. If you meant you wantde zero aligned to the middle. You can do that to. You need to set the min and max values of the horizontal axis to the following

Min Value:

```<code>=MAX(ABS(Fields!MyValueField.Value), "MyDataSet")*-1
</code>```

Max Value will be:

```<code>=MAX(ABS(Fields!MyValueField.Value), "MyDataSet")
</code>```

Basically we take the ABSolute largest value and use that as the extent (*-1 for the min value). The problem is that zero might not show so you'll have to play around with the Axis properties maybe to get that working. I'm sure it's possible but I don't have time to test at the moment.

My test data is not great as the number are large

Title: SSRS - Major/minor gridlines spacing

Body:
You can do it, there is an offset property on the grid lines (horizontal and vertical are separate). Click one one of the gridlines and look in the properties pane. Change the offset to 0.5.

Gives you this.

I'm not sure what you meant about starting from zero on the X-Axis, you have negative values so you'll start from a negative number. If you meant you wantde zero aligned to the middle. You can do that to. You need to set the min and max values of the horizontal axis to the following

Min Value:

=MAX(ABS(Fields!MyValueField.Value), "MyDataSet")*-1

Max Value will be:

=MAX(ABS(Fields!MyValueField.Value), "MyDataSet")

Basically we take the ABSolute largest value and use that as the extent (*-1 for the min value). The problem is that zero might not show so you'll have to play around with the Axis properties maybe to get that working. I'm sure it's possible but I don't have time to test at the moment.

My test data is not great as the number are large


问:
Redirect to website in a new window or tab
I have the following code and I need the timeout function, which works, but opening a new tab or window isn't.

How to change the code so when it redirects after five seconds it forwards the user to another site, but in a new window or tab?

$('#google').click(function(){
      setTimeout(function() {
         window.location.href = "https://google.com", '_blank'
      }, 5000);
      });```

答:
To open a new window you have to call window.open() function.

So your code becomes something like so:

```<code>$('#google').click(function(){
   setTimeout(function() {
      window.open('https://google.com') //this by default opens a new window
   }, 5000);
});
</code>```

UPDATE
This will probably lead to the browser blocking the popup (or opening of a new tab). If you want to open the new tab you will have to do it as soon as the user performs the click event, any delay will lead to blocking of the popup.

Body:
To open a new window you have to call window.open() function.

So your code becomes something like so:

$('#google').click(function(){
   setTimeout(function() {
      window.open('https://google.com') //this by default opens a new window
   }, 5000);
});

UPDATE
This will probably lead to the browser blocking the popup (or opening of a new tab). If you want to open the new tab you will have to do it as soon as the user performs the click event, any delay will lead to blocking of the popup.


问:
Delphi code to turn on screen saver doesn't work in Windows 7
I have a Delphi app that places the computer into screensave using

```<code>hWnd := GetDesktopWindow ;
SendMessage (hWnd, WM_SYSCOMMAND, SC_SCREENSAVE, 0) ;
</code>```

This works fine under XP but I find it doesn't work under (embedded) Windows 7.

Any ideas?

答: It works for me (Windows 7 Home Premium, 64-bit). Have you tried to send the message to another window, such as Handle? (Also, are you sure that you have a screensaver installed?)

Body:
I have a Delphi app that places the computer into screensave using

hWnd := GetDesktopWindow ;
SendMessage (hWnd, WM_SYSCOMMAND, SC_SCREENSAVE, 0) ;

This works fine under XP but I find it doesn't work under (embedded) Windows 7.

Any ideas?


问:
Can I embed a markdown file in a markdown file with Jekyll?
I am using Jekyll to generate a website.  Is it possible for a markdown file to include another markdown file?  This could be useful if, say, I want the same markdown text at the beginning of several pages.</p>

答:
I've never used Jekyll but some Google searching yields a combination of capture and markdownify:

```<code>{% capture my_include %}{% include a_markdown_file.md %}{% endcapture %}
{{ my_include | markdownify }}
</code>```

You can substitute my_include with whatever name you want.

Sources:

https://github.com/jekyll/jekyll/issues/1303 (particularly relevant)

http://ricostacruz.com/til/markdown-in-jekyll

Jekyll, include markdown with layout in html (answer to your question is implied in this question's text)

https://jekyllrb.com/docs/includes/

Body:
I've never used Jekyll but some Google searching yields a combination of capture and markdownify:

{% capture my_include %}{% include a_markdown_file.md %}{% endcapture %}
{{ my_include | markdownify }}

You can substitute my_include with whatever name you want.

Sources:

https://github.com/jekyll/jekyll/issues/1303 (particularly relevant)

http://ricostacruz.com/til/markdown-in-jekyll

Jekyll, include markdown with layout in html (answer to your question is implied in this question's text)

https://jekyllrb.com/docs/includes/


问:
Instantiate View Controller from Storyboard vs. Creating New Instance
What is the functional difference between instantiating a View Controller from the storyboard and creating a new instance of it? For example:

```<code>#import "SomeViewController.h"

...

SomeViewController *someViewController = [SomeViewController new];
</code>```

versus

```<code>#import "SomeViewController.h"

...

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];

SomeViewController *someViewController = [storyboard instantiateViewControllerWithIdentifier:@"SomeViewController"];
</code>```

In either case, is someViewController effectively the same thing?

答:
```<code>simple swift 3 extension
 fileprivate enum Storyboard : String {
        case main = "Main"
    }

    fileprivate extension UIStoryboard {
        static func loadFromMain(_ identifier: String) -> UIViewController {
            return load(from: .main, identifier: identifier)
        }

        static func load(from storyboard: Storyboard, identifier: String) -> UIViewController {
            let uiStoryboard = UIStoryboard(name: storyboard.rawValue, bundle: nil)
            return uiStoryboard.instantiateViewController(withIdentifier: identifier)
        }
    }

    // MARK: App View Controllers

    extension UIStoryboard {
        class func loadHomeViewController() ->  HomeViewController {
            return loadFromMain("HomeViewController") as! HomeViewController
        }
    }
</code>```

Body:
What is the functional difference between instantiating a View Controller from the storyboard and creating a new instance of it? For example:

#import "SomeViewController.h"

...

SomeViewController *someViewController = [SomeViewController new];

versus

#import "SomeViewController.h"

...

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];

SomeViewController *someViewController = [storyboard instantiateViewControllerWithIdentifier:@"SomeViewController"];

In either case, is someViewController effectively the same thing?


问:
How to use an admin react component on front-end?
How can I re-use the admin react-day-picker.js component (already included in keystonejs) on a front-end form date field?

答:
react-day-picker is installed as a Node module by Keystone. You can require/import it to re-use the code within that folder. You can alternatively save it as a depdency in your own project to make sure you always have it, though it isn't necessary since Keystone has it in its own package.json.

```<code>import DayPicker from "react-day-picker";

import "react-day-picker/lib/style.css"
</code>```

https://www.npmjs.com/package/react-day-picker

Body:
react-day-picker is installed as a Node module by Keystone. You can require/import it to re-use the code within that folder. You can alternatively save it as a depdency in your own project to make sure you always have it, though it isn't necessary since Keystone has it in its own package.json.

import DayPicker from "react-day-picker";

import "react-day-picker/lib/style.css"

https://www.npmjs.com/package/react-day-picker


问:
MySQL works in terminal but not in PHP
I have migrated my project from AWS to Google Cloud. I had a working application earlier, but now after migrating to GCP, mysqli_connect no longer seems to work.
So far, I have installed the following:

php-mysql-5.4.16-42.el7.x86_64

php-pdo-5.4.16-42.el7.x86_64

php-5.4.16-42.el7.x86_64

php-common-5.4.16-42.el7.x86_64

php-cli-5.4.16-42.el7.x86_64

mariadb-libs-5.5.52-1.el7.x86_64

mariadb-5.5.52-1.el7.x86_64

I am able to access MySQL using terminal but unable to connect to the remote database (on AWS RDS) using PHP. The RDS Database doesn't have any restriction on IP Connection and is open to the world. I have tried removing PHP, MySQL, MariaDB completely, however, no success. The script to connect to the database is unchanged since migration. Other functions such as mysqli_fetch_assoc and mysqli_query are not throwing any error. Here is the content of mysqld_log:

```<code>170329 07:20:15 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
170329 07:31:09 mysqld_safe Logging to '/var/log/mysqld.log'.
170329 07:31:09 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
2017-03-29 07:31:09 0 [Warning] s deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-03-29 07:31:09 0 [Note] /usr/sbin/mysqld (mysqld 5.6.35) starting as process 32611 ...
2017-03-29 07:31:09 32611 [Warning] Buffered warning: Changed limits: max_open_files: 1024 (requested 5000)

2017-03-29 07:31:09 32611 [Warning] Buffered warning: Changed limits: table_open_cache: 431 (requested 2000)

2017-03-29 07:31:09 32611 [Note] Plugin 'FEDERATED' is disabled.
2017-03-29 07:31:09 32611 [Note] InnoDB: Using atomics to ref count buffer pool pages
2017-03-29 07:31:09 32611 [Note] InnoDB: The InnoDB memory heap is disabled
2017-03-29 07:31:09 32611 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-03-29 07:31:09 32611 [Note] InnoDB: Memory barrier is not used
2017-03-29 07:31:09 32611 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-03-29 07:31:09 32611 [Note] InnoDB: Using Linux native AIO
2017-03-29 07:31:09 32611 [Note] InnoDB: Using CPU crc32 instructions
2017-03-29 07:31:09 32611 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2017-03-29 07:31:09 32611 [Note] InnoDB: Completed initialization of buffer pool
2017-03-29 07:31:09 32611 [Note] InnoDB: Highest supported file format is Barracuda.
2017-03-29 07:31:09 32611 [Note] InnoDB: 128 rollback segment(s) are active.
2017-03-29 07:31:09 32611 [Note] InnoDB: Waiting for purge to start
2017-03-29 07:31:09 32611 [Note] InnoDB: 5.6.35 started; log sequence number 1626037
2017-03-29 07:31:09 32611 [Note] Server hostname (bind-address): '*'; port: 3306
2017-03-29 07:31:09 32611 [Note] IPv6 is available.
2017-03-29 07:31:09 32611 [Note]   - '::' resolves to '::';
2017-03-29 07:31:09 32611 [Note] Server socket created on IP: '::'.
2017-03-29 07:31:09 32611 [Note] Event Scheduler: Loaded 0 events
2017-03-29 07:31:09 32611 [Note] /usr/sbin/mysqld: ready for connections.
Version: '5.6.35'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MySQL Community Server (GPL)
</code>```

答: You write that you use mysqli_connect, but you have installed php-mysql-5.4.16-42.el7.x86_64 (Note: no 'i'). You need the package for mysqli in order for PHP to connect.</p>

Title: MySQL works in terminal but not in PHP

Body:
I have migrated my project from AWS to Google Cloud. I had a working application earlier, but now after migrating to GCP, mysqli_connect no longer seems to work.
So far, I have installed the following:

php-mysql-5.4.16-42.el7.x86_64

php-pdo-5.4.16-42.el7.x86_64

php-5.4.16-42.el7.x86_64

php-common-5.4.16-42.el7.x86_64

php-cli-5.4.16-42.el7.x86_64

mariadb-libs-5.5.52-1.el7.x86_64

mariadb-5.5.52-1.el7.x86_64

I am able to access MySQL using terminal but unable to connect to the remote database (on AWS RDS) using PHP. The RDS Database doesn't have any restriction on IP Connection and is open to the world. I have tried removing PHP, MySQL, MariaDB completely, however, no success. The script to connect to the database is unchanged since migration. Other functions such as mysqli_fetch_assoc and mysqli_query are not throwing any error. Here is the content of mysqld_log:

170329 07:20:15 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
170329 07:31:09 mysqld_safe Logging to '/var/log/mysqld.log'.
170329 07:31:09 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
2017-03-29 07:31:09 0 [Warning] s deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-03-29 07:31:09 0 [Note] /usr/sbin/mysqld (mysqld 5.6.35) starting as process 32611 ...
2017-03-29 07:31:09 32611 [Warning] Buffered warning: Changed limits: max_open_files: 1024 (requested 5000)

2017-03-29 07:31:09 32611 [Warning] Buffered warning: Changed limits: table_open_cache: 431 (requested 2000)

2017-03-29 07:31:09 32611 [Note] Plugin 'FEDERATED' is disabled.
2017-03-29 07:31:09 32611 [Note] InnoDB: Using atomics to ref count buffer pool pages
2017-03-29 07:31:09 32611 [Note] InnoDB: The InnoDB memory heap is disabled
2017-03-29 07:31:09 32611 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-03-29 07:31:09 32611 [Note] InnoDB: Memory barrier is not used
2017-03-29 07:31:09 32611 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-03-29 07:31:09 32611 [Note] InnoDB: Using Linux native AIO
2017-03-29 07:31:09 32611 [Note] InnoDB: Using CPU crc32 instructions
2017-03-29 07:31:09 32611 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2017-03-29 07:31:09 32611 [Note] InnoDB: Completed initialization of buffer pool
2017-03-29 07:31:09 32611 [Note] InnoDB: Highest supported file format is Barracuda.
2017-03-29 07:31:09 32611 [Note] InnoDB: 128 rollback segment(s) are active.
2017-03-29 07:31:09 32611 [Note] InnoDB: Waiting for purge to start
2017-03-29 07:31:09 32611 [Note] InnoDB: 5.6.35 started; log sequence number 1626037
2017-03-29 07:31:09 32611 [Note] Server hostname (bind-address): '*'; port: 3306
2017-03-29 07:31:09 32611 [Note] IPv6 is available.
2017-03-29 07:31:09 32611 [Note]   - '::' resolves to '::';
2017-03-29 07:31:09 32611 [Note] Server socket created on IP: '::'.
2017-03-29 07:31:09 32611 [Note] Event Scheduler: Loaded 0 events
2017-03-29 07:31:09 32611 [Note] /usr/sbin/mysqld: ready for connections.
Version: '5.6.35'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MySQL Community Server (GPL)


问:
Python: 'list' object has no attribute 'read'
I have a list with a single string that contains non-ascii characters. My goal is to get rid of the non-ascii characters and convert the list to a string.

Every time I try to strip out the non-ascii characters, I get this error: 'list' object has no attribute 'read'

I've tried most of these and I still get this error every time. I'm not sure what I am doing wrong, any help would be appreciated.

答:
```<code>result = ''.join([s.encode('ascii','ignore') for s in mylist])
</code>```


问:
Android - Set max length of logcat messages
By default, it seems that logcat will truncate any log message that it considers to be "too long".  This happens both inside of Eclipse and when running logcat on the command line using adb -d logcat, and is truncating some important debugging messages.

Is there any way to increase the maximum string length supported by logcat to get it to stop truncating the debug information?  The official documentation implies that there may not be, but maybe logcat supports some additional options not mentioned there?

答:
If your log is very long (eg. logging entire dump of your database for debugging reasons etc.) it may happen that logcat prevents excessive logging. To work around this you can add a timeout evry x milliseconds.

```<code>/**
 * Used for very long messages, splits it into equal chunks and logs each individual to
 * work around the logcat max message length. Will log with {@link Log#d(String, String)}.
 *
 * @param tag     used in for logcat
 * @param message long message to log
 */
public static void longLogDebug(final String tag, @NonNull String message) {
    int i = 0;

    final int maxLogLength = 1000;
    while (message.length() > maxLogLength) {
        Log.d(tag, message.substring(0, maxLogLength));
        message = message.substring(maxLogLength);
        i++;

        if (i % 100 == 0) {
            StrictMode.noteSlowCall("wait to flush logcat");
            SystemClock.sleep(32);
        }
    }
    Log.d(tag, message);
}
</code>```

Beware, only use this for debugging purpose as it may halts blocks main thread.

Body:
If your log is very long (eg. logging entire dump of your database for debugging reasons etc.) it may happen that logcat prevents excessive logging. To work around this you can add a timeout evry x milliseconds.

/**
 * Used for very long messages, splits it into equal chunks and logs each individual to
 * work around the logcat max message length. Will log with {@link Log#d(String, String)}.
 *
 * @param tag     used in for logcat
 * @param message long message to log
 */
public static void longLogDebug(final String tag, @NonNull String message) {
    int i = 0;

    final int maxLogLength = 1000;
    while (message.length() > maxLogLength) {
        Log.d(tag, message.substring(0, maxLogLength));
        message = message.substring(maxLogLength);
        i++;

        if (i % 100 == 0) {
            StrictMode.noteSlowCall("wait to flush logcat");
            SystemClock.sleep(32);
        }
    }
    Log.d(tag, message);
}

Beware, only use this for debugging purpose as it may halts blocks main thread.


问:
Reapeat/replay a session x times with a different request header
is it possible to reapeat/replay a session x times with a different reaquest header.

I was thinking of a for loop inside OnBeforeRequest which will iterate over the same request from the session, but with a different parameter for the request header ...

But I am kind of lost, can you help me?

答:
```<code>    for (var i=0; i< 50; i++)
    {
        var oSD = new System.Collections.Specialized.StringDictionary();
        oSD.Add("x-Builder-MaxRedir", "10");
        var oRH: Fiddler.HTTPRequestHeaders = new Fiddler.HTTPRequestHeaders();

        var oURI: System.Uri = new Uri("https://whatever.com/" + i.ToString());

        var sHeaders: String = String.Format("GET {0} HTTP/1.1\r\nHost: {1}\r\n\r\n", oURI.PathAndQuery, oURI.Host);
  // ^^^ Add any header you like here, then...
        oRH.AssignFromString(sHeaders);
        var newSession = FiddlerApplication.oProxy.SendRequest(oRH, null, oSD);

    }
</code>```


问:
doxygen is generating empty documentation
I have a source repository in C++ (and some CUDA), which I want to doxygenate. I've added doxygen comments to some - but not all - of the code; generated a Doxygen config file, and ran doxygen with it to see some partial output.

What I get is: Nothing. Empty.

A main page is generated, it just doesn't show anything - even though I specifically set EXTRACT_ALL = YES (after getting empty results with EXTRACT_ALL = NO.

Why is nothing being generated and how can I fix it?

Notes:

All header files have @file comments.

I've added CUDA-related extensions to the allowed patterns

I had an earlier version of this question, with no answers following which the situation changed somewhat (so I deleted that one).

Even when removing most lines out of the doxygen.cfg (see below), the problem persists.

doxygen.cfg (shorter version, with comments filtered out):

```<code>DOXYFILE_ENCODING      = UTF-8
PROJECT_NAME           = "cuda-api-wrappers"
PROJECT_BRIEF          = "Thin C++-flavored wrappers for the CUDA Runtime API"
OUTPUT_DIRECTORY       = docs
ALLOW_UNICODE_NAMES    = YES
OUTPUT_LANGUAGE        = English
BRIEF_MEMBER_DESC      = YES
REPEAT_BRIEF           = YES
FULL_PATH_NAMES        = YES
JAVADOC_AUTOBRIEF      = YES
QT_AUTOBRIEF           = NO
MULTILINE_CPP_IS_BRIEF = NO
INHERIT_DOCS           = YES
SEPARATE_MEMBER_PAGES  = NO
TAB_SIZE               = 4
EXTENSION_MAPPING      = cu=C++ cuh=C++ cuhpp=C++ hpp=C++
MARKDOWN_SUPPORT       = YES
AUTOLINK_SUPPORT       = YES
BUILTIN_STL_SUPPORT    = YES
SUBGROUPING            = YES
LOOKUP_CACHE_SIZE      = 2
EXTRACT_ALL            = YES
EXTRACT_LOCAL_CLASSES  = YES
HIDE_UNDOC_MEMBERS     = NO
HIDE_UNDOC_CLASSES     = NO
HIDE_FRIEND_COMPOUNDS  = NO
CASE_SENSE_NAMES       = YES
HIDE_SCOPE_NAMES       = NO
HIDE_COMPOUND_REFERENCE= NO
SHOW_INCLUDE_FILES     = YES
SHOW_GROUPED_MEMB_INC  = NO
FORCE_LOCAL_INCLUDES   = NO
INLINE_INFO            = YES
SORT_MEMBER_DOCS       = YES
STRICT_PROTO_MATCHING  = NO
MAX_INITIALIZER_LINES  = 30
SHOW_USED_FILES        = YES
SHOW_FILES             = YES
SHOW_NAMESPACES        = YES
QUIET                  = NO
WARNINGS               = YES
WARN_IF_UNDOCUMENTED   = YES
WARN_IF_DOC_ERROR      = YES
WARN_NO_PARAMDOC       = NO
WARN_AS_ERROR          = NO
WARN_FORMAT            = "$file:$line: $text"
INPUT                  = src
INPUT_ENCODING         = UTF-8
FILE_PATTERNS          = *.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, *.qsf, *.as *.js, *.cuh, *.cu, *.cuhpp
RECURSIVE              = YES
</code>```

Doxygen console output:

```<code>Adding custom extension mapping: .cu will be treated as language c++
Adding custom extension mapping: .cuh will be treated as language c++
Adding custom extension mapping: .cuhpp will be treated as language c++
Adding custom extension mapping: .hpp will be treated as language c++
Searching for include files...
Searching for example files...
Searching for images...
Searching for dot files...
Searching for msc files...
Searching for dia files...
Searching for files to exclude
Searching INPUT for files to process...
Searching for files in directory /home/eyalroz/src/mine/cuda-api-wrappers/src
Searching for files in directory /home/eyalroz/src/mine/cuda-api-wrappers/src/cuda
Searching for files in directory /home/eyalroz/src/mine/cuda-api-wrappers/src/cuda/api
Reading and parsing tag files
Parsing files
Building group list...
Building directory list...
Building namespace list...
Building file list...
Building class list...
Associating documentation with classes...
Computing nesting relations for classes...
Building example list...
Searching for enumerations...
Searching for documented typedefs...
Searching for members imported via using declarations...
Searching for included using directives...
Searching for documented variables...
Building interface member list...
Building member list...
Searching for friends...
Searching for documented defines...
Computing class inheritance relations...
Computing class usage relations...
Flushing cached template relations that have become invalid...
Creating members for template instances...
Computing class relations...
Add enum values to enums...
Searching for member function documentation...
Building page list...
Search for main page...
Computing page relations...
Determining the scope of groups...
Sorting lists...
Freeing entry tree
Determining which enums are documented
Computing member relations...
Building full member lists recursively...
Adding members to member groups.
Computing member references...
Inheriting documentation...
Generating disk names...
Adding source references...
Adding xrefitems...
Sorting member lists...
Computing dependencies between directories...
Generating citations page...
Counting data structures...
Resolving user defined references...
Finding anchors and sections in the documentation...
Transferring function references...
Combining using relations...
Adding members to index pages...
Generating style sheet...
Generating search indices...
Generating example documentation...
Generating file sources...
Generating file documentation...
Generating page documentation...
Generating group documentation...
Generating class documentation...
Generating namespace index...
Generating graph info page...
Generating directory documentation...
Generating index page...
Generating page index...
Generating module index...
Generating namespace index...
Generating namespace member index...
Generating annotated compound index...
Generating alphabetical compound index...
Generating hierarchical class index...
Generating graphical class hierarchy...
Generating member index...
Generating file index...
Generating file member index...
Generating example index...
finalizing index lists...
writing tag file...
Running dot...
lookup cache used 127/262144 hits=628 misses=194
finished...
</code>```

答:
TL;DR: Drop the commas in the FILE_PATTERNS variable and make it space-separated.

Instead of:

```<code>FILE_PATTERNS          = *.c, *.cc, *.cxx, *.etc
</code>```

you should use:

```<code>FILE_PATTERNS          = *.c *.cc *.cxx *.etc
</code>```

Explanation

@albert is the one who cracked this conundrum...

The Doxygen-generated config file says:

```<code># If the value of the INPUT tag contains directories, you can use the
# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
# *.h) to filter out the source-files in the directories.
#
# Note that for custom extensions or not directly supported extensions you also
# need to set EXTENSION_MAPPING for the extension otherwise the files are not
# read by doxygen.
#
# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,
# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,
# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc,
# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f, *.for, *.tcl,
# *.vhd, *.vhdl, *.ucf, *.qsf, *.as and *.js.

FILE_PATTERNS          =
</code>```

this comment is misleading, since it gives you a comma-separated list, while in fact commas are not treated as separators. If you use that list (and perhaps add/change it), like in OP's example, Doxygen sees a list of patterns with the extensions having a trailing , character. And - it doesn't complain. It also doesn't complain about ignoring essentially all files in the repository - it just ends up with an empty result.

Dropping the , characters results in non-empty generated documentation.

Note: Beginning with Doxygen version 1.8.15, this should no longer be an issue, and commas should be accepted as delimiters of fields.

Body:
I have a source repository in C++ (and some CUDA), which I want to doxygenate. I've added doxygen comments to some - but not all - of the code; generated a Doxygen config file, and ran doxygen with it to see some partial output.

What I get is: Nothing. Empty.

A main page is generated, it just doesn't show anything - even though I specifically set EXTRACT_ALL = YES (after getting empty results with EXTRACT_ALL = NO.

Why is nothing being generated and how can I fix it?

Notes:

All header files have @file comments.

I've added CUDA-related extensions to the allowed patterns

I had an earlier version of this question, with no answers following which the situation changed somewhat (so I deleted that one).

Even when removing most lines out of the doxygen.cfg (see below), the problem persists.

doxygen.cfg (shorter version, with comments filtered out):

DOXYFILE_ENCODING      = UTF-8
PROJECT_NAME           = "cuda-api-wrappers"
PROJECT_BRIEF          = "Thin C++-flavored wrappers for the CUDA Runtime API"
OUTPUT_DIRECTORY       = docs
ALLOW_UNICODE_NAMES    = YES
OUTPUT_LANGUAGE        = English
BRIEF_MEMBER_DESC      = YES
REPEAT_BRIEF           = YES
FULL_PATH_NAMES        = YES
JAVADOC_AUTOBRIEF      = YES
QT_AUTOBRIEF           = NO
MULTILINE_CPP_IS_BRIEF = NO
INHERIT_DOCS           = YES
SEPARATE_MEMBER_PAGES  = NO
TAB_SIZE               = 4
EXTENSION_MAPPING      = cu=C++ cuh=C++ cuhpp=C++ hpp=C++
MARKDOWN_SUPPORT       = YES
AUTOLINK_SUPPORT       = YES
BUILTIN_STL_SUPPORT    = YES
SUBGROUPING            = YES
LOOKUP_CACHE_SIZE      = 2
EXTRACT_ALL            = YES
EXTRACT_LOCAL_CLASSES  = YES
HIDE_UNDOC_MEMBERS     = NO
HIDE_UNDOC_CLASSES     = NO
HIDE_FRIEND_COMPOUNDS  = NO
CASE_SENSE_NAMES       = YES
HIDE_SCOPE_NAMES       = NO
HIDE_COMPOUND_REFERENCE= NO
SHOW_INCLUDE_FILES     = YES
SHOW_GROUPED_MEMB_INC  = NO
FORCE_LOCAL_INCLUDES   = NO
INLINE_INFO            = YES
SORT_MEMBER_DOCS       = YES
STRICT_PROTO_MATCHING  = NO
MAX_INITIALIZER_LINES  = 30
SHOW_USED_FILES        = YES
SHOW_FILES             = YES
SHOW_NAMESPACES        = YES
QUIET                  = NO
WARNINGS               = YES
WARN_IF_UNDOCUMENTED   = YES
WARN_IF_DOC_ERROR      = YES
WARN_NO_PARAMDOC       = NO
WARN_AS_ERROR          = NO
WARN_FORMAT            = "$file:$line: $text"
INPUT                  = src
INPUT_ENCODING         = UTF-8
FILE_PATTERNS          = *.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, *.qsf, *.as *.js, *.cuh, *.cu, *.cuhpp
RECURSIVE              = YES

Doxygen console output:

Adding custom extension mapping: .cu will be treated as language c++
Adding custom extension mapping: .cuh will be treated as language c++
Adding custom extension mapping: .cuhpp will be treated as language c++
Adding custom extension mapping: .hpp will be treated as language c++
Searching for include files...
Searching for example files...
Searching for images...
Searching for dot files...
Searching for msc files...
Searching for dia files...
Searching for files to exclude
Searching INPUT for files to process...
Searching for files in directory /home/eyalroz/src/mine/cuda-api-wrappers/src
Searching for files in directory /home/eyalroz/src/mine/cuda-api-wrappers/src/cuda
Searching for files in directory /home/eyalroz/src/mine/cuda-api-wrappers/src/cuda/api
Reading and parsing tag files
Parsing files
Building group list...
Building directory list...
Building namespace list...
Building file list...
Building class list...
Associating documentation with classes...
Computing nesting relations for classes...
Building example list...
Searching for enumerations...
Searching for documented typedefs...
Searching for members imported via using declarations...
Searching for included using directives...
Searching for documented variables...
Building interface member list...
Building member list...
Searching for friends...
Searching for documented defines...
Computing class inheritance relations...
Computing class usage relations...
Flushing cached template relations that have become invalid...
Creating members for template instances...
Computing class relations...
Add enum values to enums...
Searching for member function documentation...
Building page list...
Search for main page...
Computing page relations...
Determining the scope of groups...
Sorting lists...
Freeing entry tree
Determining which enums are documented
Computing member relations...
Building full member lists recursively...
Adding members to member groups.
Computing member references...
Inheriting documentation...
Generating disk names...
Adding source references...
Adding xrefitems...
Sorting member lists...
Computing dependencies between directories...
Generating citations page...
Counting data structures...
Resolving user defined references...
Finding anchors and sections in the documentation...
Transferring function references...
Combining using relations...
Adding members to index pages...
Generating style sheet...
Generating search indices...
Generating example documentation...
Generating file sources...
Generating file documentation...
Generating page documentation...
Generating group documentation...
Generating class documentation...
Generating namespace index...
Generating graph info page...
Generating directory documentation...
Generating index page...
Generating page index...
Generating module index...
Generating namespace index...
Generating namespace member index...
Generating annotated compound index...
Generating alphabetical compound index...
Generating hierarchical class index...
Generating graphical class hierarchy...
Generating member index...
Generating file index...
Generating file member index...
Generating example index...
finalizing index lists...
writing tag file...
Running dot...
lookup cache used 127/262144 hits=628 misses=194
finished...

Body:
TL;DR: Drop the commas in the FILE_PATTERNS variable and make it space-separated.

Instead of:

FILE_PATTERNS          = *.c, *.cc, *.cxx, *.etc

you should use:

FILE_PATTERNS          = *.c *.cc *.cxx *.etc

Explanation

@albert is the one who cracked this conundrum...

The Doxygen-generated config file says:

# If the value of the INPUT tag contains directories, you can use the
# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
# *.h) to filter out the source-files in the directories.
#
# Note that for custom extensions or not directly supported extensions you also
# need to set EXTENSION_MAPPING for the extension otherwise the files are not
# read by doxygen.
#
# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,
# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,
# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc,
# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f, *.for, *.tcl,
# *.vhd, *.vhdl, *.ucf, *.qsf, *.as and *.js.

FILE_PATTERNS          =

this comment is misleading, since it gives you a comma-separated list, while in fact commas are not treated as separators. If you use that list (and perhaps add/change it), like in OP's example, Doxygen sees a list of patterns with the extensions having a trailing , character. And - it doesn't complain. It also doesn't complain about ignoring essentially all files in the repository - it just ends up with an empty result.

Dropping the , characters results in non-empty generated documentation.

Note: Beginning with Doxygen version 1.8.15, this should no longer be an issue, and commas should be accepted as delimiters of fields.


问:
Laravel: Perform where using multiple tables
I'm using the Eloquent ORM that Laravel provides and I want to perform a where over two tables.  I have 3 models

House

Occupants

Job

The occupants table has a column called pocket_money and the jobs table has a column called income.  The occupant can have multiple jobs so I want to select all of the occupants where the sum of their income + pocket_money is greater than X.  So the raw query would be

```<code>select occupants.*
from occupants o, jobs j
where o.pocket_money + sum(j.income) > X
and o.occupant_id = j.occupant_id
</code>```

This is what I have at the moment but it doesn't work as the occupants table isn't available when it executes the query.

```<code>$occupants = House::with(["occupants", "occupants.jobs" => function($query) {
    $query->where('occupants.pocket_money + sum(jobs.income)', '>', 1000);
}])->find($house_id);
</code>```

答:
try this

```<code>$occupants = House::with(["occupants.jobs", "occupants" => function($query) {
     $query->leftJoin('jobs','jobs.occupant_id','=','occupants.id')
           ->select("occupants.*")
           ->whereRaw('occupants.pocket_money + sum(jobs.income) > 1000')
 }])->find($house_id);
</code>```

Hope it helps. (Not tested though)

Body:
I'm using the Eloquent ORM that Laravel provides and I want to perform a where over two tables.  I have 3 models

House

Occupants

Job

The occupants table has a column called pocket_money and the jobs table has a column called income.  The occupant can have multiple jobs so I want to select all of the occupants where the sum of their income + pocket_money is greater than X.  So the raw query would be

select occupants.*
from occupants o, jobs j
where o.pocket_money + sum(j.income) > X
and o.occupant_id = j.occupant_id

This is what I have at the moment but it doesn't work as the occupants table isn't available when it executes the query.

$occupants = House::with(["occupants", "occupants.jobs" => function($query) {
    $query->where('occupants.pocket_money + sum(jobs.income)', '>', 1000);
}])->find($house_id);

Body:
try this

$occupants = House::with(["occupants.jobs", "occupants" => function($query) {
     $query->leftJoin('jobs','jobs.occupant_id','=','occupants.id')
           ->select("occupants.*")
           ->whereRaw('occupants.pocket_money + sum(jobs.income) > 1000')
 }])->find($house_id);

Hope it helps. (Not tested though)


问:
Can I use multiple top level domains for my Github repositories?
I want to have this kind of custom domains setup.

arunsathiya.github.io = sathiya.me
 arunsathiya/blog =
  blog.sathiya.me
 arunsathiya/project-one = projectone.com

  arunsathiya/project-two = projecttwo.com

How can I get this done? I need to know proper DNS records for this setup.

答:
I figured out how to go about this. I added CNAME records for the subdomain. A records for the top level domain with the IP mentioned by Github.

Added the domains to Github repository settings and created CNAME files in the repositories.


问:
Selecting rows which are not linked to another table
I have a table called 'messages', which contains the columns sender_id, recipient_id, message (the text of the message) and readbyrecipient (a flag to indicate whether the message was read by the person to whom it was sent.

I am implementing the option to block users, so have added a table called block with columns blocker_id (the user who did the blocking) and blockee_id (the user who was blocked). All of the *_id columns link to my users table.

I am trying to get all unread messages which are not sent from users which were blocked by the recipient. Here's the query I have been working with:

```<code>SELECT
    A.*
FROM
    messages A,
    block B
WHERE
    A.recipient_id = 18
    AND A.readbyrecipient = 0
    AND NOT (
                B.blocker_id = A.recipient_id
                AND
                B.blockee_id = A.sender_id
            )
</code>```

This returns no rows, even though I know the user id specified in A.recipient_id refers to a user who has one unread message from a user whom they have not blocked. I tried removing the AND NOT clause in the query, but it still returned zero rows until I removed block B from the SELECT part of the query, so I'm not sure whether the problem is with the WHERE clause or the SELECT clause.

Thanks in advance!

答:
You can find all the records that do not have a matching record by using a left join and then in the where clause, specifying that a field in that table must be null. True only for records that didn't have a match.</p>

```<code>SELECT
    A.*
FROM `messages` A
LEFT JOIN `BLOCK` B
ON B.`blockee_id` = a.`sender_id` OR B.`blockee_id` = a.`recipient_id`
WHERE b.`blockee_id` is NULL;
</code>```

Body:
I have a table called 'messages', which contains the columns sender_id, recipient_id, message (the text of the message) and readbyrecipient (a flag to indicate whether the message was read by the person to whom it was sent.

I am implementing the option to block users, so have added a table called block with columns blocker_id (the user who did the blocking) and blockee_id (the user who was blocked). All of the *_id columns link to my users table.

I am trying to get all unread messages which are not sent from users which were blocked by the recipient. Here's the query I have been working with:

SELECT
    A.*
FROM
    messages A,
    block B
WHERE
    A.recipient_id = 18
    AND A.readbyrecipient = 0
    AND NOT (
                B.blocker_id = A.recipient_id
                AND
                B.blockee_id = A.sender_id
            )

This returns no rows, even though I know the user id specified in A.recipient_id refers to a user who has one unread message from a user whom they have not blocked. I tried removing the AND NOT clause in the query, but it still returned zero rows until I removed block B from the SELECT part of the query, so I'm not sure whether the problem is with the WHERE clause or the SELECT clause.

Thanks in advance!

Body:
You can find all the records that do not have a matching record by using a left join and then in the where clause, specifying that a field in that table must be null. True only for records that didn't have a match.

SELECT
    A.*
FROM `messages` A
LEFT JOIN `BLOCK` B
ON B.`blockee_id` = a.`sender_id` OR B.`blockee_id` = a.`recipient_id`
WHERE b.`blockee_id` is NULL;