问:
C# StackOverFlowException when creating new instance of class
Hm i get a strange problem. when i creating new instance of class i get StackOverflowExcepion :)

Here is code:

```<code>public partial class PlayerChooser : Window
{
public PlayerChooser()
    {
        InitializeComponent();
        textBoxPlayer1Name.Visibility = Visibility.Hidden;
        textBoxPlayer2Name.Visibility = Visibility.Hidden;
        textBoxPlayer3Name.Visibility = Visibility.Hidden;
        textBoxPlayer4Name.Visibility = Visibility.Hidden;

    }

    public static String player1Name;
    public static String player2Name;
    public static String player3Name;
    public static String player4Name;
    ...

    PlayerChooser.player1Name = textBoxPlayer1Name.Text;
    PlayerChooser.player2Name = textBoxPlayer2Name.Text;
    TwoPlayers501_new twoPlayers501_new = new TwoPlayers501_new();
    twoPlayers501_new.Show();
    ...
}
</code>```

and class and constructor where exception occurs

```<code>public partial class TwoPlayers501_new : Window
{
    public TwoPlayers501_new()
    {
        InitializeComponent();

        textBlockPlayer1Name.Text = PlayerChooser.player1Name;
        textBlockPlayer2Name.Text = PlayerChooser.player2Name;
    }
    ...
}
</code>```

thanx in advance, it is probably some kind of triviality...

答:
Do you have an event handler somewhere performing an action that changes one of those properties based on the property having been changed?

Short version:  There isn't enough information here to debug your problem.

Suggestion:  Debug your program and when you get the stackoverflowexception, check out the callstack.  I suspect that there's a method or series of methods that cycle infinitely in your stack.

Body:
Hm i get a strange problem. when i creating new instance of class i get StackOverflowExcepion :)

Here is code:

public partial class PlayerChooser : Window
{
public PlayerChooser()
    {
        InitializeComponent();
        textBoxPlayer1Name.Visibility = Visibility.Hidden;
        textBoxPlayer2Name.Visibility = Visibility.Hidden;
        textBoxPlayer3Name.Visibility = Visibility.Hidden;
        textBoxPlayer4Name.Visibility = Visibility.Hidden;

    }

    public static String player1Name;
    public static String player2Name;
    public static String player3Name;
    public static String player4Name;
    ...

    PlayerChooser.player1Name = textBoxPlayer1Name.Text;
    PlayerChooser.player2Name = textBoxPlayer2Name.Text;
    TwoPlayers501_new twoPlayers501_new = new TwoPlayers501_new();
    twoPlayers501_new.Show();
    ...
}

and class and constructor where exception occurs

public partial class TwoPlayers501_new : Window
{
    public TwoPlayers501_new()
    {
        InitializeComponent();

        textBlockPlayer1Name.Text = PlayerChooser.player1Name;
        textBlockPlayer2Name.Text = PlayerChooser.player2Name;
    }
    ...
}

thanx in advance, it is probably some kind of triviality...


来源: stackexchange

问:
MYSQLI Connection refused when connecting to another docker container running MariaDB
I'm starting to get my hands dirty with Docker and I'm trying to get my PHP application running in a docker container with nginx to connect to the database running in another container running MariaDB.

When I run the containers, I can connect without any problems to the database from my computer (using Sequel Pro) but when i try to connect to the database from the PHP application running in the nginx container I get the following mysqli error:

Warning: mysqli_connect(): (HY000/2002): Connection refused in >/app/web/php/db-config.php on line 7
  Failed to connect to the database, died with error:

The db-config.php where the error happens is as follows:

```<code>    define('DB_HOST', '0.0.0.0:3306');
    define('DB_NAME', 'Jumpooling');
    define('DB_USER', 'root');
    define('DB_PASSWORD', 'root');

    $con=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die('Failed to connect to the database, died with error:');
</code>```

All the docker-compose.yml file content is in this repository.

What am I missing?

答:
Links are not required to enable services to communicate - by default, any service can reach any other service at that service’s name.

Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.

ContentLicense: CC BY-SA 3.0

Body:
I'm starting to get my hands dirty with Docker and I'm trying to get my PHP application running in a docker container with nginx to connect to the database running in another container running MariaDB.

When I run the containers, I can connect without any problems to the database from my computer (using Sequel Pro) but when i try to connect to the database from the PHP application running in the nginx container I get the following mysqli error:

Warning: mysqli_connect(): (HY000/2002): Connection refused in >/app/web/php/db-config.php on line 7
  Failed to connect to the database, died with error:

The db-config.php where the error happens is as follows:

    define('DB_HOST', '0.0.0.0:3306');
    define('DB_NAME', 'Jumpooling');
    define('DB_USER', 'root');
    define('DB_PASSWORD', 'root');

    $con=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die('Failed to connect to the database, died with error:');

All the docker-compose.yml file content is in this repository.

What am I missing?


问:
Counting the position of a character after two or more spaces
I am trying to return a value equal to the position of the first letter coming after two or more spaces.

I have a tool that extract tables with variable column length into TXT docs. I need to get these tables into an Excel sheet without having to put fixed width to each column in each table (that is a lot of coding to be done). I am trying to find something more dynamic to do so based on the position of the first character after two or more spaces.

Bearing in mind that not all rows are fully populated but the first row would make a perfect candidate to get the width of the column.

To give an example, the lines of the text would look like this

John       Robert       Eric       Tom

10          11            143        43

21                       265        56

99          241                     76

All I got so far is to make it work with fixed width as per the code below

```<code>Sub exporttosheet()

Dim fPath As String
fPath = "C:\test.txt"

Const fsoForReading = 1
Const F_LEN_A As Integer = 10
Const F_LEN_B As Integer = 23
Const F_LEN_C As Integer = 7
Const F_LEN_D As Integer = 10

Dim objFSO As Object, objTextStream As Object, txt, f1, f2, f3, f4
Dim start As Integer
Dim fLen As Integer
Dim rw As Long

Set objFSO = CreateObject("scripting.filesystemobject")
Set objTextStream = objFSO.OpenTextFile(fPath, fsoForReading)
rw = 1

Do Until objTextStream.AtEndOfStream
    txt = objTextStream.Readline

    f1 = Trim(Left(txt, F_LEN_A))
    start = F_LEN_A + 1
    f2 = Trim(Mid(txt, start, F_LEN_B))
    start = start + F_LEN_B + 1
    f3 = Trim(Mid(txt, start, F_LEN_C))
    start = start + F_LEN_C + 1
    f4 = Trim(Mid(txt, start, F_LEN_D))

    With ThisWorkbook.Sheets("data").Cells(rw, 1).Resize(1, 4)
        .NumberFormat = "@" 'format cells as text
        .Value = Array(f1, f2, f3, f4)
    End With
    rw = rw + 1
Loop

objTextStream.Close
End Sub
</code>```

答:
In lieu of any confirmation from you, I am going to assume that there actually is unicode characters in your actual data.

```<code>Option Explicit

Sub Split_My_Data()
    Dim s As Long, str As String, tmp As Variant, varFieldInfo As Variant

    ReDim tmp(0 To 0)

    With Worksheets("Sheet3")
        str = .Cells(1, 1).Value2
        s = Application.Max(InStrRev(str, Chr(32)), _
                            InStrRev(str, ChrW(8194)))
        Do While CBool(s)
            tmp(UBound(tmp)) = Array(s, 1)
            str = Left(str, s)
            Do While Right(str, 1) = Chr(32) Or Right(str, 1) = ChrW(8194): str = Left(str, Len(str) - 1): Loop
            s = Application.Max(InStrRev(str, Chr(32)), _
                                InStrRev(str, ChrW(8194)))
            ReDim Preserve tmp(LBound(tmp) To UBound(tmp) + 1)
            If Not CBool(s) Then Exit Do
        Loop

        'make the last (first) fieldinfo element
        tmp(UBound(tmp)) = Array(0, 1)

        'make room for the reversed fieldinfo
        ReDim varFieldInfo(LBound(tmp) To UBound(tmp))

        'reverse the fieldinfo array
        For s = UBound(tmp) To LBound(tmp) Step -1
            varFieldInfo(UBound(tmp) - s) = tmp(s)
        Next s

        'run TextToColumns with the new array of arrays for FieldInfo
        .Columns("A:A").TextToColumns Destination:=.Cells(1, "A"), DataType:=xlFixedWidth, FieldInfo:=varFieldInfo

        For s = 1 To .Cells(1, .Columns.Count).End(xlToLeft).Column
            With Intersect(.Columns(s), .UsedRange).Cells
                'get rid of unicode
                .Replace what:=ChrW(8194), replacement:=vbNullString, lookat:=xlPart
                'use another texttocolumns as a fast Trim
                .TextToColumns Destination:=.Cells(1, "A"), DataType:=xlFixedWidth, FieldInfo:=Array(Array(0, 1))
                'shrink/expand the column
                .EntireColumn.AutoFit
                .EntireColumn.ColumnWidth = Application.Max(.ColumnWidth, 9)
            End With
        Next s
    End With
End Sub
</code>```

Results with text as trimmed text and numbers as real numbers (no unicode):

Body:
I am trying to return a value equal to the position of the first letter coming after two or more spaces.

I have a tool that extract tables with variable column length into TXT docs. I need to get these tables into an Excel sheet without having to put fixed width to each column in each table (that is a lot of coding to be done). I am trying to find something more dynamic to do so based on the position of the first character after two or more spaces.

Bearing in mind that not all rows are fully populated but the first row would make a perfect candidate to get the width of the column.

To give an example, the lines of the text would look like this

John       Robert       Eric       Tom

10          11            143        43

21                       265        56

99          241                     76

All I got so far is to make it work with fixed width as per the code below

Sub exporttosheet()

Dim fPath As String
fPath = "C:\test.txt"

Const fsoForReading = 1
Const F_LEN_A As Integer = 10
Const F_LEN_B As Integer = 23
Const F_LEN_C As Integer = 7
Const F_LEN_D As Integer = 10

Dim objFSO As Object, objTextStream As Object, txt, f1, f2, f3, f4
Dim start As Integer
Dim fLen As Integer
Dim rw As Long

Set objFSO = CreateObject("scripting.filesystemobject")
Set objTextStream = objFSO.OpenTextFile(fPath, fsoForReading)
rw = 1

Do Until objTextStream.AtEndOfStream
    txt = objTextStream.Readline

    f1 = Trim(Left(txt, F_LEN_A))
    start = F_LEN_A + 1
    f2 = Trim(Mid(txt, start, F_LEN_B))
    start = start + F_LEN_B + 1
    f3 = Trim(Mid(txt, start, F_LEN_C))
    start = start + F_LEN_C + 1
    f4 = Trim(Mid(txt, start, F_LEN_D))

    With ThisWorkbook.Sheets("data").Cells(rw, 1).Resize(1, 4)
        .NumberFormat = "@" 'format cells as text
        .Value = Array(f1, f2, f3, f4)
    End With
    rw = rw + 1
Loop

objTextStream.Close
End Sub

Body:
In lieu of any confirmation from you, I am going to assume that there actually is unicode characters in your actual data.

Option Explicit

Sub Split_My_Data()
    Dim s As Long, str As String, tmp As Variant, varFieldInfo As Variant

    ReDim tmp(0 To 0)

    With Worksheets("Sheet3")
        str = .Cells(1, 1).Value2
        s = Application.Max(InStrRev(str, Chr(32)), _
                            InStrRev(str, ChrW(8194)))
        Do While CBool(s)
            tmp(UBound(tmp)) = Array(s, 1)
            str = Left(str, s)
            Do While Right(str, 1) = Chr(32) Or Right(str, 1) = ChrW(8194): str = Left(str, Len(str) - 1): Loop
            s = Application.Max(InStrRev(str, Chr(32)), _
                                InStrRev(str, ChrW(8194)))
            ReDim Preserve tmp(LBound(tmp) To UBound(tmp) + 1)
            If Not CBool(s) Then Exit Do
        Loop

        'make the last (first) fieldinfo element
        tmp(UBound(tmp)) = Array(0, 1)

        'make room for the reversed fieldinfo
        ReDim varFieldInfo(LBound(tmp) To UBound(tmp))

        'reverse the fieldinfo array
        For s = UBound(tmp) To LBound(tmp) Step -1
            varFieldInfo(UBound(tmp) - s) = tmp(s)
        Next s

        'run TextToColumns with the new array of arrays for FieldInfo
        .Columns("A:A").TextToColumns Destination:=.Cells(1, "A"), DataType:=xlFixedWidth, FieldInfo:=varFieldInfo

        For s = 1 To .Cells(1, .Columns.Count).End(xlToLeft).Column
            With Intersect(.Columns(s), .UsedRange).Cells
                'get rid of unicode
                .Replace what:=ChrW(8194), replacement:=vbNullString, lookat:=xlPart
                'use another texttocolumns as a fast Trim
                .TextToColumns Destination:=.Cells(1, "A"), DataType:=xlFixedWidth, FieldInfo:=Array(Array(0, 1))
                'shrink/expand the column
                .EntireColumn.AutoFit
                .EntireColumn.ColumnWidth = Application.Max(.ColumnWidth, 9)
            End With
        Next s
    End With
End Sub

Results with text as trimmed text and numbers as real numbers (no unicode):


问:
Change react-native-router-flux scene using a variable
I am using react-native-router-flux for the navigation in my react-native mobile app.

I want to call Actions.sceneKey() from drawer using a variable sceneKey which will be based on the store state.
Let's say, there are 3 menus in drawer:

menu1

menu2

menu3

I just want to call Actions.{{ selectedMenu }}, is this somehow possible?

答:
You can use bracket notation, see property accessors.
Here is a example of how you can use it:

```<code>const selectedMenu = 'menu1'; //menus values coming from your store
Actions[selectedMenu]();
</code>```

Make sure the variable is of type string and matches one of your defined routes.

Body:
You can use bracket notation, see property accessors.
Here is a example of how you can use it:

const selectedMenu = 'menu1'; //menus values coming from your store
Actions[selectedMenu]();

Make sure the variable is of type string and matches one of your defined routes.


问:
How do I set the packet size (in bytes) when I ping host from another?
I've tried my best to look around www.mininet.org and other walkthroughs and simply can't seem to find the general format syntax for the 'ping' command. The command :

h1 ping h2

pings between the hosts h1 and h2 with a 64 byte echo packet. How can I change this parameter (packet size)? I would like to experiment with packets of varying sizes, such as 40 bytes, 1000 bytes and so on. I'm guessing there must be an upper limit on this, but not sure what it is.

I've tried using the command

h1 ping -l 40 h2

but this is incorrect syntax as per mininet.

答:
Any available Linux command or program can be run on any virtual host.
Check manual page of ping.

try:mininet> h1 ping -c count -s packetsize h2

```<code>-s packetsize
</code>```

Specifies  the  number of data bytes to be sent.

```<code> -c count
</code>```

Stop after sending count  ECHO_REQUEST  packets.  With  deadline option, ping waits for count ECHO_REPLY packets, until the time‐out expires.

Body:
Any available Linux command or program can be run on any virtual host.
Check manual page of ping.

try:mininet> h1 ping -c count -s packetsize h2

-s packetsize

Specifies  the  number of data bytes to be sent.

 -c count

Stop after sending count  ECHO_REQUEST  packets.  With  deadline option, ping waits for count ECHO_REPLY packets, until the time‐out expires.


问:
NetSuite Advanced PDF / HTML error: "Parse exception during template merging. Unexpected end of file reached."
I have created a complex Advanced PDF / HTML Template using freemarker. When I make no changes and attempt to save the template, the template saves with no errors. When I add a new field to the template through the UI or even simple HTML "Test" and then try to save, I get the following error:

"Parse exception during template merging.
  com.netledger.templates.TemplateServiceException: Parse exception
  during template merging. freemarker.core.ParseException: Unexpected
  end of file reached."

If I proceed and save anyway, the printed PDF gives the same error and displays:
 "The template stored was invalid". What does this error mean and how can I resolve it?

答:
It means that you have some FreeMarker construct in the template that weren't closed. Like, and ${ without the matching }, or an <#if ...> without the matching </#if>.

BTW, usually the error message also tells what wasn't closed. Perhaps you are using an old FreeMarker version where error message quality was lower. You may try to copy-paste the template into http://freemarker-online.kenshoo.com/ to see what a more recent version says.

ContentLicense: CC BY-SA 4.0


问:
Cannot read property 'handleClick' of undefined when using map
I am trying to make a table row function like a Link with react-router.

I keep getting the error Cannot read property 'handleClick' of undefined

```<code>handleClick(user) {
   this.router.transitionTo('index', user);
}

render(){
   var userNodes = this.props.posts.map(function(user, i){
       return (
         <tr onClick={() => this.handleClick(user)}>
           <Td>{user.postId}</Td>
           <Td>{user.title}</Td>
           <Td>{user.body}</Td>
         </tr>
       )
   });
...
</code>```

答:
Its a binding issue, you need to bind the context otherwise this will not point to the react component. Either use .bind(this) with function or use arrow function to avoid this kind of problem. Use this:

```<code>render(){
   var userNodes = this.props.posts.map(function(user, i){
       return (
         <tr onClick={() => this.handleClick(user)}>
           <Td>{user.postId}</Td>
           <Td>{user.title}</Td>
           <Td>{user.body}</Td>
         </tr>
       )
   }.bind(this));
</code>```

Or this:

```<code>render(){
   var userNodes = this.props.posts.map((user, i) => {
       return (
         <tr onClick={() => this.handleClick(user)}>
           <Td>{user.postId}</Td>
           <Td>{user.title}</Td>
           <Td>{user.body}</Td>
         </tr>
       )
   });
</code>```

Check the working example:

class App extends React.Component{

  handleClick(user){
    console.log(user);
  }

  render(){
   var data = [0,1,2,3,4].map((user, i) => {
       return (

 this.handleClick(user)}>
           {user}
           {user}
           {user}

       )
   });

   return(

            A
            B
            C

            {data}

   )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/></code>```

Body:
I am trying to make a table row function like a Link with react-router.

I keep getting the error Cannot read property 'handleClick' of undefined

handleClick(user) {
   this.router.transitionTo('index', user);
}

render(){
   var userNodes = this.props.posts.map(function(user, i){
       return (

 this.handleClick(user)}>
           {user.postId}
           {user.title}
           {user.body}

       )
   });
...

Body:
Its a binding issue, you need to bind the context otherwise this will not point to the react component. Either use .bind(this) with function or use arrow function to avoid this kind of problem. Use this:

render(){
   var userNodes = this.props.posts.map(function(user, i){
       return (
         <tr onClick={() => this.handleClick(user)}>
           <Td>{user.postId}</Td>
           <Td>{user.title}</Td>
           <Td>{user.body}</Td>
         </tr>
       )
   }.bind(this));

Or this:

render(){
   var userNodes = this.props.posts.map((user, i) => {
       return (
         <tr onClick={() => this.handleClick(user)}>
           <Td>{user.postId}</Td>
           <Td>{user.title}</Td>
           <Td>{user.body}</Td>
         </tr>
       )
   });

Check the working example:

class App extends React.Component{

  handleClick(user){
    console.log(user);
  }

  render(){
   var data = [0,1,2,3,4].map((user, i) => {
       return (
         <tr onClick={() => this.handleClick(user)}>
           <td>{user}</td>
           <td>{user}</td>
           <td>{user}</td>
         </tr>
       )
   });

   return(
      <table>
         <thead>
            <th>A</th>
            <th>B</th>
            <th>C</th>
         </thead>
         <tbody>
            {data}
         </tbody>
      </table>
   )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>


问:
PHP: Is it better to concatenate on 1 line or multiple lines? Or is there a difference?
Is there a difference or is one better than the other of the following:

```<code>$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';
</code>```

Or

```<code>$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';
</code>```

Is there a speed difference or is there a reason why you'd pick one over the other?

答:
It doesn't matter for a few, short, strings. Use whatever is clearer to read.

But if you have lots of them (say thousands) not so short ones, you'll probably want to keep them in an array and join them together. (As it happens such code is often as easy to read as concatenating the strings using ".=", so you're not sacrificing clarity on the altar of performance.)

EDIT: I don't think my above thinking is valid. PHP's strings are mutable, right?

OwnerDisplayName: Darryl Hein

ContentLicense: CC BY-SA 2.5

Body:
Is there a difference or is one better than the other of the following:

$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';

Or

$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';

Is there a speed difference or is there a reason why you'd pick one over the other?

LastEditorDisplayName: Paul Dixon

OwnerDisplayName: PEZ

LastEditorDisplayName: PEZ


问:
Best practice for securing sensitive data in plain text file?
Currently I am working on a C linux daemon that takes user input for an SQL connection string, then stores the information into a local conf file (client side). The purpose of the daemon is to submit data to an SQL database at a set interval in that every time the daemon is loaded it will look to the local conf for the SQL connection string. Also by using the command line argument -c, the user can reconfigure the SQL connection string in the event that the information changes. Would anyone be willing to share a way of securing this conf file so that it is not plain text. Keep in mind that I still need to be able to access and read in from the conf file as there is other conf settings present. Thanks in advance guys.

Edit: I do eventually plan to use SSL to submit the data between the client side and the SQL server.

答: If you have no place to keep your secrets, cryptography will not help you. If your daemon is somehow able to decode password not using any secret, then anyone can do this too. So you have to rely on system protection, such as file access mode flags to keep keys.</p>


问:
MySQL: Incorrect data type returns default row
I have this statement:

```<code>SELECT * FROM pffusers where uGoogleSecret=?;
</code>```

uGoogleSecret is a BIGINT.  If I do:

```<code>SELECT * FROM pffusers where uGoogleSecret=00000000000000000;
</code>```

this is not in the database and correctly returns 0 records. However, if I do:

```<code>SELECT * FROM pffusers where uGoogleSecret='hi';
</code>```

this is also not in the database, yet it returns the first row in the table.  I want it to return 0 records.

Thanks!

答: Data type mismatch was converting string to 0 in mysql. 0 was my test uGoogleSecret .

Body:
I have this statement:

SELECT * FROM pffusers where uGoogleSecret=?;

uGoogleSecret is a BIGINT.  If I do:

SELECT * FROM pffusers where uGoogleSecret=00000000000000000;

this is not in the database and correctly returns 0 records. However, if I do:

SELECT * FROM pffusers where uGoogleSecret='hi';

this is also not in the database, yet it returns the first row in the table.  I want it to return 0 records.

Thanks!


问:
Stream the output from SSHJ or JScH
I went through the Java APIs like SSHJ and JScH for executing commands over a remote machine. I explored Java Expect API's like ExpectIt and Expect4j. But I could not find a way to stream the output line by line from the machine to my java process. Let say I am doing a grep on a huge file in my remote machine and I want to stream the huge output, line by line , to my process instead of waiting for the whole command to complete. Is it possible ? if so , how to do it ?</p>

答:
I hope we can do this once you set the output stream to a file.
In the below code my output stream is directed to "outs.txt" file in your system. While it is filling you can create a new thread start processing the contents of file. Below snippet shows how to set output stream can be set.
After this code snippet you have to start a thread in order to process the output from "outs.txt" file. Happy Coding!!!</p>

```<code>                    ss=new StringBuilder("grep aa.txt");
                    ss.append("\n");
                    FileWriter fw = new FileWriter("comm.txt");
                    BufferedWriter bw = new BufferedWriter(fw);
                    bw.write(ss.toString());
                    bw.flush();
                    fw.close();
                    bw.close();
                    InputStream is=new FileInputStream("comm.txt");
                    OutputStream os=new FileOutputStream("outs.txt");
                    channel.setInputStream(is);
                    channel.setOutputStream(os);
                    Thread.sleep(1000);
                    channel.connect();
</code>```

Title: Stream the output from SSHJ or JScH

Body:
I hope we can do this once you set the output stream to a file.
In the below code my output stream is directed to "outs.txt" file in your system. While it is filling you can create a new thread start processing the contents of file. Below snippet shows how to set output stream can be set.
After this code snippet you have to start a thread in order to process the output from "outs.txt" file. Happy Coding!!!

                    ss=new StringBuilder("grep aa.txt");
                    ss.append("\n");
                    FileWriter fw = new FileWriter("comm.txt");
                    BufferedWriter bw = new BufferedWriter(fw);
                    bw.write(ss.toString());
                    bw.flush();
                    fw.close();
                    bw.close();
                    InputStream is=new FileInputStream("comm.txt");
                    OutputStream os=new FileOutputStream("outs.txt");
                    channel.setInputStream(is);
                    channel.setOutputStream(os);
                    Thread.sleep(1000);
                    channel.connect();


问:
How to set form action to open new window with certain size?
So I use code like:

```<code><form action="file.php" method="post" target="foo" onSubmit="window.open('', 'foo', 'width=450,height=300,status=yes,resizable=yes,scrollbars=yes')">
</code>```

But it probubly will not work if user has JS disabeld. So how to set new window Width and height not using JS?

I know we can use  target="_blank" to open what I need in new window but size... I just cant find how to do such thing...

答:
There's not a non-JavaScript way available to to this.

There's just not another way available to ensure a certain size.  The target to target a certain window is all you have available, but you can't size it like window.open() can.

Body:
So I use code like:

<form action="file.php" method="post" target="foo" onSubmit="window.open('', 'foo', 'width=450,height=300,status=yes,resizable=yes,scrollbars=yes')">

But it probubly will not work if user has JS disabeld. So how to set new window Width and height not using JS?

I know we can use  target="_blank" to open what I need in new window but size... I just cant find how to do such thing...


问:
Database connection script works in PHP 5.3 but not in 5.5
I have developed a web based member management tool for my sailing club few years ago and used some free script (a class) that handles database connection and operations on database. The class (connection.php) is invoked by the following code in a required file "settings.php":

```<code>$db = new db ( DBUSER, DBPASS, DATABASE, HOSTNAME );
</code>```

and then is used throughout the site for handling database related requests. It is working fine in PHP 5.3 but due to some security concerns the site has to be upgraded to min 5.4. Unfortunately the script in PHP 5.4 fails to connect to database. I will include the script below (for brevity I show only couple of functions in the class that should give the idea):

```<code>// ==================================================================
//  The Main Class

class db {

    // ==================================================================
    //  DB Constructor - connects to the server and selects a database

    function db($dbuser, $dbpassword, $dbname, $dbhost)
    {

        $this->dbh = @mysql_connect($dbhost,$dbuser,$dbpassword);

        if ( ! $this->dbh )
        {
            $this->print_error("<ol><b>Error establishing a database connection!</b><li>Are you sure you have the correct user/password?<li>Are you sure that you have typed the correct hostname?<li>Are you sure that the database server is running?</ol>");
        }

        $this->select($dbname);

    }

    // ==================================================================
    //  Select a DB (if another one needs to be selected)

    function select($db)
    {
        if ( !@mysql_select_db($db,$this->dbh))
        {
            $this->print_error("<ol><b>Error selecting database <u>$db</u>!</b><li>Are you sure it exists?<li>Are you sure there is a valid database connection?</ol>");
        }
    }
</code>```

When trying to display a page in PHP 5.4 I get the following output:

dbh = @mysql_connect($dbhost,$dbuser,$dbpassword); if ( ! $this->dbh ) { $this->print_error("
  Error establishing a database connection!
  Are you sure you have the correct user/password?
  Are you sure that you have typed the correct hostname?
  Are you sure that the database server is running?
  "); } $this->select($dbname); } // ================================================================== //    Select a DB (if another one needs to be selected) function select($db) { if ( !@mysql_select_db($db,$this->dbh)) { $this->print_error("
  Error selecting database $db!
  Are you sure it exists?he rest of the pages
  Are you sure there is a valid database connection?

My aim is to rewrite the class db without touching the rest of the pages.
I was trying to use mysqli instead of mysql but that made no difference. I'm using mainly procedural php in my programming and am not to good with object oriented.

My question is: what approach should I take to solve my problem. Could you put me in some direction...

答:
@Qchmqs Jan 8 at 7:28

you should be using PDO anyway

No!

You should be using PDO OR MySQLi

Balance please! there are plenty of well learned folk who advocate MySQLi for some situations, its a matter of judgement etc.

Body:
I have developed a web based member management tool for my sailing club few years ago and used some free script (a class) that handles database connection and operations on database. The class (connection.php) is invoked by the following code in a required file "settings.php":

$db = new db ( DBUSER, DBPASS, DATABASE, HOSTNAME );

and then is used throughout the site for handling database related requests. It is working fine in PHP 5.3 but due to some security concerns the site has to be upgraded to min 5.4. Unfortunately the script in PHP 5.4 fails to connect to database. I will include the script below (for brevity I show only couple of functions in the class that should give the idea):

// ==================================================================
//  The Main Class

class db {

    // ==================================================================
    //  DB Constructor - connects to the server and selects a database

    function db($dbuser, $dbpassword, $dbname, $dbhost)
    {

        $this->dbh = @mysql_connect($dbhost,$dbuser,$dbpassword);

        if ( ! $this->dbh )
        {
            $this->print_error("
Error establishing a database connection!
Are you sure you have the correct user/password?
Are you sure that you have typed the correct hostname?
Are you sure that the database server is running?
");
        }

        $this->select($dbname);

    }

    // ==================================================================
    //  Select a DB (if another one needs to be selected)

    function select($db)
    {
        if ( !@mysql_select_db($db,$this->dbh))
        {
            $this->print_error("
Error selecting database $db!
Are you sure it exists?
Are you sure there is a valid database connection?
");
        }
    }

When trying to display a page in PHP 5.4 I get the following output:

dbh = @mysql_connect($dbhost,$dbuser,$dbpassword); if ( ! $this->dbh ) { $this->print_error("
  Error establishing a database connection!
  Are you sure you have the correct user/password?
  Are you sure that you have typed the correct hostname?
  Are you sure that the database server is running?
  "); } $this->select($dbname); } // ================================================================== //    Select a DB (if another one needs to be selected) function select($db) { if ( !@mysql_select_db($db,$this->dbh)) { $this->print_error("
  Error selecting database $db!
  Are you sure it exists?he rest of the pages
  Are you sure there is a valid database connection?

My aim is to rewrite the class db without touching the rest of the pages.
I was trying to use mysqli instead of mysql but that made no difference. I'm using mainly procedural php in my programming and am not to good with object oriented.

My question is: what approach should I take to solve my problem. Could you put me in some direction...


问:
How to format stacktrace in log4j2?
By default log4j2 prints stacktrace on multiple lines, separated by newline characters. Something like:

```<code>java.lang.NullPointerException: error enovountered
    at ...
    at ...
    at ...
</code>```

I want my stacktrace on a single line, something like, essentially using | as a delimiter rather than \n

```<code>java.lang.NullPointerException: error enovountered at ... | at ... | at ...
</code>```

How will I accomplish something like this in log4j2?

答:
As the PatternLayout documentation specifies, the %throwable family of conversion keys actually support being able to change the separator used for individual stack trace elements, as well as the "cause" exceptions.

Given a pattern like:

```<code>[%threadName] %-5level %logger{36} - %message{nolookups}%xThrowable{separator(|)}%n
</code>```

You'll get output like:

```<code>[main] ERROR my.cool.Application - Catching java.lang.RuntimeException: I'm wrapping the NPE|   at my.cool.Application.main(Application.java:24) [main/:?]|Caused by: java.lang.NullPointerException: This is a forced NPE| at java.util.Objects.requireNonNull(Objects.java:228) ~[?:1.8.0_121]|   at my.cool.Application.main(Application.java:21) ~[main/:?]
</code>```

Title: How to format stacktrace in log4j2?

Body:
By default log4j2 prints stacktrace on multiple lines, separated by newline characters. Something like:

java.lang.NullPointerException: error enovountered
    at ...
    at ...
    at ...

I want my stacktrace on a single line, something like, essentially using | as a delimiter rather than \n

java.lang.NullPointerException: error enovountered at ... | at ... | at ...

How will I accomplish something like this in log4j2?

Body:
As the PatternLayout documentation specifies, the %throwable family of conversion keys actually support being able to change the separator used for individual stack trace elements, as well as the "cause" exceptions.

Given a pattern like:

[%threadName] %-5level %logger{36} - %message{nolookups}%xThrowable{separator(|)}%n

You'll get output like:

[main] ERROR my.cool.Application - Catching java.lang.RuntimeException: I'm wrapping the NPE|   at my.cool.Application.main(Application.java:24) [main/:?]|Caused by: java.lang.NullPointerException: This is a forced NPE| at java.util.Objects.requireNonNull(Objects.java:228) ~[?:1.8.0_121]|   at my.cool.Application.main(Application.java:21) ~[main/:?]


问:
Is this the correct way to gitignore files?
I'm doing an interactive rebase and trying to remove all bin and obj folders from my history. The folder structure of my repo is like

```<code>MyRepo
    MyClass
        .
        .
        bin
        obj
        .
    MyTestClass
        .
        .
        bin
        obj
        .
    .
    .
    .
</code>```

I amended my first commit and added a .gitignore with contents

```<code>/MyClass/bin
/MyClass/obj
/MyTestClass/bin
/MyTestClass/obj
</code>```

and put it in MyRepo.

However, when I go to commit I still see the files I don't want are there (.exe, .pbd, etc.)

答:
The best way to ignore files is using http://gitignore.io
The second is to understand that all the patterns that you put inside are to ignore files that are not committed (not tracked). Once that's done by error, git rm --cached is your friend.

Body:
I'm doing an interactive rebase and trying to remove all bin and obj folders from my history. The folder structure of my repo is like

MyRepo
    MyClass
        .
        .
        bin
        obj
        .
    MyTestClass
        .
        .
        bin
        obj
        .
    .
    .
    .

I amended my first commit and added a .gitignore with contents

/MyClass/bin
/MyClass/obj
/MyTestClass/bin
/MyTestClass/obj

and put it in MyRepo.

However, when I go to commit I still see the files I don't want are there (.exe, .pbd, etc.)


问:
Race timing - Find position on person
I have an excel that I am using to record the times of an Aquathlon. My sheet is as follows:

Excel sheet showing rows and columns

I have worked out how to calculate the competitors overall time and position. But now I need to also have their rank for the various categories. These being:

First Overall male
First Overall female
First U18 male
First U18 female

And so on...

答:
You can use the formula something similar to the below

```<code>=IF(E1="Male",SUMPRODUCT(($E$1:$E$9="Male")*($K$1:$K$9>K1))+1,"")
</code>```

($K$1:$K$9>K1) part has to ($K$1:$K$9 < K1) if you want to rank in descending order.

The above formula is based on over all positions found in column K. Also, this formula filters based on the category found in column E. If you want any other category, you may need to customize this formula accordingly by changing the column references.

Title: Race timing - Find position on person

Body:
You can use the formula something similar to the below

=IF(E1="Male",SUMPRODUCT(($E$1:$E$9="Male")*($K$1:$K$9>K1))+1,"")

($K$1:$K$9>K1) part has to ($K$1:$K$9 < K1) if you want to rank in descending order.

The above formula is based on over all positions found in column K. Also, this formula filters based on the category found in column E. If you want any other category, you may need to customize this formula accordingly by changing the column references.


问:
Javascript User Input
I'm trying to create this script where the user can only select one option from category 1, one option from category 2, and the click submit to generate a link.
What would be the best approach if I wanted this to live online and all be done client-side without the need for a server?
<img src="https://i.stack.imgur.com/mU2aB.jpg" alt=""> </p>

答:
Use radio buttons

```<code><form>
    <fieldset id="group1">
        <input type="radio" value="" name="group1">
        <input type="radio" value="" name="group1">
    </fieldset>

    <fieldset id="group2">
        <input type="radio" value="" name="group2">
        <input type="radio" value="" name="group2">
        <input type="radio" value="" name="group2">
    </fieldset>
</form>
</code>```

This answer is from here  Multiple radio button groups in one form

If you edit the code a bit you get (You use value1 and value2 as strings for the link)

```<code>    <form>
        <fieldset id="group1" style="float:left;">
            <input type="radio" value="" name="group1">
            <input type="radio" value="" name="group1">
        </fieldset>

        <fieldset id="group2" style="float:right;left:100px;">
            <input type="radio" value="" name="group2">
            <input type="radio" value="" name="group2">
            <input type="radio" value="" name="group2">
        </fieldset>
       <button onclick="myFunction();">Submit</button>
    </form>

<script>
function myFunction() {
value1 =document.getElementById('group1').value ;
value2 =document.getElementById('group2').value ;
}
</script>
</code>```

Title: Javascript User Input

Body:
Use radio buttons

<form>
    <fieldset id="group1">
        <input type="radio" value="" name="group1">
        <input type="radio" value="" name="group1">
    </fieldset>

    <fieldset id="group2">
        <input type="radio" value="" name="group2">
        <input type="radio" value="" name="group2">
        <input type="radio" value="" name="group2">
    </fieldset>
</form>

This answer is from here  Multiple radio button groups in one form

If you edit the code a bit you get (You use value1 and value2 as strings for the link)

    <form>
        <fieldset id="group1" style="float:left;">
            <input type="radio" value="" name="group1">
            <input type="radio" value="" name="group1">
        </fieldset>

        <fieldset id="group2" style="float:right;left:100px;">
            <input type="radio" value="" name="group2">
            <input type="radio" value="" name="group2">
            <input type="radio" value="" name="group2">
        </fieldset>
       <button onclick="myFunction();">Submit</button>
    </form>

<script>
function myFunction() {
value1 =document.getElementById('group1').value ;
value2 =document.getElementById('group2').value ;
}
</script>


问:
failed to resolve com.android.support:support-v7:25.2.0
```<code>    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:support-v7:25.2.0'
compile 'com.android.support:design:25.1.1'
</code>```

}

failed to resolve com.android.support:support-v7:25.2.0

Am trying but cant find the solution please help me

答:
If you are trying to get the support repository, this is the correct import:

```<code>compile "com.android.support:support-v4:25.3.1"
</code>```

If your compile api isn't 25, change the version to the latest with your compile api

If it isn't any of these you have to add some context: What is it intent of the import? What do you need it for?

Side note

I [believe] the repository you are trying to get is the support repository. The support repository is v4, not v7.

Body:
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:support-v7:25.2.0'
compile 'com.android.support:design:25.1.1'

}

failed to resolve com.android.support:support-v7:25.2.0

Am trying but cant find the solution please help me

Body:
If you are trying to get the support repository, this is the correct import:

compile "com.android.support:support-v4:25.3.1"

If your compile api isn't 25, change the version to the latest with your compile api

If it isn't any of these you have to add some context: What is it intent of the import? What do you need it for?

Side note

I [believe] the repository you are trying to get is the support repository. The support repository is v4, not v7.


问:
Pygame Pacman ghost, random change direction
I am creating a pacman game, so far everything works aside from the ghosts, when a ghost collides against a wall the class bellow is called. However as you can see self.a returns a str, but I need it to be applied to my ghost sprites, Ghost1,Ghost2, etc. So it calls, Ghost1.a and the ghost moves accordingly.

Any help would be appreciated, thank you.

```<code>class Ghost_move(object):
    def __init__(self,g_speed):
        super(Ghost_move, self).__init__()
        self.left=".rect.x-=g_speed"
        self.right=".rect.x+=g_speed"
        self.up=".rect.y-=g_speed"
        self.down=".rect.y+=g_speed"
        self.direction=self.left,self.right,self.up,self.down
        self.a=random.choice(self.direction)
</code>```

答:
As abccd already pointed out, it is a bad idea to put source code, that you want to be executed into strings. The solution that is nearest to yours is defining functions for left, right, up, down. Then you can store those functions in directions and execute a randomly chosen one:

```<code>class Ghost_move(object):
    def __init__(self,g_speed):
        super(Ghost_move, self).__init__()
        self.g_speed = g_speed
        self.directions = self.left, self.right, self.up, self.down
        self.a = random.choice(self.directions)
    def left(self):
        self.rect.x -= self.g_speed
    def right(self):
        self.rect.x += self.g_speed
    def up(self):
        self.rect.y -= self.g_speed
    def down(self):
        self.rect.y += self.g_speed
</code>```

Now self.a is a function that you can call. For example ghost1.a() would move ghost1 randomly in one of the four directions. But be careful, because a is just set once and therefore ghost1.a() always moves this ghost in the same direction and does not choose a random direction everytime you call it.

A different approach is to do it with vectors:

```<code>class Ghost_move(object):
    def __init__(self,g_speed):
        super(Ghost_move, self).__init__()
        self.left = (-g_speed, 0)
        self.right = (g_speed, 0)
        self.up = (0, -g_speed)
        self.down = (0, g_speed)
        self.directions = self.left, self.right, self.up, self.down
        self.random_dir = random.choice(self.directions)
    def a():
        self.rect.x += self.random_dir[0]
        self.rect.y += self.random_dir[1]
</code>```

The usage is the same as before, you would just call a() on a ghost.

Body:
I am creating a pacman game, so far everything works aside from the ghosts, when a ghost collides against a wall the class bellow is called. However as you can see self.a returns a str, but I need it to be applied to my ghost sprites, Ghost1,Ghost2, etc. So it calls, Ghost1.a and the ghost moves accordingly.

Any help would be appreciated, thank you.

class Ghost_move(object):
    def __init__(self,g_speed):
        super(Ghost_move, self).__init__()
        self.left=".rect.x-=g_speed"
        self.right=".rect.x+=g_speed"
        self.up=".rect.y-=g_speed"
        self.down=".rect.y+=g_speed"
        self.direction=self.left,self.right,self.up,self.down
        self.a=random.choice(self.direction)

Body:
As abccd already pointed out, it is a bad idea to put source code, that you want to be executed into strings. The solution that is nearest to yours is defining functions for left, right, up, down. Then you can store those functions in directions and execute a randomly chosen one:

class Ghost_move(object):
    def __init__(self,g_speed):
        super(Ghost_move, self).__init__()
        self.g_speed = g_speed
        self.directions = self.left, self.right, self.up, self.down
        self.a = random.choice(self.directions)
    def left(self):
        self.rect.x -= self.g_speed
    def right(self):
        self.rect.x += self.g_speed
    def up(self):
        self.rect.y -= self.g_speed
    def down(self):
        self.rect.y += self.g_speed

Now self.a is a function that you can call. For example ghost1.a() would move ghost1 randomly in one of the four directions. But be careful, because a is just set once and therefore ghost1.a() always moves this ghost in the same direction and does not choose a random direction everytime you call it.

A different approach is to do it with vectors:

class Ghost_move(object):
    def __init__(self,g_speed):
        super(Ghost_move, self).__init__()
        self.left = (-g_speed, 0)
        self.right = (g_speed, 0)
        self.up = (0, -g_speed)
        self.down = (0, g_speed)
        self.directions = self.left, self.right, self.up, self.down
        self.random_dir = random.choice(self.directions)
    def a():
        self.rect.x += self.random_dir[0]
        self.rect.y += self.random_dir[1]

The usage is the same as before, you would just call a() on a ghost.


问:
Computer Vision API for javascript not working[Beginner's error]
I am new to Microsoft Cognitive services and this problem seems to have an easy fix but it has spoiled my two days. I have just copied the Computer vision for javascript code and replaced my the subscription key with mine and opened the .html file in my browser it says error.

DO I have to add something in the code

Also, I have nowt provided any image in this code what's he doing without an image?

The script code is here

```<code><!DOCTYPE html>
<html>
<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
    $(function() {
        var params = {
            // Request parameters
            "visualFeatures": "Categories",
            "details": "{string}",
            "language": "en",
        };

        $.ajax({
            url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{6e07223403d94848be20af6f126fsssd}");
            },
            type: "POST",
            // Request body
            data: "{body}",
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function() {
            alert("error");
        });
    });
</script>
</body>
</html>
</code>```

code and preview of error

答:
While it's not very obvious, in any code snippet from the Cognitive Service API reference page such as this one that I suspect you were using, you must provide a value (or remove) wherever it shows {something}.  Here's code with suitable values:

```<code><!DOCTYPE html>
<html>
<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
    var myKey = "6e07223403d94848be20af6f126fsssd";
    var myBody = {url:"http://www.gannett-cdn.com/-mm-/2d2a8e29485ced74b7537554043aeae2e0bba202/c=0-104-5177-3029&r=x1683&c=3200x1680/local/-/media/2015/07/18/USATODAY/USATODAY/635728260394906410-AP-GOP-Trump-2016.jpg"}
    $(function() {
        var params = {
            // Request parameters
            "visualFeatures": "Categories",
            "language": "en",
        };

        $.ajax({
            url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", myKey);
            },
            type: "POST",
            // Request body
            data: JSON.stringify(myBody),
        })
        .done(function(data) {
            alert("success");
            debugger;
        })
        .fail(function() {
            alert("error");
        });
    });
</script>
</body>
</html>
</code>```

Body:
I am new to Microsoft Cognitive services and this problem seems to have an easy fix but it has spoiled my two days. I have just copied the Computer vision for javascript code and replaced my the subscription key with mine and opened the .html file in my browser it says error.

DO I have to add something in the code

Also, I have nowt provided any image in this code what's he doing without an image?

The script code is here

<!DOCTYPE html>

    <title>JSSample</title>

code and preview of error

Body:
While it's not very obvious, in any code snippet from the Cognitive Service API reference page such as this one that I suspect you were using, you must provide a value (or remove) wherever it shows {something}.  Here's code with suitable values:

<!DOCTYPE html>
<html>
<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
    var myKey = "6e07223403d94848be20af6f126fsssd";
    var myBody = {url:"http://www.gannett-cdn.com/-mm-/2d2a8e29485ced74b7537554043aeae2e0bba202/c=0-104-5177-3029&r=x1683&c=3200x1680/local/-/media/2015/07/18/USATODAY/USATODAY/635728260394906410-AP-GOP-Trump-2016.jpg"}
    $(function() {
        var params = {
            // Request parameters
            "visualFeatures": "Categories",
            "language": "en",
        };

        $.ajax({
            url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", myKey);
            },
            type: "POST",
            // Request body
            data: JSON.stringify(myBody),
        })
        .done(function(data) {
            alert("success");
            debugger;
        })
        .fail(function() {
            alert("error");
        });
    });
</script>
</body>
</html>


问:
Underscores _.clone() does not work with Parse JS SDK compound queries
I'm having trouble getting this to work in Parse Server v2.3.7 (which includes Parse JS SDK v1.9.2) with sorting a compound query. I can use ascending/descending query methods in the original query, but when I clone it they no longer work. Any ideas why this isn't working or is there a better approach to cloning the query?

```<code>var firstQuery = new Parse.Query('Object');
firstQuery.equalTo('property', 1);
var secondQuery = new Parse.Query('Object');
secondQuery.equalTo('property', 2);

var query = Parse.Query.or(firstQuery, secondQuery);
query.descending('updatedAt');
// This works
var clonedQuery = _.clone(query);
clonedQuery.ascending('updatedAt');
// Throws error "clonedQuery.ascending is not a function"
</code>```

Continuing this issue: How can I clone a Parse Query using the Javascript SDK on Parse Cloud Code?

答:
Updated

There is one thing Lodash.js does which Underscore.js doesn't. Lodash.js copy the prototype while Underscore.js sets prototype to undefined. To make it works with Underscore.js, you need to copy the prototype manually:

```<code>var Parse = require('parse').Parse;
var _ = require('underscore');

var firstQuery = new Parse.Query('Object');
firstQuery.equalTo('property', 1);
var secondQuery = new Parse.Query('Object');
secondQuery.equalTo('property', 2);

var query = Parse.Query.or(firstQuery, secondQuery);
query.descending('updatedAt');
// This works
var clonedQuery = _.clone(query);
Object.setPrototypeOf(clonedQuery, Object.getPrototypeOf(query)); // This line is very important!
clonedQuery.ascending('updatedAt');
// This works too
</code>```

Body:
I'm having trouble getting this to work in Parse Server v2.3.7 (which includes Parse JS SDK v1.9.2) with sorting a compound query. I can use ascending/descending query methods in the original query, but when I clone it they no longer work. Any ideas why this isn't working or is there a better approach to cloning the query?

var firstQuery = new Parse.Query('Object');
firstQuery.equalTo('property', 1);
var secondQuery = new Parse.Query('Object');
secondQuery.equalTo('property', 2);

var query = Parse.Query.or(firstQuery, secondQuery);
query.descending('updatedAt');
// This works
var clonedQuery = _.clone(query);
clonedQuery.ascending('updatedAt');
// Throws error "clonedQuery.ascending is not a function"

Continuing this issue: How can I clone a Parse Query using the Javascript SDK on Parse Cloud Code?

Body:
Updated

There is one thing Lodash.js does which Underscore.js doesn't. Lodash.js copy the prototype while Underscore.js sets prototype to undefined. To make it works with Underscore.js, you need to copy the prototype manually:

var Parse = require('parse').Parse;
var _ = require('underscore');

var firstQuery = new Parse.Query('Object');
firstQuery.equalTo('property', 1);
var secondQuery = new Parse.Query('Object');
secondQuery.equalTo('property', 2);

var query = Parse.Query.or(firstQuery, secondQuery);
query.descending('updatedAt');
// This works
var clonedQuery = _.clone(query);
Object.setPrototypeOf(clonedQuery, Object.getPrototypeOf(query)); // This line is very important!
clonedQuery.ascending('updatedAt');
// This works too


问:
How can I stream a zip in a zip stream download?
I want to be able to archive (zip, no compression needed, but that is a plus),

 in memory and stream it, the problem is that I want to create an inner zip in

 the zip I am streaming, like so:

Files:

```<code>a.txt, b.txt, c.txt
</code>```

Stream download should look like:

```<code>my.zip {
  a.txt
  inner.zip {
   b.txt, c.txt
  }
}
</code>```

Notes, I have to stream the files because I have no HD storage available and I can't have all the files in memory either (that is why I am streaming them)

Here Is a normal zip stream I managed to get working (without the inner zip streamed yet):

```<code><?php
require 'ZipStream.php';

$zip = new ZipStream\ZipStream('my.zip');
$zip->addFileFromPath('a.txt', 'a.txt');
// I want to add inner.zip here and stream it too only from memory
$zip->finish();
</code>```

答:
Well, this kind of works. I wanted to post it although I decided to fix the problem in another way. But just for future reference this may be helpful for someone.

```<code><?php
$zip_header_outer = "\x1f\x8b\x08\x08i\xbb\xb9X\x00\xffinner.zip\x00";
$zip_header_inner = "\x1F\x8B\x08\x08\x69\xBB\xB9\x58\x00\xFF";
$compression_level = 0;
$download_headers = true;
$download_file_name = 'my.zip';
$inner_file_name = 'inner.zip';
$first_level_file = 'a.txt';
$second_level_file = 'b.txt';

$fout = fopen("php://output", "wb");
if ($fout === FALSE) {
    die('Problem outputting');
}

if ($download_headers) {
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"" . $download_file_name . "\"");
}

function add_to_inner_zip($filename, $path, &$fout, &$fsize_outer, &$hctx_outer) {
    $zip_header_inner = "\x1F\x8B\x08\x08\x69\xBB\xB9\x58\x00\xFF";

        fwrite($fout, $zip_header_inner);
        hash_update($hctx_outer, $zip_header_inner);
        $fsize_outer += strlen($zip_header_inner);
        $hctx_inner = hash_init("crc32b");
        $fsize_inner = 0;

        // Inner Add file name
        $file_name = str_replace("\0", "", basename($filename));
        $data = $file_name."\0";
        fwrite($fout, $data, 1+strlen($data));
        hash_update($hctx_outer, $data);
        $fsize_outer += strlen($data);

        // Start inner.zip contents
            // Inner Add file data * STREAM CHUNKS HERE *
            $file_data = file_get_contents($path);
            $clen = strlen($file_data);
            hash_update($hctx_inner, $file_data);
            $fsize_inner += $clen;
            /*hash_update($hctx_member, $file_data);
            $fsize_member += $clen;*/

            // Actually encode the chunk and add to the main stream
            $gziped_chunk = zlib_encode($file_data, ZLIB_ENCODING_RAW);
            fwrite($fout, $gziped_chunk);
            hash_update($hctx_outer, $gziped_chunk);
            $fsize_outer += strlen($gziped_chunk);

        // Close the inner zip
    $crc = hash_final($hctx_inner, TRUE);
    $zip_footer = $crc[3].$crc[2].$crc[1].$crc[0] . pack("V", $fsize_inner);
    fwrite($fout, $zip_footer);

    // update outer crc + size
    hash_update($hctx_outer, $zip_footer);
    $fsize_outer += strlen($zip_footer);
}

// Outer
fwrite($fout, $zip_header_outer);
$fltr_outer = stream_filter_append($fout, "zlib.deflate", STREAM_FILTER_WRITE, $compression_level);
$hctx_outer = hash_init("crc32b");
$fsize_outer = 0;

    add_to_inner_zip($first_level_file, $first_level_file, $fout, $fsize_outer, $hctx_outer);

stream_filter_remove($fltr_outer);
$crc = hash_final($hctx_outer, TRUE);
fwrite($fout, $crc[3].$crc[2].$crc[1].$crc[0], 4);
fwrite($fout, pack("V", $fsize_outer), 4);
</code>```

Plus, I know the code sucks, and is hacky - but the situation asked for it :P

Body:
I want to be able to archive (zip, no compression needed, but that is a plus),

 in memory and stream it, the problem is that I want to create an inner zip in

 the zip I am streaming, like so:

Files:

a.txt, b.txt, c.txt

Stream download should look like:

my.zip {
  a.txt
  inner.zip {
   b.txt, c.txt
  }
}

Notes, I have to stream the files because I have no HD storage available and I can't have all the files in memory either (that is why I am streaming them)

Here Is a normal zip stream I managed to get working (without the inner zip streamed yet):

<?php
require 'ZipStream.php';

$zip = new ZipStream\ZipStream('my.zip');
$zip->addFileFromPath('a.txt', 'a.txt');
// I want to add inner.zip here and stream it too only from memory
$zip->finish();

Body:
Well, this kind of works. I wanted to post it although I decided to fix the problem in another way. But just for future reference this may be helpful for someone.

<?php
$zip_header_outer = "\x1f\x8b\x08\x08i\xbb\xb9X\x00\xffinner.zip\x00";
$zip_header_inner = "\x1F\x8B\x08\x08\x69\xBB\xB9\x58\x00\xFF";
$compression_level = 0;
$download_headers = true;
$download_file_name = 'my.zip';
$inner_file_name = 'inner.zip';
$first_level_file = 'a.txt';
$second_level_file = 'b.txt';

$fout = fopen("php://output", "wb");
if ($fout === FALSE) {
    die('Problem outputting');
}

if ($download_headers) {
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"" . $download_file_name . "\"");
}

function add_to_inner_zip($filename, $path, &$fout, &$fsize_outer, &$hctx_outer) {
    $zip_header_inner = "\x1F\x8B\x08\x08\x69\xBB\xB9\x58\x00\xFF";

        fwrite($fout, $zip_header_inner);
        hash_update($hctx_outer, $zip_header_inner);
        $fsize_outer += strlen($zip_header_inner);
        $hctx_inner = hash_init("crc32b");
        $fsize_inner = 0;

        // Inner Add file name
        $file_name = str_replace("\0", "", basename($filename));
        $data = $file_name."\0";
        fwrite($fout, $data, 1+strlen($data));
        hash_update($hctx_outer, $data);
        $fsize_outer += strlen($data);

        // Start inner.zip contents
            // Inner Add file data * STREAM CHUNKS HERE *
            $file_data = file_get_contents($path);
            $clen = strlen($file_data);
            hash_update($hctx_inner, $file_data);
            $fsize_inner += $clen;
            /*hash_update($hctx_member, $file_data);
            $fsize_member += $clen;*/

            // Actually encode the chunk and add to the main stream
            $gziped_chunk = zlib_encode($file_data, ZLIB_ENCODING_RAW);
            fwrite($fout, $gziped_chunk);
            hash_update($hctx_outer, $gziped_chunk);
            $fsize_outer += strlen($gziped_chunk);

        // Close the inner zip
    $crc = hash_final($hctx_inner, TRUE);
    $zip_footer = $crc[3].$crc[2].$crc[1].$crc[0] . pack("V", $fsize_inner);
    fwrite($fout, $zip_footer);

    // update outer crc + size
    hash_update($hctx_outer, $zip_footer);
    $fsize_outer += strlen($zip_footer);
}

// Outer
fwrite($fout, $zip_header_outer);
$fltr_outer = stream_filter_append($fout, "zlib.deflate", STREAM_FILTER_WRITE, $compression_level);
$hctx_outer = hash_init("crc32b");
$fsize_outer = 0;

    add_to_inner_zip($first_level_file, $first_level_file, $fout, $fsize_outer, $hctx_outer);

stream_filter_remove($fltr_outer);
$crc = hash_final($hctx_outer, TRUE);
fwrite($fout, $crc[3].$crc[2].$crc[1].$crc[0], 4);
fwrite($fout, pack("V", $fsize_outer), 4);

Plus, I know the code sucks, and is hacky - but the situation asked for it :P


问:
C# StackOverFlowException when creating new instance of class
Hm i get a strange problem. when i creating new instance of class i get StackOverflowExcepion :)

Here is code:

```<code>public partial class PlayerChooser : Window
{
public PlayerChooser()
    {
        InitializeComponent();
        textBoxPlayer1Name.Visibility = Visibility.Hidden;
        textBoxPlayer2Name.Visibility = Visibility.Hidden;
        textBoxPlayer3Name.Visibility = Visibility.Hidden;
        textBoxPlayer4Name.Visibility = Visibility.Hidden;

    }

    public static String player1Name;
    public static String player2Name;
    public static String player3Name;
    public static String player4Name;
    ...

    PlayerChooser.player1Name = textBoxPlayer1Name.Text;
    PlayerChooser.player2Name = textBoxPlayer2Name.Text;
    TwoPlayers501_new twoPlayers501_new = new TwoPlayers501_new();
    twoPlayers501_new.Show();
    ...
}
</code>```

and class and constructor where exception occurs

```<code>public partial class TwoPlayers501_new : Window
{
    public TwoPlayers501_new()
    {
        InitializeComponent();

        textBlockPlayer1Name.Text = PlayerChooser.player1Name;
        textBlockPlayer2Name.Text = PlayerChooser.player2Name;
    }
    ...
}
</code>```

thanx in advance, it is probably some kind of triviality...

答:
You are recursing on yourself:</p>

```<code>PlayerChooser.player1Name = textBoxPlayer1Name.Text;
PlayerChooser.player2Name = textBoxPlayer2Name.Text;

textBlockPlayer1Name.Text = PlayerChooser.player1Name;
textBlockPlayer2Name.Text = PlayerChooser.player2Name;
</code>```

Body:
Hm i get a strange problem. when i creating new instance of class i get StackOverflowExcepion :)

Here is code:

public partial class PlayerChooser : Window
{
public PlayerChooser()
    {
        InitializeComponent();
        textBoxPlayer1Name.Visibility = Visibility.Hidden;
        textBoxPlayer2Name.Visibility = Visibility.Hidden;
        textBoxPlayer3Name.Visibility = Visibility.Hidden;
        textBoxPlayer4Name.Visibility = Visibility.Hidden;

    }

    public static String player1Name;
    public static String player2Name;
    public static String player3Name;
    public static String player4Name;
    ...

    PlayerChooser.player1Name = textBoxPlayer1Name.Text;
    PlayerChooser.player2Name = textBoxPlayer2Name.Text;
    TwoPlayers501_new twoPlayers501_new = new TwoPlayers501_new();
    twoPlayers501_new.Show();
    ...
}

and class and constructor where exception occurs

public partial class TwoPlayers501_new : Window
{
    public TwoPlayers501_new()
    {
        InitializeComponent();

        textBlockPlayer1Name.Text = PlayerChooser.player1Name;
        textBlockPlayer2Name.Text = PlayerChooser.player2Name;
    }
    ...
}

thanx in advance, it is probably some kind of triviality...

Body:
You are recursing on yourself:

PlayerChooser.player1Name = textBoxPlayer1Name.Text;
PlayerChooser.player2Name = textBoxPlayer2Name.Text;

textBlockPlayer1Name.Text = PlayerChooser.player1Name;
textBlockPlayer2Name.Text = PlayerChooser.player2Name;


问:
grep for a variable excluding the dot sign
I want to grep a variable excluding those that start with a dot sign. However choosing the -w option for entire word doesn't include a dot sign so instead of only selecting 4 55 48 it also selects 0.4 0.55 5.48.

e.g. $var=1565

input

```<code>A 3.00027 1565
B 3.00026 1565
C -1.1565 5000
</code>```

desired output

```<code>A 3.00027 1565
B 3.00026 1565
</code>```

I have seen solutions to grep for an exact pattern starting with grep, but that doesn't work with a variable.

I have tried adding a space sign before the variable as in lines below but it doesn't give desired output either.

```<code>grep -E -w " $var" input.txt > output.txt #results in empty output
grep -E -w "[:space:]|$var" input.txt > output.txt # gives solutions that include the dot sign
</code>```

答:
You could try:</p>

```<code>grep -E "(^|\s)$var(\s|$)"
</code>```

Body:
I want to grep a variable excluding those that start with a dot sign. However choosing the -w option for entire word doesn't include a dot sign so instead of only selecting 4 55 48 it also selects 0.4 0.55 5.48.

e.g. $var=1565

input

A 3.00027 1565
B 3.00026 1565
C -1.1565 5000

desired output

A 3.00027 1565
B 3.00026 1565

I have seen solutions to grep for an exact pattern starting with grep, but that doesn't work with a variable.

I have tried adding a space sign before the variable as in lines below but it doesn't give desired output either.

grep -E -w " $var" input.txt > output.txt #results in empty output
grep -E -w "[:space:]|$var" input.txt > output.txt # gives solutions that include the dot sign

Body:
You could try:

grep -E "(^|\s)$var(\s|$)"


问:
What does 'In [*]' mean in Jupyter notebooks?
What does In [*] at the upper left-hand of the cell mean when running a Jupyter notebook?

I know that when the cell in Jupyter notebook has not been run, it shows as In[ ], after running the cell, it shows as In[num].

What about In [*], does it mean that this cell is running now?

答:
This means that your kernel is busy.
If you want to interrupt/stop the execution, go to the menu Kernel and click Interrupt.If it doesn't work, click Restart.
You need to go in a new cell and press Shift + Enter to see if it worked.</p>


问:
Regex Multiple Lines AHK
I am trying to workout a solution to get a regexmatch to a string that are in between 2 text, I came up with a working solution of

```<code>RegExMatch(clipboard,"STUFF<p class=""figure"">(.*)</p></div><",match)
</code>```

that matches the things from (gave me 2140)

```<code><div><div>STUFF<p class="figure">2140</p></div></div>
</code>```

but this is all in a single line, I have no idea how do I apply this to a code that are multiple line, such as

```<code><tr>
    <td>Qty</td>
    <td>:</td>
    <td>
        310
    </td>
</tr>
</table>
</code>```

I would like to get 310, how should my regex be? I couldn't figure out how, I've tried with \s\s but to no avail. Please help

EDIT

I seem to get a hang of \s* function now, I tried it slowly to see where it omits, as I go on with

```<code><td>Qty</td>\s*<td>(.*?)</td>
</code>```

it gave me :

but I couldn't get it pass the :	 part, it always returns blank, I am wondering if my (.?) should be (.\s?) instead?

I tried

```<code>RegExMatch(clipboard,"<td>Qty</td>\s*<td>(.\s*?)</td>\s*</tr>",match)
</code>```

but to no avail

答:
The basic idea is that you add \s* where ever you think a space might come. It will match zero or space like characters. (like tabs, new lines etc). For example,

\s*
\s*Qty	\s*:	\s*(.*?)	/s*

Title: Regex Multiple Lines AHK

Body:
I am trying to workout a solution to get a regexmatch to a string that are in between 2 text, I came up with a working solution of

RegExMatch(clipboard,"STUFF
(.*)

<",match)

that matches the things from (gave me 2140)

STUFF
2140

but this is all in a single line, I have no idea how do I apply this to a code that are multiple line, such as

    Qty
    :

        310

I would like to get 310, how should my regex be? I couldn't figure out how, I've tried with \s\s but to no avail. Please help

EDIT

I seem to get a hang of \s* function now, I tried it slowly to see where it omits, as I go on with

Qty	\s*(.*?)

it gave me :

but I couldn't get it pass the :	 part, it always returns blank, I am wondering if my (.?) should be (.\s?) instead?

I tried

RegExMatch(clipboard,"Qty	\s*(.\s*?)	\s*
",match)

but to no avail

Body:
The basic idea is that you add \s* where ever you think a space might come. It will match zero or space like characters. (like tabs, new lines etc). For example,

\s*<tr>\s*<td>Qty</td>\s*<td>:</td>\s*<td>(.*?)</td>/s*</tr>


问:
linux : Finding the postgres idle process originator
Actually ,  I am running four daemon program. It makes postgres connection, and it disconnects once through with the stuffs. But When I am putting ps aux , there are lot of postgres idle process being run in my system.  I just want to know , originator of the each idle postres process.  So, that I could find out which process does not close postgres connection properly. </p>

<p>Thanks in  Advance . </p>

答:
If you are using postgresql 9.0, set the "application name" property when you connect so that you can distinguish which client process each server process is talking to. For example (Perl):

```<code>$dbh = DBI->connect("dbi:Pg:application_name=test/$$", undef, undef)
</code>```

This will include the client PID in the application name, which is ugly but effective.

If you are connecting over TCP/IP, then pg_stat_activity includes the client port which you can use with lsof (or netstat -p) to find the client process.

Body:
Actually ,  I am running four daemon program. It makes postgres connection, and it disconnects once through with the stuffs. But When I am putting ps aux , there are lot of postgres idle process being run in my system.  I just want to know , originator of the each idle postres process.  So, that I could find out which process does not close postgres connection properly.

Thanks in  Advance .

Body:
If you are using postgresql 9.0, set the "application name" property when you connect so that you can distinguish which client process each server process is talking to. For example (Perl):

$dbh = DBI->connect("dbi:Pg:application_name=test/$$", undef, undef)

This will include the client PID in the application name, which is ugly but effective.

If you are connecting over TCP/IP, then pg_stat_activity includes the client port which you can use with lsof (or netstat -p) to find the client process.


问:
How to intercept abstract method
Question title is not fully describes meaning of the question but I can't do it within title limitation. If you help me to change it to more convenient I'll be happy.

I have some class hierarchy described below:

AbstractParent :

```<code>public abstract class AbstractParent {

    public void realParentMethod() {
        System.out.println("invoking abstractMethod from realParentMethod");
        abstractMethod();
    }

    public abstract void abstractMethod();

}
</code>```

ChildImpl:

```<code>public class ChildImpl extends AbstractParent {

    public void abstractMethod() {
        System.out.println("abstractMethod implementation is running!");
    }

}
</code>```

I want to intercept every method invocation in this hierarchy and add some functionality. Even if method is invoked from each other I want to intercept each of them every time.

I use cglib Enhancer with MethodInterceptor implementation to do it:

```<code>import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class Main {

public static void main(String[] srgs) {
    AbstractParent parentImpl = new ChildImpl();

    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(AbstractParent.class);
    enhancer.setCallback(new LocalMethodInterceptor(parentImpl));

    AbstractParent proxyImpl = (AbstractParent) enhancer.create();
    // straight calling abstractMethod
    proxyImpl.abstractMethod();
    System.out.println("-----------------");
    // calling realParentMethod will lead to abstractMethod calling
    proxyImpl.realParentMethod();
    }

    static class LocalMethodInterceptor<T> implements MethodInterceptor {

        private T origin;

        public LocalMethodInterceptor(T origin) {
            this.origin = origin;
        }

        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            try {
                System.out.println("intercept method["+method.getName()+"] before execution!");
                return method.invoke(origin, args);
            } finally {
                System.out.println("cleanup after  method["+method.getName()+"] execution!");
            }
        }
    }
}
</code>```

But the problem is that any method is intercepted only once:
If I invoke abstract method - It will be intercepted. But hierarchy was planned so way that you never have to invoke it (abstractMethod). You just invoke realParentMethod and it do all things for you, meaning it invokes abstractMethod from itself.

In this example if you call realParentMethod only realParentMethod will be intercepted, abstract method will be just skipped.

Here are some console output to this example:

```<code>intercept method[abstractMethod] before execution!
abstractMethod implementation is running!
cleanup after  method[abstractMethod] execution!
-----------------
intercept method[realParentMethod] before execution!
invoking abstractMethod from realParentMethod
abstractMethod implementation is running!
cleanup after  method[realParentMethod] execution!
</code>```

答:
This is a consequence of your delegation approach where you invoke the intercepted method on another instance T origin. Cglib creates a proxy where it overriddes any method to implement your MethodInterceptor. The interceptor is therefore only applied when it is invoked directly. One you pass to your origin object, the interceptor is therefore no longer in effect.

If you wanted to intercept any method call, instead of delegating, you would need to use the cglib object as a replacement for your delegation target. You can invoke the original method by invoking it via the MethodProxy instance.

Title: How to intercept abstract method

Body:
Question title is not fully describes meaning of the question but I can't do it within title limitation. If you help me to change it to more convenient I'll be happy.

I have some class hierarchy described below:

AbstractParent :

public abstract class AbstractParent {

    public void realParentMethod() {
        System.out.println("invoking abstractMethod from realParentMethod");
        abstractMethod();
    }

    public abstract void abstractMethod();

}

ChildImpl:

public class ChildImpl extends AbstractParent {

    public void abstractMethod() {
        System.out.println("abstractMethod implementation is running!");
    }

}

I want to intercept every method invocation in this hierarchy and add some functionality. Even if method is invoked from each other I want to intercept each of them every time.

I use cglib Enhancer with MethodInterceptor implementation to do it:

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class Main {

public static void main(String[] srgs) {
    AbstractParent parentImpl = new ChildImpl();

    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(AbstractParent.class);
    enhancer.setCallback(new LocalMethodInterceptor(parentImpl));

    AbstractParent proxyImpl = (AbstractParent) enhancer.create();
    // straight calling abstractMethod
    proxyImpl.abstractMethod();
    System.out.println("-----------------");
    // calling realParentMethod will lead to abstractMethod calling
    proxyImpl.realParentMethod();
    }

    static class LocalMethodInterceptor<T> implements MethodInterceptor {

        private T origin;

        public LocalMethodInterceptor(T origin) {
            this.origin = origin;
        }

        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            try {
                System.out.println("intercept method["+method.getName()+"] before execution!");
                return method.invoke(origin, args);
            } finally {
                System.out.println("cleanup after  method["+method.getName()+"] execution!");
            }
        }
    }
}

But the problem is that any method is intercepted only once:
If I invoke abstract method - It will be intercepted. But hierarchy was planned so way that you never have to invoke it (abstractMethod). You just invoke realParentMethod and it do all things for you, meaning it invokes abstractMethod from itself.

In this example if you call realParentMethod only realParentMethod will be intercepted, abstract method will be just skipped.

Here are some console output to this example:

intercept method[abstractMethod] before execution!
abstractMethod implementation is running!
cleanup after  method[abstractMethod] execution!
-----------------
intercept method[realParentMethod] before execution!
invoking abstractMethod from realParentMethod
abstractMethod implementation is running!
cleanup after  method[realParentMethod] execution!


问:
Meaning of struct.pack( ) arguments in code for Beagleboard IP assignment
I was writing a program to assign IP address to beaglebone black in python using ioctl.

(reference How to assign IP address to interface in python? and Getting IP address of the beagleboard using python )

Since IOCTL method implemented in Linux Kernel needs all the parameters to be passed into a particular structure. Hence I constructed all those parameters as a struct and then passed to IOCTL.

```<code>bin_ip = socket.inet_aton('192.168.0.1')
ifreq = struct.pack('16sH2s4s8s', 'eth0', socket.AF_INET, '\x00'*2, bin_ip, '\x00'*8)
</code>```

found partial meaning of first argument at https://docs.python.org/3.0/library/struct.html as  s= char[] and H = unsigned short what is meaning of numbers 16 2 4 8 written with s and H

edit: For the 's' format character, the count is interpreted as the length of the bytes, for example, 16s means a single 16-byte string followed by 1 unsigned short, 2-byte string ,4-byte string , 8-byte string

why 4th argument is '\x00\x00'and last argument is '\x00\x00\x00\x00\x00\x00\x00\x00'? Is this the standard format / expected format?

答:
It appears that the struct being packed here is ifreq, where the fields "ifr_name" and "ifr_addr" gets set. 'eth0' gets set for "ifr_name", while the rest is for "ifr_addr".

Ifr_addr is a sockaddr, in this case I suppose actually a sockaddr_in. Based on this page the fields are:

```<code>struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};
</code>```

In your code socket.AF_INET sets the sin_family. Then the fourth argument two zeroes are the port, likely as here the IP address is set so it isn't port-specific. Then comes the ip address and finally eight zeroes.

Body:
I was writing a program to assign IP address to beaglebone black in python using ioctl.

(reference How to assign IP address to interface in python? and Getting IP address of the beagleboard using python )

Since IOCTL method implemented in Linux Kernel needs all the parameters to be passed into a particular structure. Hence I constructed all those parameters as a struct and then passed to IOCTL.

bin_ip = socket.inet_aton('192.168.0.1')
ifreq = struct.pack('16sH2s4s8s', 'eth0', socket.AF_INET, '\x00'*2, bin_ip, '\x00'*8)

found partial meaning of first argument at https://docs.python.org/3.0/library/struct.html as  s= char[] and H = unsigned short what is meaning of numbers 16 2 4 8 written with s and H

edit: For the 's' format character, the count is interpreted as the length of the bytes, for example, 16s means a single 16-byte string followed by 1 unsigned short, 2-byte string ,4-byte string , 8-byte string

why 4th argument is '\x00\x00'and last argument is '\x00\x00\x00\x00\x00\x00\x00\x00'? Is this the standard format / expected format?

Body:
It appears that the struct being packed here is ifreq, where the fields "ifr_name" and "ifr_addr" gets set. 'eth0' gets set for "ifr_name", while the rest is for "ifr_addr".

Ifr_addr is a sockaddr, in this case I suppose actually a sockaddr_in. Based on this page the fields are:

struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

In your code socket.AF_INET sets the sin_family. Then the fourth argument two zeroes are the port, likely as here the IP address is set so it isn't port-specific. Then comes the ip address and finally eight zeroes.


问:
Not able to use enum in mysql
```<code>DROP TABLE IF EXISTS CountryLanguage;
CREATE TABLE CountryLanguage (
  CountryCode CHAR(3) NOT NULL DEFAULT '',
  Language CHAR(30) NOT NULL DEFAULT '',
  IsOfficial ENUM('True','False') NOT NUll default 'False',
  Percentage FLOAT(4,1) NOT NULL DEFAULT '0.0',
  PRIMARY KEY  (CountryCode,Language)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO CountryLanguage VALUES ('AND','Spanish',0,44.6);
</code>```

When I enter the insert statement it gives me an error:

'Data truncated for column IsOfficial'.

It only gives an error when I use 0 ,it works well for 1.

答:
Because the ENUM type indexes are not zero-based:

Index Values for Enumeration Literals

Each enumeration value has an index:

The elements listed in the column specification are assigned index numbers, beginning with 1.

Additionally, 0 has a special meaning:

The index value of the empty string error value is 0. This means that you can use the following SELECT statement to find rows into which invalid ENUM values were assigned:

```<code>mysql> SELECT * FROM tbl_name WHERE enum_col=0;
</code>```

If you go through the hassle of defining and maintaining an ENUM type you could just use the text labels. However, for a simple boolean column I would just use TINYINT and 0/1 values, maybe through the TRUE and FALSEconstants:

```<code>DROP TABLE IF EXISTS CountryLanguage;
CREATE TABLE CountryLanguage (
  CountryCode CHAR(3) NOT NULL,
  Language CHAR(30) NOT NULL,
  IsOfficial TINYINT(1) NOT NULL default false,
  Percentage FLOAT(4,1) NOT NULL DEFAULT 0.0,
  PRIMARY KEY (CountryCode, Language)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO CountryLanguage (CountryCode, Language, IsOfficial, Percentage)
VALUES ('AND', 'Spanish', false, 44.6);

INSERT INTO CountryLanguage (CountryCode, Language, IsOfficial, Percentage)
VALUES ('AND', 'Catalan ', true, 33);
</code>```

Title: Not able to use enum in mysql

Body:
DROP TABLE IF EXISTS CountryLanguage;
CREATE TABLE CountryLanguage (
  CountryCode CHAR(3) NOT NULL DEFAULT '',
  Language CHAR(30) NOT NULL DEFAULT '',
  IsOfficial ENUM('True','False') NOT NUll default 'False',
  Percentage FLOAT(4,1) NOT NULL DEFAULT '0.0',
  PRIMARY KEY  (CountryCode,Language)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO CountryLanguage VALUES ('AND','Spanish',0,44.6);

When I enter the insert statement it gives me an error:

'Data truncated for column IsOfficial'.

It only gives an error when I use 0 ,it works well for 1.

Body:
Because the ENUM type indexes are not zero-based:

Index Values for Enumeration Literals

Each enumeration value has an index:

The elements listed in the column specification are assigned index numbers, beginning with 1.

Additionally, 0 has a special meaning:

The index value of the empty string error value is 0. This means that you can use the following SELECT statement to find rows into which invalid ENUM values were assigned:

mysql> SELECT * FROM tbl_name WHERE enum_col=0;

If you go through the hassle of defining and maintaining an ENUM type you could just use the text labels. However, for a simple boolean column I would just use TINYINT and 0/1 values, maybe through the TRUE and FALSEconstants:

DROP TABLE IF EXISTS CountryLanguage;
CREATE TABLE CountryLanguage (
  CountryCode CHAR(3) NOT NULL,
  Language CHAR(30) NOT NULL,
  IsOfficial TINYINT(1) NOT NULL default false,
  Percentage FLOAT(4,1) NOT NULL DEFAULT 0.0,
  PRIMARY KEY (CountryCode, Language)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO CountryLanguage (CountryCode, Language, IsOfficial, Percentage)
VALUES ('AND', 'Spanish', false, 44.6);

INSERT INTO CountryLanguage (CountryCode, Language, IsOfficial, Percentage)
VALUES ('AND', 'Catalan ', true, 33);


问:
Using regexp to select rows in R dataframe
I'm trying to select rows in a dataframe where the string contained in a column matches either a regular expression or a substring:

dataframe:

```<code>aName   bName   pName   call  alleles   logRatio    strength
AX-11086564 F08_ADN103  2011-02-10_R10  AB  CG  0.363371    10.184215
AX-11086564 A01_CD1919  2011-02-24_R11  BB  GG  -1.352707   9.54909
AX-11086564 B05_CD2920  2011-01-27_R6   AB  CG  -0.183802   9.766334
AX-11086564 D04_CD5950  2011-02-09_R9   AB  CG  0.162586    10.165051
AX-11086564 D07_CD6025  2011-02-10_R10  AB  CG  -0.397097   9.940238
AX-11086564 B05_CD3630  2011-02-02_R7   AA  CC  2.349906    9.153076
AX-11086564 D04_ADN103  2011-02-10_R2   BB  GG  -1.898088   9.872966
AX-11086564 A01_CD2588  2011-01-27_R5   BB  GG  -1.208094   9.239801
</code>```

For example, I want a dataframe containing only rows that contain ADN in column bName.   Secondarily, I would like all rows that contain ADN in column bName and that match 2011-02-10_R2 in column pName.

I tried using functions grep(), agrep() and more but without success...

Body:
I'm trying to select rows in a dataframe where the string contained in a column matches either a regular expression or a substring:

dataframe:

aName   bName   pName   call  alleles   logRatio    strength
AX-11086564 F08_ADN103  2011-02-10_R10  AB  CG  0.363371    10.184215
AX-11086564 A01_CD1919  2011-02-24_R11  BB  GG  -1.352707   9.54909
AX-11086564 B05_CD2920  2011-01-27_R6   AB  CG  -0.183802   9.766334
AX-11086564 D04_CD5950  2011-02-09_R9   AB  CG  0.162586    10.165051
AX-11086564 D07_CD6025  2011-02-10_R10  AB  CG  -0.397097   9.940238
AX-11086564 B05_CD3630  2011-02-02_R7   AA  CC  2.349906    9.153076
AX-11086564 D04_ADN103  2011-02-10_R2   BB  GG  -1.898088   9.872966
AX-11086564 A01_CD2588  2011-01-27_R5   BB  GG  -1.208094   9.239801

For example, I want a dataframe containing only rows that contain ADN in column bName.   Secondarily, I would like all rows that contain ADN in column bName and that match 2011-02-10_R2 in column pName.

I tried using functions grep(), agrep() and more but without success...

Body:
This is a pretty minimal solution using dplyr and magrittr which I think is what you are after:

Data:
library(magrittr)
library(stringr)
dat <- read.table(text="
aName   bName   pName   call  alleles   logRatio    strength
                  AX-11086564 F08_ADN103  2011-02-10_R10  AB  CG  0.363371    10.184215
                  AX-11086564 A01_CD1919  2011-02-24_R11  BB  GG  -1.352707   9.54909
                  AX-11086564 B05_CD2920  2011-01-27_R6   AB  CG  -0.183802   9.766334
                  AX-11086564 D04_CD5950  2011-02-09_R9   AB  CG  0.162586    10.165051
                  AX-11086564 D07_CD6025  2011-02-10_R10  AB  CG  -0.397097   9.940238
                  AX-11086564 B05_CD3630  2011-02-02_R7   AA  CC  2.349906    9.153076
                  AX-11086564 D04_ADN103  2011-02-10_R2   BB  GG  -1.898088   9.872966
                  AX-11086564 A01_CD2588  2011-01-27_R5   BB  GG  -1.208094   9.239801
                  ", header=TRUE)

rows that contain ADN in column bName.

dat %>%
  filter(str_detect(bName, "ADN") == TRUE)

Secondarily, I would like all rows that contain ADN in column bName
  and that match 2011-02-10_R2 in column pName.

dat %>%
  filter(str_detect(bName, "ADN") & pName == "2011-02-10_R2")


问:
Read in next line from file each call
I have a bash script

```<code>for ((i=0; i < 2500; i++)); do
    ./program.bin < in >> out
done
</code>```

I want to read from the next line every time I call this. For example this is my in file

```<code>1024 2048 3096

1045 8754 5412

5648 5457 5646

EOF
</code>```

So the first time through the loop the program gets 1024 2048 3096 as the inputs. The second time through it gets 1045 8754 5412 and so on. I have a feeling the way I have it set up now it continually reads in only the first line. How do I solve this problem?

答:
Try this instead:

```<code>while IFS= read -r line
do
    ./program.bin <<<"$line" >> out
done < in
</code>```

This will read the in file line by line, and for each line call ./program.bin, provide the value read (found inside variable line) and supply  it on standard input to the program.

Of course, you could have the program itself be able to handle multi-line input if you are coding this program.

Title: Read in next line from file each call

Body:
I have a bash script

for ((i=0; i < 2500; i++)); do
    ./program.bin < in >> out
done

I want to read from the next line every time I call this. For example this is my in file

1024 2048 3096

1045 8754 5412

5648 5457 5646

EOF

So the first time through the loop the program gets 1024 2048 3096 as the inputs. The second time through it gets 1045 8754 5412 and so on. I have a feeling the way I have it set up now it continually reads in only the first line. How do I solve this problem?

Body:
Try this instead:

while IFS= read -r line
do
    ./program.bin <<<"$line" >> out
done < in

This will read the in file line by line, and for each line call ./program.bin, provide the value read (found inside variable line) and supply  it on standard input to the program.

Of course, you could have the program itself be able to handle multi-line input if you are coding this program.


问:
how can you tell if github repository is for python 2 or python 3
I'm interested in running this code from github – how do I know if it was written for python2 or python3?

I'm hoping this is a really basic question and there is just some part of the site which makes this obvious.

答:
You could download the source and run the 2to3 script to see if it proposes changes to upgrade it to python3:

https://docs.python.org/3/library/2to3.html

If there are no changes, then it is Python3 (and maybe also Python2) code.


问:
How I can generate all combinations from RegEx (regular expression)?
For example, I have the following regular expression:

60[FP]LP[FP]XXXXXX

And now need all possible combinations, in this case:

60FLPFXXXXXX

60FLPPXXXXXX

60PLPFXXXXXX

60PLPPXXXXXX

Input RegEx is 12 characters long and consists of uppercase letters [A-Z] and numbers [0-9]

答:
I found a solution. With the tool rexgen (https://github.com/teeshop/rexgen) is it possible to generate all combinations from a given regular expression :)</p>

```<code>$ rexgen 60[FP]LP[FP]XXXXXX
60FLPFXXXXXX
60PLPFXXXXXX
60FLPPXXXXXX
60PLPPXXXXXX
</code>```

Body:
I found a solution. With the tool rexgen (https://github.com/teeshop/rexgen) is it possible to generate all combinations from a given regular expression :)

$ rexgen 60[FP]LP[FP]XXXXXX
60FLPFXXXXXX
60PLPFXXXXXX
60FLPPXXXXXX
60PLPPXXXXXX


问:
Facebook share button not showing until after refresh
Last week I added Facebook and Twitter share buttons to my rails app. I thought they were working fine but it seems they were not reliably loaded and required a refresh to get them to show. I thought this was a turbolinks issue as these things often are so I installed the 'jquery-turbolinks'gem. It isn't a turbolinks issue.

After looking around I found answers like this one and whilst adding  twttr.widgets.load(); to the end of my twitter function solved that problem, I've had no luck with getting  FB.XFBML.parse(); to make the Facebook share button to load without a refresh. On this Facebook dev page it doesn't list the share button as one of the things that can be fixed with that code.

My code, which is in a partial, is as follows:

```<code><script>(function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.0";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk')); FB.XFBML.parse();</script>

<div class="share-buttons">
   <div id="fb-root"></div>
      <div class="fb-share-button" data-href="#{request.original_url}" data-width="110"></div>
</div>
</code>```

答: I embedded a Facebook page widget into my website which was an Angular SPA and I had the same "needs a refresh" problem because I had mistakenly put the Script in a parent containing view page called "index.html", but I'd put the embedded DIV in a different sub view specifically on a "social_media.html" page. "index.html" loaded and fired the script on first visit to any page of my website, but at that point had no visibility of the DIV on my as of yet unused and un-requested "social_media.html" view, so when the user eventually navigates to a link that uses the sub view for "social_media.html", "index.html" was not "re-loaded" and thus did not re-fire the script unless I clicked refresh. To fix it I just put the Script and DIVS all into the same "social_media.html" to load and fire at once on all requests for the "social_media.html" to be loaded as a view page. Note: I also had to add DhruvPathak's approach too.</p>


问:
Error using Perforce within Emacs
I've obtained p4.el and put the following in my .emacs, running under cygwin:

```<code>(setq p4-executable "p4")
(load-library "p4")
</code>```

p4.exe is the cygwin version.

On running M-x p4-info I get the following error:

```<code>/path/to/p4.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory
</code>```

Yet running M-! p4 info works fine. Probably I'm missing an env variable. Apologies if this is a basic question - I'm new to emacs.

答: Try adding (p4-set-p4-executable "/my/path/to/p4") to your .emacs.

Title: Error using Perforce within Emacs

Body:
I've obtained p4.el and put the following in my .emacs, running under cygwin:

(setq p4-executable "p4")
(load-library "p4")

p4.exe is the cygwin version.

On running M-x p4-info I get the following error:

/path/to/p4.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory

Yet running M-! p4 info works fine. Probably I'm missing an env variable. Apologies if this is a basic question - I'm new to emacs.