问:
Extracting multiple xml trees from a mixed content document
I'm trying to use Python to extract multiple XML elements from a mixed-content document. The use case is an email that contains email text but also contains multiple XML trees.

Here's the example document:

```<code>Email text email text email text email text.

email signature email signature.

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
</catalog>

Email text email text email text email text.

email signature email signature.

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
</catalog>

Email text email text email text email text.

email signature email signature.

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
</catalog>

Email text email text email text email text.

email signature email signature.
</code>```

I want to extract the XML trees so they can be parsed by an XML parser in a for loop. I've perfected parsing the XML, and if I take one of the XML trees and parse it directly, it works llike a charm.

Any advise on how to extract the XML trees? This example is over-simplified as well, the email text and signatures are different in each example that I have, so the only reliable text to key on is the beginning and ending of the XML tree.

答:
With the help from another very smart developer, this code solves my problem. </p>

```<code>tr1 = "<?xml"
str2 = "</catalog>"
i = 0
ii = 0
tracker = []
final_ls = []

for c in data:
    for char in str1:
        if data[i + ii] == char:
            if ii == len(str1) - 1:
                tracker.append(i)
            ii += 1
    i += 1
    ii = 0

for xml in tracker:
    ii = 0
    i = xml
    for c in data[i:]:
        if ii == len(str2):
            break
        ii = 0
        for char in str2:
            if data[i + ii] == char:
                if ii == len(str2) - 1:
                    final_ls.append(data[xml:i + ii])
                    ii += 1
                else:
                    ii += 1
        i += 1

for ls in final_ls:
    print(ls)
</code>```

Body:
I'm trying to use Python to extract multiple XML elements from a mixed-content document. The use case is an email that contains email text but also contains multiple XML trees.

Here's the example document:

Email text email text email text email text.

email signature email signature.

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
</catalog>

Email text email text email text email text.

email signature email signature.

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
</catalog>

Email text email text email text email text.

email signature email signature.

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
</catalog>

Email text email text email text email text.

email signature email signature.

I want to extract the XML trees so they can be parsed by an XML parser in a for loop. I've perfected parsing the XML, and if I take one of the XML trees and parse it directly, it works llike a charm.

Any advise on how to extract the XML trees? This example is over-simplified as well, the email text and signatures are different in each example that I have, so the only reliable text to key on is the beginning and ending of the XML tree.

Body:
With the help from another very smart developer, this code solves my problem.

tr1 = "<?xml"
str2 = "</catalog>"
i = 0
ii = 0
tracker = []
final_ls = []

for c in data:
    for char in str1:
        if data[i + ii] == char:
            if ii == len(str1) - 1:
                tracker.append(i)
            ii += 1
    i += 1
    ii = 0

for xml in tracker:
    ii = 0
    i = xml
    for c in data[i:]:
        if ii == len(str2):
            break
        ii = 0
        for char in str2:
            if data[i + ii] == char:
                if ii == len(str2) - 1:
                    final_ls.append(data[xml:i + ii])
                    ii += 1
                else:
                    ii += 1
        i += 1

for ls in final_ls:
    print(ls)


来源: stackexchange

问:
How to properly document S4 "[" and “[<-“ methods using roxygen?
Below I posted a mini example in which I want do write documentation for
an “[“ method for a S4 class. Does someone know how to properly document a method for the generic "[" using roxygen and S4?

I get a warning when checking the package after building (see below).

```<code>#' An S4 class that stores a string.
#' @slot a contains a string
#' @export
setClass("testClass",
         representation(a="character"))

#' extract method for testClass
#'
#' @docType methods
#' @rdname extract-methods
setMethod("[", signature(x = "testClass", i = "ANY", j="ANY"),
         function (x, i, j, ..., drop){
             print("void function")
         }
)
</code>```

Excerpt from  package check:

```<code>* checking for missing documentation entries ... WARNING
Undocumented S4 methods:
  generic '[' and siglist 'testClass'
All user-level objects in a package (including S4 classes and methods)
should have documentation entries.
See the chapter 'Writing R documentation files' in manual 'Writing R Extensions'.
</code>```

答:
I finally figured it out more or less. At least it works now:</p>

```<code>#' An S4 class that stores a string.
#' @slot a contains a string
#' @export
setClass("testClass",
     representation(a="character"))

#' extract parts of testClass
#'
#' @name [
#' @aliases [,testClass-method
#' @docType methods
#' @rdname extract-methods
#'
setMethod("[", signature(x = "testClass", i = "ANY", j="ANY"),
    function (x, i, j, ..., drop){
       print("void function")
    }
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Below I posted a mini example in which I want do write documentation for
an “[“ method for a S4 class. Does someone know how to properly document a method for the generic "[" using roxygen and S4?

I get a warning when checking the package after building (see below).

#' An S4 class that stores a string.
#' @slot a contains a string
#' @export
setClass("testClass",
         representation(a="character"))

#' extract method for testClass
#'
#' @docType methods
#' @rdname extract-methods
setMethod("[", signature(x = "testClass", i = "ANY", j="ANY"),
         function (x, i, j, ..., drop){
             print("void function")
         }
)

Excerpt from  package check:

* checking for missing documentation entries ... WARNING
Undocumented S4 methods:
  generic '[' and siglist 'testClass'
All user-level objects in a package (including S4 classes and methods)
should have documentation entries.
See the chapter 'Writing R documentation files' in manual 'Writing R Extensions'.

Body:
I finally figured it out more or less. At least it works now:

#' An S4 class that stores a string.
#' @slot a contains a string
#' @export
setClass("testClass",
     representation(a="character"))

#' extract parts of testClass
#'
#' @name [
#' @aliases [,testClass-method
#' @docType methods
#' @rdname extract-methods
#'
setMethod("[", signature(x = "testClass", i = "ANY", j="ANY"),
    function (x, i, j, ..., drop){
       print("void function")
    }
)

ContentLicense: CC BY-SA 2.5


问:
firebase asking for key id when activating for iOS app

What does the key id mean? Please help me, I don't know what to enter in there.

答:
You have selected "APNS Auth key" option while uploading .p12 file (Attached image (1) ).

To generate a "APNS Auth key", You should open developer.apple.com, and generate key from below attached image.

If you don't have  "APNS Auth key", you should go with "APNs Certificate" option in firebase (Attached image (2). In that case, Firebase will not ask you for "key id".

ContentLicense: CC BY-SA 3.0


问:
How to decomrepss a password protected 7zip archive with Java on Linux?
In my project, we need to extract a file from a password protected 7zip archive.

My source code as following:

```<code>try {
    ProcessBuilder pb = new ProcessBuilder("7z", "e", "bootstrap.7z", "-so", "bootstrap.txt");
    Process p = pb.start();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

    writer.write("password" + "\n");
    writer.flush();
    writer.close();

    String line = null;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch  (IOException e) {
    e.printStackTrace();
}
</code>```

The above code block doesn't work.

Although I have passed the password via BufferedWriter, I still need to input the password manually when I run the java program.

For the security reason, I can't use the parameter "-p" to pass the password to the 7z when create the sub-process(If the process "7z" hang, the customer can see the password from the process information via the command "ps aux | grep 7z").

Can you pls figure out the issue in my code?  My java version is 1.8, the OS is Ubuntu 16.04.

Appreciate.

答:
You can't type to some command line programs using std.out, because they don't read std.out, they just read signs entered on keyboard. I belive this is the case when you enter password for 7z using command line. In order to be able to enter this password, you need to start a console window, and then mimic the behavior of keyboard, so it will be like someone is really typing into the window. You can use a java Robot class to do that. I have an Keyborad class that encloses the Robot, to simplify the proces of typing. Beware, that the in the Keyboard class on your systems some of the special characters may need to be typed differently, so you need to adjust this. Here is some pseudo code (it is for windows, but it should be easy to convert it for linux) for your case and the Keyboard.java implementation:

```<code>public static void run7z() throws IOException, InterruptedException {
    startCommandLineShell();
    waitABit();
    keyboard.type("7z.exe e bootstrap.7z -so bootstrap.txt").enter();
    waitABit();
    keyboard.type("yourSecretPasswordHere").enter();
}

private static void startCommandLineShell() throws IOException {
    Runtime.getRuntime().exec(new String[] { "C:\\Windows\\system32\\cmd.exe", "/C", "start" });
}
</code>```

And the keyboard class:

```<code>import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class Keyboard {

    private Robot robot;

    public static void main(String... args) throws Exception
    {

        Keyboard keyboard = new Keyboard();
        keyboard.type("~!@#$%^&*()_+");
    }

    public Keyboard()
    {
        try {
            this.robot = new Robot();
            robot.delay(500);
            robot.setAutoDelay(2);
            robot.setAutoWaitForIdle(true);
        } catch (AWTException e) {
            throw new RuntimeException(e);
        }
    }

    public Keyboard(Robot robot)
    {
        this.robot = robot;
    }

    public Keyboard type(CharSequence characters)
    {
        int length = characters.length();
        for (int i = 0; i < length; i++)
        {
                char character = characters.charAt(i);
                type(character);
        }
        return this;
    }

    public void enter()
    {
      robot.keyPress(KeyEvent.VK_ENTER);
    }

    public void type(char character)
    {
        try {
        switch (character) {
        case 'a': doType(KeyEvent.VK_A); break;
        case 'b': doType(KeyEvent.VK_B); break;
        case 'c': doType(KeyEvent.VK_C); break;
        case 'd': doType(KeyEvent.VK_D); break;
        case 'e': doType(KeyEvent.VK_E); break;
        case 'f': doType(KeyEvent.VK_F); break;
        case 'g': doType(KeyEvent.VK_G); break;
        case 'h': doType(KeyEvent.VK_H); break;
        case 'i': doType(KeyEvent.VK_I); break;
        case 'j': doType(KeyEvent.VK_J); break;
        case 'k': doType(KeyEvent.VK_K); break;
        case 'l': doType(KeyEvent.VK_L); break;
        case 'm': doType(KeyEvent.VK_M); break;
        case 'n': doType(KeyEvent.VK_N); break;
        case 'o': doType(KeyEvent.VK_O); break;
        case 'p': doType(KeyEvent.VK_P); break;
        case 'q': doType(KeyEvent.VK_Q); break;
        case 'r': doType(KeyEvent.VK_R); break;
        case 's': doType(KeyEvent.VK_S); break;
        case 't': doType(KeyEvent.VK_T); break;
        case 'u': doType(KeyEvent.VK_U); break;
        case 'v': doType(KeyEvent.VK_V); break;
        case 'w': doType(KeyEvent.VK_W); break;
        case 'x': doType(KeyEvent.VK_X); break;
        case 'y': doType(KeyEvent.VK_Y); break;
        case 'z': doType(KeyEvent.VK_Z); break;
        case 'A': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_A); break;
        case 'B': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_B); break;
        case 'C': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_C); break;
        case 'D': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_D); break;
        case 'E': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_E); break;
        case 'F': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_F); break;
        case 'G': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_G); break;
        case 'H': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_H); break;
        case 'I': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_I); break;
        case 'J': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_J); break;
        case 'K': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_K); break;
        case 'L': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_L); break;
        case 'M': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_M); break;
        case 'N': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_N); break;
        case 'O': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_O); break;
        case 'P': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_P); break;
        case 'Q': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_Q); break;
        case 'R': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_R); break;
        case 'S': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_S); break;
        case 'T': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_T); break;
        case 'U': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_U); break;
        case 'V': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_V); break;
        case 'W': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_W); break;
        case 'X': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_X); break;
        case 'Y': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_Y); break;
        case 'Z': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_Z); break;
        case '`': doType(KeyEvent.VK_BACK_QUOTE); break;
        case '0': doType(KeyEvent.VK_0); break;
        case '1': doType(KeyEvent.VK_1); break;
        case '2': doType(KeyEvent.VK_2); break;
        case '3': doType(KeyEvent.VK_3); break;
        case '4': doType(KeyEvent.VK_4); break;
        case '5': doType(KeyEvent.VK_5); break;
        case '6': doType(KeyEvent.VK_6); break;
        case '7': doType(KeyEvent.VK_7); break;
        case '8': doType(KeyEvent.VK_8); break;
        case '9': doType(KeyEvent.VK_9); break;
        case '-': doType(KeyEvent.VK_MINUS); break;
        case '=': doType(KeyEvent.VK_EQUALS); break;
        case '~': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_BACK_QUOTE); break;
        case '!': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_1); break;//doType(KeyEvent.VK_EXCLAMATION_MARK); break;
        case '@': doType(KeyEvent.VK_AT); break;
        case '#': doType(KeyEvent.VK_NUMBER_SIGN); break;
        case '$': doType(KeyEvent.VK_DOLLAR); break;
        case '%': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_5); break;
        case '^': doType(KeyEvent.VK_CIRCUMFLEX); break;
        case '&': doType(KeyEvent.VK_AMPERSAND); break;
        case '*': doType(KeyEvent.VK_ASTERISK); break;
        case '(': doType(KeyEvent.VK_LEFT_PARENTHESIS); break;
        case ')': doType(KeyEvent.VK_RIGHT_PARENTHESIS); break;
        case '_': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_MINUS); break;
        case '+': doType(KeyEvent.VK_PLUS); break;
        case '\t': doType(KeyEvent.VK_TAB); break;
        case '\n': doType(KeyEvent.VK_ENTER); break;
        case '[': doType(KeyEvent.VK_OPEN_BRACKET); break;
        case ']': doType(KeyEvent.VK_CLOSE_BRACKET); break;
        case '\\': doType(KeyEvent.VK_BACK_SLASH); break;
        case '{': doType(KeyEvent.VK_SHIFT, KeyEvent. VK_OPEN_BRACKET); break;
        case '}': doType(KeyEvent.VK_SHIFT, KeyEvent. VK_CLOSE_BRACKET); break;
        case '|': doType(KeyEvent.VK_SHIFT, KeyEvent. VK_BACK_SLASH); break;
        case ';': doType(KeyEvent.VK_SEMICOLON); break;
        case ':': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_SEMICOLON); break;
        case '\'': doType(KeyEvent.VK_QUOTE); break;
        case '"': doType(KeyEvent.VK_QUOTEDBL); break;
        case ',': doType(KeyEvent.VK_COMMA); break;
        case '<': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_COMMA); break;//doType(KeyEvent.VK_LESS); break;
        case '.': doType(KeyEvent.VK_PERIOD); break;
        case '>': doType(KeyEvent.VK_SHIFT,KeyEvent.VK_PERIOD); break;
        case '/': doType(KeyEvent.VK_SLASH); break;
        case '?': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_SLASH); break;
        case ' ': doType(KeyEvent.VK_SPACE); break;
//        default:  doType(KeyEvent.getExtendedKeyCodeForChar(character));
//                throw new IllegalArgumentException("Cannot type character " + character);
        }
        } catch (Exception e) {
            System.out.println(e+" Can't type characer: "+character);
        }
    }

    private void doType(int... keyCodes)
    {
        doType(keyCodes, 0, keyCodes.length);
    }

    private void doType(int[] keyCodes, int offset, int length)
    {
        if (length == 0)
            return;

        robot.keyPress(keyCodes[offset]);
        doType(keyCodes, offset + 1, length - 1);
        robot.keyRelease(keyCodes[offset]);
    }

}
</code>```

Body:
In my project, we need to extract a file from a password protected 7zip archive.

My source code as following:

try {
    ProcessBuilder pb = new ProcessBuilder("7z", "e", "bootstrap.7z", "-so", "bootstrap.txt");
    Process p = pb.start();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

    writer.write("password" + "\n");
    writer.flush();
    writer.close();

    String line = null;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch  (IOException e) {
    e.printStackTrace();
}

The above code block doesn't work.

Although I have passed the password via BufferedWriter, I still need to input the password manually when I run the java program.

For the security reason, I can't use the parameter "-p" to pass the password to the 7z when create the sub-process(If the process "7z" hang, the customer can see the password from the process information via the command "ps aux | grep 7z").

Can you pls figure out the issue in my code?  My java version is 1.8, the OS is Ubuntu 16.04.

Appreciate.

Body:
You can't type to some command line programs using std.out, because they don't read std.out, they just read signs entered on keyboard. I belive this is the case when you enter password for 7z using command line. In order to be able to enter this password, you need to start a console window, and then mimic the behavior of keyboard, so it will be like someone is really typing into the window. You can use a java Robot class to do that. I have an Keyborad class that encloses the Robot, to simplify the proces of typing. Beware, that the in the Keyboard class on your systems some of the special characters may need to be typed differently, so you need to adjust this. Here is some pseudo code (it is for windows, but it should be easy to convert it for linux) for your case and the Keyboard.java implementation:

public static void run7z() throws IOException, InterruptedException {
    startCommandLineShell();
    waitABit();
    keyboard.type("7z.exe e bootstrap.7z -so bootstrap.txt").enter();
    waitABit();
    keyboard.type("yourSecretPasswordHere").enter();
}

private static void startCommandLineShell() throws IOException {
    Runtime.getRuntime().exec(new String[] { "C:\\Windows\\system32\\cmd.exe", "/C", "start" });
}

And the keyboard class:

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class Keyboard {

    private Robot robot;

    public static void main(String... args) throws Exception
    {

        Keyboard keyboard = new Keyboard();
        keyboard.type("~!@#$%^&*()_+");
    }

    public Keyboard()
    {
        try {
            this.robot = new Robot();
            robot.delay(500);
            robot.setAutoDelay(2);
            robot.setAutoWaitForIdle(true);
        } catch (AWTException e) {
            throw new RuntimeException(e);
        }
    }

    public Keyboard(Robot robot)
    {
        this.robot = robot;
    }

    public Keyboard type(CharSequence characters)
    {
        int length = characters.length();
        for (int i = 0; i < length; i++)
        {
                char character = characters.charAt(i);
                type(character);
        }
        return this;
    }

    public void enter()
    {
      robot.keyPress(KeyEvent.VK_ENTER);
    }

    public void type(char character)
    {
        try {
        switch (character) {
        case 'a': doType(KeyEvent.VK_A); break;
        case 'b': doType(KeyEvent.VK_B); break;
        case 'c': doType(KeyEvent.VK_C); break;
        case 'd': doType(KeyEvent.VK_D); break;
        case 'e': doType(KeyEvent.VK_E); break;
        case 'f': doType(KeyEvent.VK_F); break;
        case 'g': doType(KeyEvent.VK_G); break;
        case 'h': doType(KeyEvent.VK_H); break;
        case 'i': doType(KeyEvent.VK_I); break;
        case 'j': doType(KeyEvent.VK_J); break;
        case 'k': doType(KeyEvent.VK_K); break;
        case 'l': doType(KeyEvent.VK_L); break;
        case 'm': doType(KeyEvent.VK_M); break;
        case 'n': doType(KeyEvent.VK_N); break;
        case 'o': doType(KeyEvent.VK_O); break;
        case 'p': doType(KeyEvent.VK_P); break;
        case 'q': doType(KeyEvent.VK_Q); break;
        case 'r': doType(KeyEvent.VK_R); break;
        case 's': doType(KeyEvent.VK_S); break;
        case 't': doType(KeyEvent.VK_T); break;
        case 'u': doType(KeyEvent.VK_U); break;
        case 'v': doType(KeyEvent.VK_V); break;
        case 'w': doType(KeyEvent.VK_W); break;
        case 'x': doType(KeyEvent.VK_X); break;
        case 'y': doType(KeyEvent.VK_Y); break;
        case 'z': doType(KeyEvent.VK_Z); break;
        case 'A': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_A); break;
        case 'B': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_B); break;
        case 'C': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_C); break;
        case 'D': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_D); break;
        case 'E': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_E); break;
        case 'F': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_F); break;
        case 'G': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_G); break;
        case 'H': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_H); break;
        case 'I': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_I); break;
        case 'J': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_J); break;
        case 'K': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_K); break;
        case 'L': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_L); break;
        case 'M': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_M); break;
        case 'N': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_N); break;
        case 'O': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_O); break;
        case 'P': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_P); break;
        case 'Q': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_Q); break;
        case 'R': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_R); break;
        case 'S': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_S); break;
        case 'T': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_T); break;
        case 'U': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_U); break;
        case 'V': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_V); break;
        case 'W': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_W); break;
        case 'X': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_X); break;
        case 'Y': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_Y); break;
        case 'Z': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_Z); break;
        case '`': doType(KeyEvent.VK_BACK_QUOTE); break;
        case '0': doType(KeyEvent.VK_0); break;
        case '1': doType(KeyEvent.VK_1); break;
        case '2': doType(KeyEvent.VK_2); break;
        case '3': doType(KeyEvent.VK_3); break;
        case '4': doType(KeyEvent.VK_4); break;
        case '5': doType(KeyEvent.VK_5); break;
        case '6': doType(KeyEvent.VK_6); break;
        case '7': doType(KeyEvent.VK_7); break;
        case '8': doType(KeyEvent.VK_8); break;
        case '9': doType(KeyEvent.VK_9); break;
        case '-': doType(KeyEvent.VK_MINUS); break;
        case '=': doType(KeyEvent.VK_EQUALS); break;
        case '~': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_BACK_QUOTE); break;
        case '!': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_1); break;//doType(KeyEvent.VK_EXCLAMATION_MARK); break;
        case '@': doType(KeyEvent.VK_AT); break;
        case '#': doType(KeyEvent.VK_NUMBER_SIGN); break;
        case '$': doType(KeyEvent.VK_DOLLAR); break;
        case '%': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_5); break;
        case '^': doType(KeyEvent.VK_CIRCUMFLEX); break;
        case '&': doType(KeyEvent.VK_AMPERSAND); break;
        case '*': doType(KeyEvent.VK_ASTERISK); break;
        case '(': doType(KeyEvent.VK_LEFT_PARENTHESIS); break;
        case ')': doType(KeyEvent.VK_RIGHT_PARENTHESIS); break;
        case '_': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_MINUS); break;
        case '+': doType(KeyEvent.VK_PLUS); break;
        case '\t': doType(KeyEvent.VK_TAB); break;
        case '\n': doType(KeyEvent.VK_ENTER); break;
        case '[': doType(KeyEvent.VK_OPEN_BRACKET); break;
        case ']': doType(KeyEvent.VK_CLOSE_BRACKET); break;
        case '\\': doType(KeyEvent.VK_BACK_SLASH); break;
        case '{': doType(KeyEvent.VK_SHIFT, KeyEvent. VK_OPEN_BRACKET); break;
        case '}': doType(KeyEvent.VK_SHIFT, KeyEvent. VK_CLOSE_BRACKET); break;
        case '|': doType(KeyEvent.VK_SHIFT, KeyEvent. VK_BACK_SLASH); break;
        case ';': doType(KeyEvent.VK_SEMICOLON); break;
        case ':': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_SEMICOLON); break;
        case '\'': doType(KeyEvent.VK_QUOTE); break;
        case '"': doType(KeyEvent.VK_QUOTEDBL); break;
        case ',': doType(KeyEvent.VK_COMMA); break;
        case '<': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_COMMA); break;//doType(KeyEvent.VK_LESS); break;
        case '.': doType(KeyEvent.VK_PERIOD); break;
        case '>': doType(KeyEvent.VK_SHIFT,KeyEvent.VK_PERIOD); break;
        case '/': doType(KeyEvent.VK_SLASH); break;
        case '?': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_SLASH); break;
        case ' ': doType(KeyEvent.VK_SPACE); break;
//        default:  doType(KeyEvent.getExtendedKeyCodeForChar(character));
//                throw new IllegalArgumentException("Cannot type character " + character);
        }
        } catch (Exception e) {
            System.out.println(e+" Can't type characer: "+character);
        }
    }

    private void doType(int... keyCodes)
    {
        doType(keyCodes, 0, keyCodes.length);
    }

    private void doType(int[] keyCodes, int offset, int length)
    {
        if (length == 0)
            return;

        robot.keyPress(keyCodes[offset]);
        doType(keyCodes, offset + 1, length - 1);
        robot.keyRelease(keyCodes[offset]);
    }

}


问:
Rails - RSpec NoMethodError: undefined method
I'm trying to test a very simple method that takes in 2 numbers and uses them to work out a percentage. However, when I try and run the tests it fails with the following error:

```<code>NoMethodError: undefined method `pct' for Scorable:Module
./spec/models/concerns/scorable_spec.rb:328:in `block (2 levels) in
<top (required)>'
./spec/rails_helper.rb:97:in `block (3 levels) in <top (required)>'
./spec/rails_helper.rb:96:in `block (2 levels) in <top (required)>'
-e:1:in `<main>'
</code>```

Here's my spec file for the module:

```<code>require 'rails_helper'
RSpec.describe Scorable, :type => :concern do

  it "pct should return 0 if den is 0 or nil" do
    expect(Scorable.pct(nil, 15)).to eq(0)
    expect(Scorable.pct(0, 15)).to eq(0)
  end

end
</code>```

Here is the pct method located in Scorable.rb:

```<code>def pct(num,den)
  return 0 if num == 0 or num.nil?
  return (100.0 * num / den).round
end
</code>```

And here's my rspec_helper:

```<code> if ENV['ENABLE_COVERAGE']
   require 'simplecov'
   SimpleCov.start do
   add_filter "/spec/"
   add_filter "/config/"
   add_filter '/vendor/'

   add_group 'Controllers', 'app/controllers'
   add_group 'Models', 'app/models'
   add_group 'Helpers', 'app/helpers'
   add_group 'Mailers', 'app/mailers'
   add_group 'Views', 'app/views'
 end
end

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
  expectations.include_chain_clauses_in_custom_matcher_descriptions =
  true
end
config.raise_errors_for_deprecations!

 config.mock_with :rspec do |mocks|
   mocks.verify_partial_doubles = true
 end
end
</code>```

I'm very new to RSpec and have been puzzling over this one for more than a day. It's definitely pointing to an existing method, as when I use Go To Declaration in RubyMine it opens the method declaration. Can anyone maybe shed some light for me on this one? I'm sure I'm overlooking something incredibly simple.

答:
To make the module method callable with Module.method notation is should be declared in module scope.

```<code>module Scorable
  def self.pct(num,den)
    return 0 if num == 0 or num.nil?
    return (100.0 * num / den).round
  end
end
</code>```

or:

```<code>module Scorable
  class << self
    def pct(num,den)
      return 0 if num == 0 or num.nil?
      return (100.0 * num / den).round
    end
  end
end
</code>```

or with Module#module_function:

```<code>module Scorable
  module_function
  def pct(num,den)
    return 0 if num == 0 or num.nil?
    return (100.0 * num / den).round
  end
end
</code>```

Note, that the latter declares both module method and normal instance method within this module.

Sidenote: using return in the very last line of the method is considered a code smell and should be avoided:

```<code>module Scorable
  def self.pct(num,den)
    return 0 if num == 0 or num.nil?
    (100.0 * num / den).round
  end
end
</code>```

Body:
I'm trying to test a very simple method that takes in 2 numbers and uses them to work out a percentage. However, when I try and run the tests it fails with the following error:

NoMethodError: undefined method `pct' for Scorable:Module
./spec/models/concerns/scorable_spec.rb:328:in `block (2 levels) in
<top (required)>'
./spec/rails_helper.rb:97:in `block (3 levels) in <top (required)>'
./spec/rails_helper.rb:96:in `block (2 levels) in <top (required)>'
-e:1:in `'

Here's my spec file for the module:

require 'rails_helper'
RSpec.describe Scorable, :type => :concern do

  it "pct should return 0 if den is 0 or nil" do
    expect(Scorable.pct(nil, 15)).to eq(0)
    expect(Scorable.pct(0, 15)).to eq(0)
  end

end

Here is the pct method located in Scorable.rb:

def pct(num,den)
  return 0 if num == 0 or num.nil?
  return (100.0 * num / den).round
end

And here's my rspec_helper:

 if ENV['ENABLE_COVERAGE']
   require 'simplecov'
   SimpleCov.start do
   add_filter "/spec/"
   add_filter "/config/"
   add_filter '/vendor/'

   add_group 'Controllers', 'app/controllers'
   add_group 'Models', 'app/models'
   add_group 'Helpers', 'app/helpers'
   add_group 'Mailers', 'app/mailers'
   add_group 'Views', 'app/views'
 end
end

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
  expectations.include_chain_clauses_in_custom_matcher_descriptions =
  true
end
config.raise_errors_for_deprecations!

 config.mock_with :rspec do |mocks|
   mocks.verify_partial_doubles = true
 end
end

I'm very new to RSpec and have been puzzling over this one for more than a day. It's definitely pointing to an existing method, as when I use Go To Declaration in RubyMine it opens the method declaration. Can anyone maybe shed some light for me on this one? I'm sure I'm overlooking something incredibly simple.

Body:
To make the module method callable with Module.method notation is should be declared in module scope.

module Scorable
  def self.pct(num,den)
    return 0 if num == 0 or num.nil?
    return (100.0 * num / den).round
  end
end

or:

module Scorable
  class << self
    def pct(num,den)
      return 0 if num == 0 or num.nil?
      return (100.0 * num / den).round
    end
  end
end

or with Module#module_function:

module Scorable
  module_function
  def pct(num,den)
    return 0 if num == 0 or num.nil?
    return (100.0 * num / den).round
  end
end

Note, that the latter declares both module method and normal instance method within this module.

Sidenote: using return in the very last line of the method is considered a code smell and should be avoided:

module Scorable
  def self.pct(num,den)
    return 0 if num == 0 or num.nil?
    (100.0 * num / den).round
  end
end


问:
Hibernate - how to avoid the n+1 issue while keeping a good throughput with @ManyToOne association?
I have a class Entry which has two fields serving auditing purposes: startAuditAction and endAuditAction. One audit action can affect several entries, therefore the class Entry describes ManyToOne relationships as follows:

```<code>public class Entry{
    @Id
    @Column(nullable = false)
    protected String path;

    @Id
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(nullable = false, name = "start_action_id")
    protected AuditAction startAction;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(updatable = true, nullable = true, name = "end_action_id")
    protected AuditAction endAction;
}
</code>```

I want to retrieve instances of Entry based on conditions on the path field and the audit fields. For example to retrieve entries which have not yet been deleted, the HQL would look something like that:

```<code>SELECT DISTINCT entry FROM ENTRY_TABLE entry JOIN FETCH entry.startAction startAct LEFT JOIN FETCH entry.endAction endAct WHERE entry.path LIKE myPath and endAct IS NULL
</code>```

I am using lazy loading together with JOIN FETCH to avoid the N+1 problem while still being able to access the audit fields. However, I have two problems with this:

Firstly, this really does not seem clean to me: if I know I want to access the audit fields (namely the audit actions timestamp), then they should not be lazy loaded. But if I use eager loading I am facing the n+1 problem even if I use JOIN FETCH (and in that case I do not understand why fetch = FetchType.EAGER would ever be useful)...

Secondly, even though I am avoiding the n+1 problem and therefore firing less SQL queries, I get some performance issues for the overall use of my database, probably because of the joins.

What is the proper way to avoid firing additional queries while preserving a good throughput ?

Thanks!

答:
1- Using join fetch is useful when you have FetchType.LAZY in a field that you know you'll need in that specific case whereas using FetchType.EAGER will force that entity to always load the collection independently from the query

(e.g. with your same configuration example you can do multiple query and only when you need the collection use the JOIN FETCH)

2- You probably have problems somewhere else, i doubt the join is what is slowing you down

Body:
I have a class Entry which has two fields serving auditing purposes: startAuditAction and endAuditAction. One audit action can affect several entries, therefore the class Entry describes ManyToOne relationships as follows:

public class Entry{
    @Id
    @Column(nullable = false)
    protected String path;

    @Id
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(nullable = false, name = "start_action_id")
    protected AuditAction startAction;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(updatable = true, nullable = true, name = "end_action_id")
    protected AuditAction endAction;
}

I want to retrieve instances of Entry based on conditions on the path field and the audit fields. For example to retrieve entries which have not yet been deleted, the HQL would look something like that:

SELECT DISTINCT entry FROM ENTRY_TABLE entry JOIN FETCH entry.startAction startAct LEFT JOIN FETCH entry.endAction endAct WHERE entry.path LIKE myPath and endAct IS NULL

I am using lazy loading together with JOIN FETCH to avoid the N+1 problem while still being able to access the audit fields. However, I have two problems with this:

Firstly, this really does not seem clean to me: if I know I want to access the audit fields (namely the audit actions timestamp), then they should not be lazy loaded. But if I use eager loading I am facing the n+1 problem even if I use JOIN FETCH (and in that case I do not understand why fetch = FetchType.EAGER would ever be useful)...

Secondly, even though I am avoiding the n+1 problem and therefore firing less SQL queries, I get some performance issues for the overall use of my database, probably because of the joins.

What is the proper way to avoid firing additional queries while preserving a good throughput ?

Thanks!


问:
WPF - Databinding Color to plain simple Window or Canvas in a Window Background - No controls
I need an answer so i can explore. I am running into a brick wall here:

I would like to use:

```<code>        for (int c = 0; c < 255; c++)
        {

            Color = Color.FromArgb(255, (byte)c, (byte)(255 - c), (byte)c);
            Thread.Sleep(3);
        }
</code>```

Each time the "Color" is recomputed, i would like the Window or the Canvas in the Window to IMMEDIATELY change color...so i get to SEE the cool color changes. Why is this so hard? I need to see this, but i'm hitting a brick wall. I copied a Type Converter here:

```<code>[ValueConversion(typeof(Color),typeof(SolidColorBrush))]
public class ColorBrushConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Color color = (Color)value;
        return new SolidColorBrush(color);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }

}
</code>```

THANK YOU FOR ANY HELP!

答:
You're doing this in the UI thread. If you block the UI thread with Thread.Sleep, the UI blocks as well (and no changes are applied).

The solution is to use a Timer instead of a loop. Save c in some instance variable of your window. Set a timer that expires after 3 ms, increases c, changes Color and then resets the timer to go off again in 3 ms.

Alternatively, you could start a background thread that loops (and uses Thread.Sleep). In that case, you must apply the Color change through Dispatcher.Invoke instead of simply setting Color = ....

To illustrate my point, here's a quick example of how to do it with a background thread:

```<code>// define the background thread
var colorChangeThread = new Thread(new ThreadStart(() => {
    for (int c = 0; c < 255; c++)
    {
        // this (and only this) is done in the UI thread
        Dispatcher.Invoke(new Action(() => {
            this.Background = new SolidColorBrush(Color.FromArgb(255, (byte)c, (byte)(255 - c), (byte)c));
        }));

        Thread.Sleep(8);    // the background thread waits
    }
}));
colorChangeThread.Start();  // start the background thread
</code>```

If you are using properties with INotifyPropertyChanged, you can skip the Dispatcher.Invoke and just set your property, see the explanation in Meleaks answer.

Body:
I need an answer so i can explore. I am running into a brick wall here:

I would like to use:

        for (int c = 0; c < 255; c++)
        {

            Color = Color.FromArgb(255, (byte)c, (byte)(255 - c), (byte)c);
            Thread.Sleep(3);
        }

Each time the "Color" is recomputed, i would like the Window or the Canvas in the Window to IMMEDIATELY change color...so i get to SEE the cool color changes. Why is this so hard? I need to see this, but i'm hitting a brick wall. I copied a Type Converter here:

[ValueConversion(typeof(Color),typeof(SolidColorBrush))]
public class ColorBrushConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Color color = (Color)value;
        return new SolidColorBrush(color);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }

}

THANK YOU FOR ANY HELP!

Body:
You're doing this in the UI thread. If you block the UI thread with Thread.Sleep, the UI blocks as well (and no changes are applied).

The solution is to use a Timer instead of a loop. Save c in some instance variable of your window. Set a timer that expires after 3 ms, increases c, changes Color and then resets the timer to go off again in 3 ms.

Alternatively, you could start a background thread that loops (and uses Thread.Sleep). In that case, you must apply the Color change through Dispatcher.Invoke instead of simply setting Color = ....

To illustrate my point, here's a quick example of how to do it with a background thread:

// define the background thread
var colorChangeThread = new Thread(new ThreadStart(() => {
    for (int c = 0; c < 255; c++)
    {
        // this (and only this) is done in the UI thread
        Dispatcher.Invoke(new Action(() => {
            this.Background = new SolidColorBrush(Color.FromArgb(255, (byte)c, (byte)(255 - c), (byte)c));
        }));

        Thread.Sleep(8);    // the background thread waits
    }
}));
colorChangeThread.Start();  // start the background thread

If you are using properties with INotifyPropertyChanged, you can skip the Dispatcher.Invoke and just set your property, see the explanation in Meleaks answer.


问:
Decoding a regex
I am looking to decode a regular expression.
Is there a way to check what the below regex means:</p>

```<code>^(PC([Y\\d])|GC([Y\\d])|Y|\\d)\\d{4,5}$
</code>```

答: Regexper is also a fine tool to analyze regular expressions.

Title: Decoding a regex

Body:
I am looking to decode a regular expression.
Is there a way to check what the below regex means:

^(PC([Y\\d])|GC([Y\\d])|Y|\\d)\\d{4,5}$


问:
fastest way to detect if a value is in a group of values in Javascript
I have a group of strings in Javascript and I need to write a function that detects if another specific string belongs to this group or not.

What is the fastest way to achieve this? Is it alright to put the group of values into an array, and then write a function that searches through the array?

I think if I keep the values sorted and do a binary search, it should work fast enough. Or is there some other smart way of doing this, which can work faster?

答:
I know it is an old post. But to detect if a value is in a set of values we can manipulate through array indexOf() which searches and detects the present of the value

var myString="this is my large string set";
var myStr=myString.split(' ');
console.log('myStr contains "my" = '+ (myStr.indexOf('my')>=0));
console.log('myStr contains "your" = '+ (myStr.indexOf('your')>=0));

console.log('integer example : [1, 2, 5, 3] contains 5 = '+ ([1, 2, 5, 3].indexOf(5)>=0));```

OwnerDisplayName: Gabi


问:
Why is Eclipse looking for nexus-maven-repository-index.zip when trying to update Nexus indexer?
I am using Eclipse Oxygen, and I have installed Nexus OSS Repository Manager. At Window->Preferences->Maven I have checked Download repository index updates on startup.

On startup Eclipse is trying to updated index for Nexus and it takes a while. But after that I am getting an error saying that it is unable to update index for nexus.

From the log I am extracting relevant lines:

```<code>!ENTRY org.eclipse.m2e.logback.appender 4 0 2017-07-04 10:55:22.312
!MESSAGE Unable to update index for nexus|http://localhost:8081/nexus/content/groups/public/: .m2\repository\.cache\m2e\1.8.0\33b5073b9c3fc53d62eb8dc83e442c3d\nexus-maven-repository-index.zip (The system cannot find the file specified)
!STACK 0
java.io.FileNotFoundException: .m2\repository\.cache\m2e\1.8.0\33b5073b9c3fc53d62eb8dc83e442c3d\nexus-maven-repository-index.zip (The system cannot find the file specified)...
</code>```

When I try to start new Maven project and choose Nexus Indexer as the Catalog I am getting the error message: No archetypes currently available. The archetype list will refresh when the indexes finish updating.

I am interested in why is Eclipse looking for nexus-maven-repository-index.zip instead of nexus-maven-repository-index.gz?

In the folder .m2\repository.cache\m2e\1.8.0\33b5073b9c3fc53d62eb8dc83e442c3d\ I have three files: nexus-maven-repository-index.gz (360 MB), nexus-maven-repository-index.properties (180 B) and chunks.lst (0B). No nexus-maven-repository-index.zip.

I have searched for solution on the Stackoverlow, tried lots of things, made some improvements on this issue (which was even worse than now), but did not solve it.

答: The log message is misleading.  Nexus will try to download that file if the other index files fail to download.  So you'll see that line if it can't download the .gz files.</p>

Body:
I am using Eclipse Oxygen, and I have installed Nexus OSS Repository Manager. At Window->Preferences->Maven I have checked Download repository index updates on startup.

On startup Eclipse is trying to updated index for Nexus and it takes a while. But after that I am getting an error saying that it is unable to update index for nexus.

From the log I am extracting relevant lines:

!ENTRY org.eclipse.m2e.logback.appender 4 0 2017-07-04 10:55:22.312
!MESSAGE Unable to update index for nexus|http://localhost:8081/nexus/content/groups/public/: .m2\repository\.cache\m2e\1.8.0\33b5073b9c3fc53d62eb8dc83e442c3d\nexus-maven-repository-index.zip (The system cannot find the file specified)
!STACK 0
java.io.FileNotFoundException: .m2\repository\.cache\m2e\1.8.0\33b5073b9c3fc53d62eb8dc83e442c3d\nexus-maven-repository-index.zip (The system cannot find the file specified)...

When I try to start new Maven project and choose Nexus Indexer as the Catalog I am getting the error message: No archetypes currently available. The archetype list will refresh when the indexes finish updating.

I am interested in why is Eclipse looking for nexus-maven-repository-index.zip instead of nexus-maven-repository-index.gz?

In the folder .m2\repository.cache\m2e\1.8.0\33b5073b9c3fc53d62eb8dc83e442c3d\ I have three files: nexus-maven-repository-index.gz (360 MB), nexus-maven-repository-index.properties (180 B) and chunks.lst (0B). No nexus-maven-repository-index.zip.

I have searched for solution on the Stackoverlow, tried lots of things, made some improvements on this issue (which was even worse than now), but did not solve it.


问:
auto number of line in excel formula to prevent manual edit
I have this function on each line:

```<code>=SUMIF(B1:B60000;A1;C1:C60000)
=SUMIF(B1:B60000;A2;C1:C60000)
=SUMIF(B1:B60000;A3;C1:C60000)
</code>```

As you can see just A1, A2, A3,etc. are changing according to the same number of line (auto number of each line).
Any idea how can I replace "A1, A2, A3, ..." in smarter way to prevent manual edit of this value on every cell on each line?

答:
Type this in first row:

```<code>=SUMIF($B$1:$B$60000;A1;$C$1:$C$60000)
</code>```

Then fill down the column or copy paste.

This makes all other range "absolute" (dont change when copy/paste to another place) but only A1 is relative, so it changes relatively with copy/paste.

Body:
I have this function on each line:

=SUMIF(B1:B60000;A1;C1:C60000)
=SUMIF(B1:B60000;A2;C1:C60000)
=SUMIF(B1:B60000;A3;C1:C60000)

As you can see just A1, A2, A3,etc. are changing according to the same number of line (auto number of each line).
Any idea how can I replace "A1, A2, A3, ..." in smarter way to prevent manual edit of this value on every cell on each line?

Body:
Type this in first row:

=SUMIF($B$1:$B$60000;A1;$C$1:$C$60000)

Then fill down the column or copy paste.

This makes all other range "absolute" (dont change when copy/paste to another place) but only A1 is relative, so it changes relatively with copy/paste.


问:
Pigeon function: where to insert x into a sorted list
Suppose I have a sorted list of things

```<code>{thing1, thing2, thing3, ...}
</code>```

and a binary comparison function that says whether one thing should come before another in that sort order.  (I say "things" because they need not be numbers; they can be arbitrary data structures.)

I now seek a function that takes

a sorted list of things,

a comparison function, and

a thing

and returns the first pair of adjacent things in the list that the new thing should be inserted between.
That is, return the first adjacent pair {a,b} such that comp(a,x) and comp(x,b) are true, where comp() is the comparison function.

For example,

```<code>pigeon[{1,3,5,7}, Less, 4]
</code>```

should return

```<code>{3,5}
</code>```

(EDIT: If the given thing is less than the first element, a, of the list, then return {Null, a}.  Likewise, if it's greater than the last element, z, then return {z, Null}.  Additionally, we need to either assume that the comparison function returns true for two identical elements (ie, it's like LessEqual rather than Less) or that the list of things doesn't contain the thing being pigeoned.  Thanks to High Performance Mark for catching that!)

My first thought was to use Split and then take the Last and First, respectively, of the resulting two sublists.
I'll post that as an answer (or feel free to beat me to it) but I imagine there's a more efficient or elegant way.

答:
Here's another binary search answer:

```<code>(* Helper for pigeon. Additional arguments a and b give current bounds on the
   indices of the pigeonhole. *)
pigeon0[l_, f_, x_, a_, b_] := Which[
  b-a==1,                    {l[[a]], l[[b]]},
  f[x, l[[Floor[(a+b)/2]]]], pigeon0[l, f, x, a, Floor[(a+b)/2]],
  True,                      pigeon0[l, f, x, Floor[(a+b)/2], b]]

pigeon[l_, f_, x_] := Which[
  f[x, First@l],                 {Null, First@l},
  f[Last@l, x] && !f[x, Last@l], {Last@l, Null},
  True,                          pigeon0[l, f, x, 1, Length@l]]
</code>```

I tried it like this:

```<code>> l = Sort@RandomReal[{0,1}, {10^6}];
> pigeon[l, LessEqual, .5]
{0.4999991874459364, 0.5000000938493356}
</code>```

That matches my other answer (the one with Select) but is much faster.

Other examples:

```<code>> pigeon[{1,3,5,7}, LessEqual, 4]
{3, 5}

> pigeon[{1,3,5,7}, LessEqual, 0]
{Null, 1}

> pigeon[{1,3,5,7}, LessEqual, 9]
{7, Null}
</code>```

Body:
Suppose I have a sorted list of things

{thing1, thing2, thing3, ...}

and a binary comparison function that says whether one thing should come before another in that sort order.  (I say "things" because they need not be numbers; they can be arbitrary data structures.)

I now seek a function that takes

a sorted list of things,

a comparison function, and

a thing

and returns the first pair of adjacent things in the list that the new thing should be inserted between.
That is, return the first adjacent pair {a,b} such that comp(a,x) and comp(x,b) are true, where comp() is the comparison function.

For example,

pigeon[{1,3,5,7}, Less, 4]

should return

{3,5}

(EDIT: If the given thing is less than the first element, a, of the list, then return {Null, a}.  Likewise, if it's greater than the last element, z, then return {z, Null}.  Additionally, we need to either assume that the comparison function returns true for two identical elements (ie, it's like LessEqual rather than Less) or that the list of things doesn't contain the thing being pigeoned.  Thanks to High Performance Mark for catching that!)

My first thought was to use Split and then take the Last and First, respectively, of the resulting two sublists.
I'll post that as an answer (or feel free to beat me to it) but I imagine there's a more efficient or elegant way.

Body:
Here's another binary search answer:

(* Helper for pigeon. Additional arguments a and b give current bounds on the
   indices of the pigeonhole. *)
pigeon0[l_, f_, x_, a_, b_] := Which[
  b-a==1,                    {l[[a]], l[[b]]},
  f[x, l[[Floor[(a+b)/2]]]], pigeon0[l, f, x, a, Floor[(a+b)/2]],
  True,                      pigeon0[l, f, x, Floor[(a+b)/2], b]]

pigeon[l_, f_, x_] := Which[
  f[x, First@l],                 {Null, First@l},
  f[Last@l, x] && !f[x, Last@l], {Last@l, Null},
  True,                          pigeon0[l, f, x, 1, Length@l]]

I tried it like this:

> l = Sort@RandomReal[{0,1}, {10^6}];
> pigeon[l, LessEqual, .5]
{0.4999991874459364, 0.5000000938493356}

That matches my other answer (the one with Select) but is much faster.

Other examples:

> pigeon[{1,3,5,7}, LessEqual, 4]
{3, 5}

> pigeon[{1,3,5,7}, LessEqual, 0]
{Null, 1}

> pigeon[{1,3,5,7}, LessEqual, 9]
{7, Null}


问:
valgrind definitely lost block calling function
I have a problem figuring out why I get definitely lost error in following code. I have changed return 0 to exit (0) in main function but it does not help.

```<code>struct s* function(int K,struct graph *G,int c){
    uint32_t *a;
    a=(uint32_t*)calloc(K+2,sizeof(uint32_t));
    int *b;
    b=(uint32_t*)calloc(K+2,sizeof(uint32_t));
    return s;
}

int main(int argc, char *argv[])
{
    struct S* s=function(K,Gprime,capacity);
    return 0;
}
</code>```

and Below you can see the S structure code:

```<code>struct S{
    int *S;
    uint32_t *Scount;
};

struct S* Sp(int s,int k){
    struct S* sz =malloc(sizeof (struct S));
    sz->S = (int*)calloc(s+1, sizeof(int));
    sz->scount=(uint32_t*)calloc(k+1,sizeof(uint32_t));
    return sz;
}
</code>```

and here is the valgrind error :

```<code>==5343== 680 bytes in 5 blocks are definitely lost in loss record 10 of 52
==5343==    at 0x4C272B8: calloc (vg_replace_malloc.c:566)
==5343==    by 0x40106B: function (reflowk.c:3)
==5343==    by 0x402BB0: main (reflowk.c:9)
</code>```

答: You have to call free() to free the memory reserved by malloc and calloc after you have finished using that memory.

Body:
I have a problem figuring out why I get definitely lost error in following code. I have changed return 0 to exit (0) in main function but it does not help.

struct s* function(int K,struct graph *G,int c){
    uint32_t *a;
    a=(uint32_t*)calloc(K+2,sizeof(uint32_t));
    int *b;
    b=(uint32_t*)calloc(K+2,sizeof(uint32_t));
    return s;
}

int main(int argc, char *argv[])
{
    struct S* s=function(K,Gprime,capacity);
    return 0;
}

and Below you can see the S structure code:

struct S{
    int *S;
    uint32_t *Scount;
};

struct S* Sp(int s,int k){
    struct S* sz =malloc(sizeof (struct S));
    sz->S = (int*)calloc(s+1, sizeof(int));
    sz->scount=(uint32_t*)calloc(k+1,sizeof(uint32_t));
    return sz;
}

and here is the valgrind error :

==5343== 680 bytes in 5 blocks are definitely lost in loss record 10 of 52
==5343==    at 0x4C272B8: calloc (vg_replace_malloc.c:566)
==5343==    by 0x40106B: function (reflowk.c:3)
==5343==    by 0x402BB0: main (reflowk.c:9)


答:
It sounds like you're looking for this. $ in front of a column letter or row acts as an anchor so it does not change. So don't put a $ in front of where you want to row to change.

```<code>=SUMIF($B$1:$B$60000;$A1;$C$1:$C$60000)
</code>```

If you do not need to copy this formula along a row, you can use this:

```<code>=SUMIF(B$1:B$60000;A1;C$1:$C$60000)
</code>```

Title: auto number of line in excel formula to prevent manual edit

Body:
It sounds like you're looking for this. $ in front of a column letter or row acts as an anchor so it does not change. So don't put a $ in front of where you want to row to change.

=SUMIF($B$1:$B$60000;$A1;$C$1:$C$60000)

If you do not need to copy this formula along a row, you can use this:

=SUMIF(B$1:B$60000;A1;C$1:$C$60000)


问:
Is it possible to use bash to search for a certain phrase on a website?
I was just curious if this was possible. I have tried googling it, but nothing seems to show up. I'd also rather not download the site beforehand and just through the html file that way.</p>

答:
Thats easy enough</p>

```<code> curl https://stackoverflow.com/questions/44927008/is-it-possible-to-use-bash-to-search-for-a-certain-phrase-on-a-website | grep possible
</code>```

Body:
Thats easy enough

 curl https://stackoverflow.com/questions/44927008/is-it-possible-to-use-bash-to-search-for-a-certain-phrase-on-a-website | grep possible


Title: How to get previous two years max value in R

Body:
Hi I have data frame as

How to create column max_value with max from last 2 years max value

dt <-
structure(list(Name = c("A", "A", "A", "A", "A", "A", "A", "B",
"B", "B", "B", "B", "B"), year = c(2012L, 2012L, 2013L, 2014L,
2015L, 2016L, 2017L, 2012L, 2013L, 2013L, 2014L, 2015L, 2016L
), value = c(22L, 99L, 12L, 1L, 23L, 40L, 12L, 12L, 33L, 40L,
NA, 20L, 20L), max_value = c(NA, NA, 99L, 99L, 12L, 23L, 40L,
NA, 12L, 12L, 40L, 40L, 20L)), .Names = c("Name", "year", "value",
"max_value"), row.names = c(NA, -13L), class = c("data.table",
"data.frame"))

Name   year   value   *max_value*
A      2012    22        NA
A      2012    99        NA
A      2013    12        99
A      2014    01        99
A      2015    23        12
A      2016    40        23
A      2017    12        40
B      2012    12        NA
B      2013    33        12
B      2013    40        12
B      2014    NA        40
B      2015    20        40
B      2016    20        20

Thanks in advance

Body:
Use by:

> by(dat$value, dat$year, function(x) max(x))
dat$year: 2012
[1] 99
------------------------------------------------------------
dat$year: 2013
[1] 40
------------------------------------------------------------
dat$year: 2014
[1] NA
------------------------------------------------------------
dat$year: 2015
[1] 23
------------------------------------------------------------
dat$year: 2016
[1] 40
------------------------------------------------------------
dat$year: 2017
[1] 12

EDIT: Misunderstood the question at first. This should be what you want:

Assign the results to a data.frame:

> dat1=by(dat$value, dat$year, function(x) max(x))
> data.frame("max"=dat1[1:length(dat1)])
     max
2012  99
2013  40
2014  NA
2015  23
2016  40
2017  12

Make a new data frame to hold biannual maximum and loop to compare years:

bi_max=data.frame("max"=nrow(dat_max))
for(i in 1:nrow(dat_max)){
  bi_max[i,]=max(dat_max$max[i], dat_max$max[i-1], na.rm=T)
}
rownames(bi_max)=rownames(dat_max)

The final result:

> bi_max
     max
2012  99
2013  99
2014  40
2015  23
2016  40
2017  40


问:
ionic 2 application long loading time
I have developed ionic 2 application but the main issue i am facing is the load time on start of application it takes minutes to load application. I am using limited plugins but still facing the issue also a white screen is shown after splash screen manually hides.</p>

答: Add --prod when you build the app. It will minify css and js files.</p>

Title: ionic 2 application long loading time


问:
Remove DIV dynamically with JQuery
i have a problem to reference an identifier of a DIV. I allow to add a div with a text field and a button to delete the text field, and i set a id to the DIV like an array with this code:

```<code>$('#aggiungi').on('click',function () {
        $count ++;
        $('#corsi').append(
            '<div class="form-group row" id="corso['+$count+']>' +
                '<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
                '<div class="col-sm-10 form-inline">' +
                    '<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
                    '<a class="btn btn-default" id="eliminacorso['+$count+']" aria-label="Elimina">' +
                        '<i class="fa fa-times" aria-hidden="true"></i>' +
                    '</a>' +
                '</div>' +
            '</div>' +
        '');
    });
</code>```

So.. if i press on the botton at the at the side of the text area, i'll call a function that will remove it.
The skeleton of the function is the follow:

```<code>$('#eliminacorso[]').on('click', function() {
  $count --;
  $('#corso[]').remove();
});
</code>```

So my ask is: How can i insert between the square brackets the right identifier of the div?

答:
Try below code.It may help you

var $count =0
$('#aggiungi').on('click',function () {
        $count ++;
        $('#corsi').append(
            '
' +
                'Corso ' + $count +'' +
                '
' +
                    '<input type="text" class="form-control" id="corso" name="corso_'+ $count + '"/>' +
                    '' +
                        'Test' +
                    '' +
                '
' +
            '
' +
        '');
    });

    function remove(aRemove){
    console.log(aRemove);
    var divid = aRemove.id.replace("eliminacorso_","corso_");
    $("#" + divid).remove();
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="aggiungi"> Click ME </button>
<div id="corsi">
</div></code>```

Title: Remove DIV dynamically with JQuery

Body:
i have a problem to reference an identifier of a DIV. I allow to add a div with a text field and a button to delete the text field, and i set a id to the DIV like an array with this code:

$('#aggiungi').on('click',function () {
        $count ++;
        $('#corsi').append(
            '
' +
                'Corso ' + $count +'' +
                '
' +
                    '<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
                    '' +
                        '' +
                    '' +
                '
' +
            '
' +
        '');
    });

So.. if i press on the botton at the at the side of the text area, i'll call a function that will remove it.
The skeleton of the function is the follow:

$('#eliminacorso[]').on('click', function() {
  $count --;
  $('#corso[]').remove();
});

So my ask is: How can i insert between the square brackets the right identifier of the div?

Body:
Try below code.It may help you

var $count =0
$('#aggiungi').on('click',function () {
        $count ++;
        $('#corsi').append(
            '<div class="form-group row" id="corso_'+$count+'">' +
                '<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
                '<div class="col-sm-10 form-inline">' +
                    '<input type="text" class="form-control" id="corso" name="corso_'+ $count + '"/>' +
                    '<a class="btn btn-default" id="eliminacorso_'+$count+'" aria-label="Elimina" onclick="remove(this);">' +
                        'Test' +
                    '</a>' +
                '</div>' +
            '</div>' +
        '');
    });

    function remove(aRemove){
    console.log(aRemove);
    var divid = aRemove.id.replace("eliminacorso_","corso_");
    $("#" + divid).remove();
    }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="aggiungi"> Click ME </button>
<div id="corsi">
</div>


答:
In your apple account go to Certificates, Identifiers & Profiles section.You can see Keys section in left side category.

Click Keys->All, Now you can see list of keys.

Click your key which you created for firebase APNS auth key.it will show prompt it shows Key ID:

Title: firebase asking for key id when activating for iOS app

Body: What does the key id mean? Please help me, I don't know what to enter in there.


问:
Is it possible to show multiple times the same queryset on template?
This is an odd question but I'd like to be able to show the same queryset multiple times on my template using different {% for loops %}, I'm trying to avoid copy pasting each {% for loops %}.

Let's say I have my views.py like this :

```<code>...
    chicken = Chicken.objects.filter(id=1)
    return render(request, 'chicken.html', {'chicken':chicken}
</code>```

chicken.html : the example below is the one I'm avoiding.

```<code><!-- {{ egg }} has the same value everywhere -->

{% for egg in chicken %} <!-- has a different index than other loops -->
    <p id="egg_1">{{egg}}</p>
{% endfor %}

{% for egg in chicken %}
    <p id="egg_2">{{egg}}</p>
{% endfor %}

{% for egg in chicken %}
    <p id="egg_3">{{egg}}</p>
{% endfor %}

...x52...
</code>```

Is there a way to automatise this while having a different index on each loop ?

I'm searching for something like this :

```<code>{% for chicken x52 %}
    {% for egg in chicken %}
        <p id="egg_index">{{egg}}</p> <!-- each with different index -->
    {% endfor %}
{% endfor %}
</code>```

答:
For the example you have given, you could add a variable loops to the context:

```<code>chicken = Chicken.objects.filter(id=1)
loops = range(1, 53)
return render(request, 'chicken.html', {'chicken':chicken, 'loops': loops}
</code>```

Then loop through loops in the template:

```<code>{% for loop in loops %}
  {% for egg in chicken %} <!-- has a different index than other loops -->
    <p id="egg_{{ loop }}">{{egg}}</p>
  {% endfor %}
{% endfor %}
</code>```

If you don't want to add a variable to the context, there are some different approaches suggested on this question, some hackier than others.

Body:
This is an odd question but I'd like to be able to show the same queryset multiple times on my template using different {% for loops %}, I'm trying to avoid copy pasting each {% for loops %}.

Let's say I have my views.py like this :

...
    chicken = Chicken.objects.filter(id=1)
    return render(request, 'chicken.html', {'chicken':chicken}

chicken.html : the example below is the one I'm avoiding.

{% for egg in chicken %}

{{egg}}

{% endfor %}

{% for egg in chicken %}

{{egg}}

{% endfor %}

{% for egg in chicken %}

{{egg}}

{% endfor %}

...x52...

Is there a way to automatise this while having a different index on each loop ?

I'm searching for something like this :

{% for chicken x52 %}
    {% for egg in chicken %}

{{egg}}

    {% endfor %}
{% endfor %}

Body:
For the example you have given, you could add a variable loops to the context:

chicken = Chicken.objects.filter(id=1)
loops = range(1, 53)
return render(request, 'chicken.html', {'chicken':chicken, 'loops': loops}

Then loop through loops in the template:

{% for loop in loops %}
  {% for egg in chicken %} <!-- has a different index than other loops -->
    <p id="egg_{{ loop }}">{{egg}}</p>
  {% endfor %}
{% endfor %}

If you don't want to add a variable to the context, there are some different approaches suggested on this question, some hackier than others.


问:
Why i can not change text view value in fragment?
I'm new to android, I wrote a simple app to learn fragments. I created a text view:

```<code><TextView
        android:id="@+id/behzad"
        android:text="behzad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</code>```

In fragment I wrote this simple method:

```<code>public void setTest(){

        TextView text=(TextView) FiveView.findViewById(R.id.behzad);
        text.setText("hahaha");
        Toast.makeText(getActivity().getBaseContext(), "ok", Toast.LENGTH_SHORT).show();
    }
</code>```

I call that method in activity:

```<code>Fragment frag=adapter.getItem(4);
        ((FiveFragment)frag).setTest();
</code>```

I get the ok message from toast but the fragment's text view does not show hahaha

Why the text view's value has not changed? This is my code

答: Make your TextView object static and try again.</p>

Body:
I'm new to android, I wrote a simple app to learn fragments. I created a text view:

<TextView
        android:id="@+id/behzad"
        android:text="behzad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

In fragment I wrote this simple method:

public void setTest(){

        TextView text=(TextView) FiveView.findViewById(R.id.behzad);
        text.setText("hahaha");
        Toast.makeText(getActivity().getBaseContext(), "ok", Toast.LENGTH_SHORT).show();
    }

I call that method in activity:

Fragment frag=adapter.getItem(4);
        ((FiveFragment)frag).setTest();

I get the ok message from toast but the fragment's text view does not show hahaha

Why the text view's value has not changed? This is my code


问:
iOS Documents Directory expand tilde in path method
Just got a -1 for my answer on how to get the documents directory. I always do it like this:

```<code>NSString *documentsPath = [@"~/Documents" stringByExpandingTildeInPath];
</code>```

And it always works as I expect it to. Are there any real underwater rocks with this method?

答:
Right method to call: NSSearchPathForDirectoriesInDomains()

As Apple documentation states:

Creates a list of path strings for the specified directories in the
  specified domains. The list is in the order in which you should search
  the directories. If expandTilde is YES, tildes are expanded as
  described in stringByExpandingTildeInPath.

Example:

NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)

Body:
Just got a -1 for my answer on how to get the documents directory. I always do it like this:

NSString *documentsPath = [@"~/Documents" stringByExpandingTildeInPath];

And it always works as I expect it to. Are there any real underwater rocks with this method?


问:
Custom interface in Java Lambda expression
I have a method from library, which look like this:

```<code><T> T invoke(K key, EntryProcessor<K, V, T> entryProcessor, Object... arguments);
</code>```

And EntryProcessor interface has a single method definition:

```<code>T process(MutableEntry<K, V> entry, Object... arguments) throws EntryProcessorException;
</code>```

Unfortunately for my use case I need EntryProcessor with Serializable.

One solution is to make a new class implementing both EntryProcessor and Serializable, in that case I would have to create a different class for each different use case.

Normally, without Serializable, I can call invoke method as a lambda, which saves me from creating pack of specialized classes.

```<code>foo.invoke(1L, (entry, arguments) -> {
    ...
    return null;
});
</code>```

Is there a way to extend this lambda with Serializable interface?

答:
how about this?</p>

```<code>Object[] arguments = new Object[0];
EntryProcessor<Long, String, Integer> it;

it = (EntryProcessor<Long, String, Integer> & Serializable) (entry, args) -> 1;

invoke(1L, it, arguments);
</code>```

Body:
I have a method from library, which look like this:

<T> T invoke(K key, EntryProcessor<K, V, T> entryProcessor, Object... arguments);

And EntryProcessor interface has a single method definition:

T process(MutableEntry<K, V> entry, Object... arguments) throws EntryProcessorException;

Unfortunately for my use case I need EntryProcessor with Serializable.

One solution is to make a new class implementing both EntryProcessor and Serializable, in that case I would have to create a different class for each different use case.

Normally, without Serializable, I can call invoke method as a lambda, which saves me from creating pack of specialized classes.

foo.invoke(1L, (entry, arguments) -> {
    ...
    return null;
});

Is there a way to extend this lambda with Serializable interface?

Body:
how about this?

Object[] arguments = new Object[0];
EntryProcessor<Long, String, Integer> it;

it = (EntryProcessor<Long, String, Integer> & Serializable) (entry, args) -> 1;

invoke(1L, it, arguments);


问:
DataTables Server Side Individual Column Filtering
I was hoping someone can help me with this. I have been running myself crazy with this.

I have a situation where I load the DataTables grid (awesome piece by the way!) and all is great. Then I go to search and I run into problems. The data being populated in the grid is coming from two different database tables (which is fine) but when someone executes a search I have no way of knowing where to go and get the data. I would need to know what criteria the search is about (i.e. title or contact). I see what when the search is called from the server via the default search box there are variables like "sSearch_0" which are all unset, how do those get set?

Here is the initialization code for the table:

```<code>oTable = $('#example').dataTable({
"bJQueryUI": true,
"bFilter": true,
"sPaginationType": "full_numbers",
"bPaginate " : true,
"bServerSide" : true,
"sAjaxSource" : "php/tabledata.php",
"aoColumnDefs": [
     { "bSortable": false, "aTargets": [ 0,6,8 ] },
 { "sClass": "tdCenter", "aTargets": [ 0,1,2,3,4,5,6,7,8 ] }
     ],
"fnServerData": function ( sSource, aoData, fnCallback ) {
aoData.push( { "name": "userid", "value": userid } );
$.getJSON( sSource, aoData, function (json) {
fnCallback(json)
});
}
</code>```

});

I have looked into options for adding data to the "fnServerData " and actually use that for the first initialization server call but am unsure how to use that for a subsequent server call. I have tried to use "fnFilter" but I do not see that executing a server call for more data. At this point I do not see any other way to execute a server call besides the default search box and I see some way of knowing which column the search is for.

Can someone help me here and point me in the right direction?

答:
If you are getting data from the server for the DataTables plugin, you have to set bServerSide to true, set the sAjaxSource to the appropriate URL, and ideally configure fnServerData if you need to do any callbacks.

If you use server-side processing, all sorting, filtering, and paging needs to be handled by you on the server.  If you configure DataTables correctly, it will request data from the server any time there is a paging, filtering, or sorting event.

DataTables server-side API documentation

PHP example of server-side processing

Body:
I was hoping someone can help me with this. I have been running myself crazy with this.

I have a situation where I load the DataTables grid (awesome piece by the way!) and all is great. Then I go to search and I run into problems. The data being populated in the grid is coming from two different database tables (which is fine) but when someone executes a search I have no way of knowing where to go and get the data. I would need to know what criteria the search is about (i.e. title or contact). I see what when the search is called from the server via the default search box there are variables like "sSearch_0" which are all unset, how do those get set?

Here is the initialization code for the table:

oTable = $('#example').dataTable({
"bJQueryUI": true,
"bFilter": true,
"sPaginationType": "full_numbers",
"bPaginate " : true,
"bServerSide" : true,
"sAjaxSource" : "php/tabledata.php",
"aoColumnDefs": [
     { "bSortable": false, "aTargets": [ 0,6,8 ] },
 { "sClass": "tdCenter", "aTargets": [ 0,1,2,3,4,5,6,7,8 ] }
     ],
"fnServerData": function ( sSource, aoData, fnCallback ) {
aoData.push( { "name": "userid", "value": userid } );
$.getJSON( sSource, aoData, function (json) {
fnCallback(json)
});
}

});

I have looked into options for adding data to the "fnServerData " and actually use that for the first initialization server call but am unsure how to use that for a subsequent server call. I have tried to use "fnFilter" but I do not see that executing a server call for more data. At this point I do not see any other way to execute a server call besides the default search box and I see some way of knowing which column the search is for.

Can someone help me here and point me in the right direction?


问:
How to check user based events on fabric
Our requirement is for specific user we need to check what events he performed.

Lets say for user John we need to check if he able to find out filter feature from app etc.

On Fabric I can see its shows event and unique users, but its not showing their username, userid etc.

So is there any way to do this?

Thanks.

答: Mike from Fabric here. With the Fabric dashboard, there is not a way to track a user across crashes and events. You can however, add custom logs, keys and user identifiers to exceptions or logged errors and can then search on those values. </p>


问:
In Maven, how can I clean external dirs on dev-build but keep default clean behaviour on any build?
This is my approach, but it doesn't work. In fact the plugin seems to ignore filesets when used inside execution tag.

```<code><plugin>
    <artifactId>maven-clean-plugin</artifactId>
    <version>3.0.0</version>
    <executions>
        <execution><!--Execute only on dev build-->
            <id>clean-dev-files</id>
            <configuration>
                <skip>${not-dev-build}</skip>
                <filesets>
                    <fileset>
                        <directory>/tmp/devdir</directory>
                    </fileset>
                </filesets>
            </configuration>
        </execution>
        <execution><!--Execute always. So that target dir is cleaned on all builds. -->
            <id>default-clean-behaviour</id>
        </execution>
    </executions>
</plugin>
</code>```

答:
I tested your configuration and it works fine for me.

Please try to invoke the maven clean plugin for dev-build using its execution id as shown below:

```<code>mvn clean:clean@clean-dev-files
</code>```

The above command should do the regular clean as well as delete your external directory. For rest of your builds, you can just use

```<code>mvn clean
</code>```

and it should not delete the external directory.

Body:
This is my approach, but it doesn't work. In fact the plugin seems to ignore filesets when used inside execution tag.

<plugin>
    <artifactId>maven-clean-plugin</artifactId>
    <version>3.0.0</version>
    <executions>
        <execution>
            <id>clean-dev-files</id>
            <configuration>
                <skip>${not-dev-build}</skip>
                <filesets>
                    <fileset>
                        <directory>/tmp/devdir</directory>
                    </fileset>
                </filesets>
            </configuration>
        </execution>
        <execution>
            <id>default-clean-behaviour</id>
        </execution>
    </executions>
</plugin>

Body:
I tested your configuration and it works fine for me.

Please try to invoke the maven clean plugin for dev-build using its execution id as shown below:

mvn clean:clean@clean-dev-files

The above command should do the regular clean as well as delete your external directory. For rest of your builds, you can just use

mvn clean

and it should not delete the external directory.


问:
Error in installing packages 'RGtk2' and 'rattle' in R
I tried to install R packages 'rattle' but when I typed

```<code>install.packages('rattle')
</code>```

it returns

```<code>Warning in install.packages :
dependency ‘RGtk2’ is not available
</code>```

So I tried install 'RGtk2',

```<code>install.packages('RGtk2')
</code>```

it returns

```<code>Warning in install.packages :
package ‘RGtk2’ is not available (for R version 3.2.3)
</code>```

My computer is windows 8.1, R version 3.2.3 and I'm working on the R studio.

答:
One possible solution as mentioned is to install an older version of RGtk2. For Windows this might be:

install.packages("https://cran.r-project.org/bin/windows/contrib/3.3/RGtk2_2.20.31.zip",
      repos=NULL)

Further suggestions can be found at https://rattle.togaware.com/rattle-install-troubleshooting.html

Body:
I tried to install R packages 'rattle' but when I typed

install.packages('rattle')

it returns

Warning in install.packages :
dependency ‘RGtk2’ is not available

So I tried install 'RGtk2',

install.packages('RGtk2')

it returns

Warning in install.packages :
package ‘RGtk2’ is not available (for R version 3.2.3)

My computer is windows 8.1, R version 3.2.3 and I'm working on the R studio.


问:
Div on('click') not working inside container
I couldn't find a working answer so I'm asking it:
Whenever I click the selected div, it just doesn't run the function.
Here's the code:

HTML:

```<code><!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>
        <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
    </head>
    <body>
    <textarea class="txt" onfocus="t()"></textarea>
    <div class="extension">
        <div class="dlr">$</div>
    </div>
    </body>
</html>
</code>```

CSS:

```<code>div.extension{
    position:fixed;
    left:0;bottom:0;
    width:100%;height:40px;
    background:darkgray;
}div.extension div{
    position:relative;
    left:0;top:0;
    width:25px;height:36px;
    background:white;
    border:none;border-radius:3px;
    margin:2px 0 0 8px;
    padding:0;
    font-size:1em;
    font-weight:900;
    font-family:arial;
    text-align:center;
    line-height:36px;
}.txt{
    position:absolute;
    left:0;top:0;
    width:100%;height:100%;
    border:none;border-radius:0;
    background:#222;
    color:#ccc;
    font-family:monospace;
}
</code>```

JS:

```<code>$(function(){
  $('div.extension').toggle(false);
  $('.txt').blur(function(){
    $('div.extension').toggle(false);
  });
  $('div.extension div.dlr').on('click',chr);
});
function t(){
  setTimeout(a,1);
}
function a(){
  $('div.extension').css({
    top:(window.innerHeight-40)+'px'
  });
  $('div.extension').toggle(true);
}
function chr(){
  $('.txt').append('$');
  $('.txt').focus();
}
</code>```

And here's the link:
http://www.sololearn.com/app/jquery/playground/Wq4l9mnCO460/

Ps.
$
 also doesn't work.

Update:

I probably found the problem, I just have no idea how to solve it. When I removed the div.dlr from the parent and placed it in the body it worked fine, but I want it to be styled relatively to the parent.

答:
```<code>$( document ).ready(function() {
$('div.extension div.dlr').on('click',chr);
});
</code>```

try this

Body:
I couldn't find a working answer so I'm asking it:
Whenever I click the selected div, it just doesn't run the function.
Here's the code:

HTML:

<!DOCTYPE html>

        <title>Page Title</title>

    <textarea class="txt" onfocus="t()"></textarea>

$

CSS:

div.extension{
    position:fixed;
    left:0;bottom:0;
    width:100%;height:40px;
    background:darkgray;
}div.extension div{
    position:relative;
    left:0;top:0;
    width:25px;height:36px;
    background:white;
    border:none;border-radius:3px;
    margin:2px 0 0 8px;
    padding:0;
    font-size:1em;
    font-weight:900;
    font-family:arial;
    text-align:center;
    line-height:36px;
}.txt{
    position:absolute;
    left:0;top:0;
    width:100%;height:100%;
    border:none;border-radius:0;
    background:#222;
    color:#ccc;
    font-family:monospace;
}

JS:

$(function(){
  $('div.extension').toggle(false);
  $('.txt').blur(function(){
    $('div.extension').toggle(false);
  });
  $('div.extension div.dlr').on('click',chr);
});
function t(){
  setTimeout(a,1);
}
function a(){
  $('div.extension').css({
    top:(window.innerHeight-40)+'px'
  });
  $('div.extension').toggle(true);
}
function chr(){
  $('.txt').append('$');
  $('.txt').focus();
}

And here's the link:
http://www.sololearn.com/app/jquery/playground/Wq4l9mnCO460/

Ps.
$
 also doesn't work.

Update:

I probably found the problem, I just have no idea how to solve it. When I removed the div.dlr from the parent and placed it in the body it worked fine, but I want it to be styled relatively to the parent.

Body:
$( document ).ready(function() {
$('div.extension div.dlr').on('click',chr);
});

try this


问:
ASP.NET MVC ignoring Content-Length?
I've been having some problems with missing post data in ASP.NET MVC which has lead me to investigate how ASP.NET MVC deals with invalid content lengths. I had presumed that a post with a invalid content length should be ignored by MVC.NET but this doesn't seem to be the case.

As an example, try creating a new ASP.NET MVC 2 web application and add this action to the HomeController:

```<code>public ActionResult Test(int userID, string text)
{
    return Content("UserID = " + userID + " Text = " + text);
}
</code>```

Try creating a simple form that posts to the above action, run fiddler and (using "Request Builder") modify the raw data so that some of the form data is missing (e.g. remove the text parameter). Before executing the request, remember to un-tick the "Fix Content-Length header" checkbox under the Request Builder options then set a break point on the code above and execute the custom http request.

I find that the request takes a lot longer than normal (30 seconds or so) but to my amazement is still processed by the controllers action. Does anyone know if this is expected behavior and, if so, what would you recommend to safeguard against invalid content-lengths?

答:
ASP.NET does not ignore the Content-Length request header. Consider the following controller action as an example which simply echoes back the foo parameter:

```<code>[HttpPost]
public ActionResult Index(string foo)
{
    return Content(foo, "text/plain");
}
</code>```

Now let's make a valid POST request to it:

```<code>using (var client = new TcpClient("127.0.0.1", 2555))
using (var stream = client.GetStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
{
    writer.Write(
@"POST /home/index HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: localhost:2555
Content-Length: 10
Connection: close

foo=foobar");
    writer.Flush();
    Console.WriteLine(reader.ReadToEnd());
}
</code>```

As expected this prints the response HTTP headers (which are not important) and in the body we have foobar. Now try reducing the Content-Length header of the request:

```<code>POST /home/index HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: localhost:2555
Content-Length: 5
Connection: close

foo=foobar
</code>```

Which returns a single f in the response body. So as you can see an invalid HTTP request could lead to incorrect parsing of the parameters.

Title: ASP.NET MVC ignoring Content-Length?

Body:
I've been having some problems with missing post data in ASP.NET MVC which has lead me to investigate how ASP.NET MVC deals with invalid content lengths. I had presumed that a post with a invalid content length should be ignored by MVC.NET but this doesn't seem to be the case.

As an example, try creating a new ASP.NET MVC 2 web application and add this action to the HomeController:

public ActionResult Test(int userID, string text)
{
    return Content("UserID = " + userID + " Text = " + text);
}

Try creating a simple form that posts to the above action, run fiddler and (using "Request Builder") modify the raw data so that some of the form data is missing (e.g. remove the text parameter). Before executing the request, remember to un-tick the "Fix Content-Length header" checkbox under the Request Builder options then set a break point on the code above and execute the custom http request.

I find that the request takes a lot longer than normal (30 seconds or so) but to my amazement is still processed by the controllers action. Does anyone know if this is expected behavior and, if so, what would you recommend to safeguard against invalid content-lengths?

Body:
ASP.NET does not ignore the Content-Length request header. Consider the following controller action as an example which simply echoes back the foo parameter:

[HttpPost]
public ActionResult Index(string foo)
{
    return Content(foo, "text/plain");
}

Now let's make a valid POST request to it:

using (var client = new TcpClient("127.0.0.1", 2555))
using (var stream = client.GetStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
{
    writer.Write(
@"POST /home/index HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: localhost:2555
Content-Length: 10
Connection: close

foo=foobar");
    writer.Flush();
    Console.WriteLine(reader.ReadToEnd());
}

As expected this prints the response HTTP headers (which are not important) and in the body we have foobar. Now try reducing the Content-Length header of the request:

POST /home/index HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: localhost:2555
Content-Length: 5
Connection: close

foo=foobar

Which returns a single f in the response body. So as you can see an invalid HTTP request could lead to incorrect parsing of the parameters.


问:
Telerik/ Kendo MVC Grid, Load grid on demand, not on page load
i found a couple examples on how to do this, and none of them are working for me.

Here is my Telerik MVC grid:

```<code>@(Html.Kendo().Grid<PlayerStatsViewModel>()
    .Name("PlayerStats")
    .Columns(columns =>
    {
        columns.Bound(o => o.PlayerId);
        columns.Bound(o => o.FirstName);
    })
    .DataSource(dataSource => dataSource
        .Ajax()
        .Model(model => model.Id(p => p.PlayerId))
    .Read(read => read.Action("PlayerStats_Read_Bound", "Contest").Data("getPlayerId"))
    ).AutoBind(false)
    )
</code>```

Open modal with my grid

I set autobind(false) which prevents page load. After a user clicks a link i open a modal with my grid, and need to pass in a parameter.

```<code>// open modal
$(document).on("click", "#openStatsModal", function () {
    playerId = $(this).data('id'); // get parameter from click
    loadPlayerStats();
});

function getPlayerId() {
    return {
        playerId: playerId
    }
}
</code>```

Make ajax call?
My click method works and i get my player id. Then i try and make my grid call.

```<code>function loadPlayerStats() {
    var grid = $("#PlayerStats").data("playerStats");
    alert(grid); // returns undefined
    //grid.ajaxRequest(); this didnt work either
    grid.dataSource.read(); // Cannot read property 'dataSource' of undefined
}
</code>```

Action method
Never gets called unless i turn off autobind

```<code>public ActionResult PlayerStats_Read_Bound([DataSourceRequest]DataSourceRequest request, int playerId)
        {
            // some code
            return Json(result)
        }
</code>```

答:
Just try:

```<code>var grid = $("#PlayerStats").data("kendoGrid");
</code>```

and then:

```<code>grid.dataSource.read();
</code>```

Body:
i found a couple examples on how to do this, and none of them are working for me.

Here is my Telerik MVC grid:

@(Html.Kendo().Grid<PlayerStatsViewModel>()
    .Name("PlayerStats")
    .Columns(columns =>
    {
        columns.Bound(o => o.PlayerId);
        columns.Bound(o => o.FirstName);
    })
    .DataSource(dataSource => dataSource
        .Ajax()
        .Model(model => model.Id(p => p.PlayerId))
    .Read(read => read.Action("PlayerStats_Read_Bound", "Contest").Data("getPlayerId"))
    ).AutoBind(false)
    )

Open modal with my grid

I set autobind(false) which prevents page load. After a user clicks a link i open a modal with my grid, and need to pass in a parameter.

// open modal
$(document).on("click", "#openStatsModal", function () {
    playerId = $(this).data('id'); // get parameter from click
    loadPlayerStats();
});

function getPlayerId() {
    return {
        playerId: playerId
    }
}

Make ajax call?
My click method works and i get my player id. Then i try and make my grid call.

function loadPlayerStats() {
    var grid = $("#PlayerStats").data("playerStats");
    alert(grid); // returns undefined
    //grid.ajaxRequest(); this didnt work either
    grid.dataSource.read(); // Cannot read property 'dataSource' of undefined
}

Action method
Never gets called unless i turn off autobind

public ActionResult PlayerStats_Read_Bound([DataSourceRequest]DataSourceRequest request, int playerId)
        {
            // some code
            return Json(result)
        }

Body:
Just try:

var grid = $("#PlayerStats").data("kendoGrid");

and then:

grid.dataSource.read();


问:
Unable to integrate OpenCV in android studio
I am trying to integrate openCV in Android studio for my latest project. I followed the following steps:

Imported new module ..\OpenCV-android-sdk\java\

Added dependancy OpenCVLibrary320

Changed compilesdk and targetsdk versions to 23 and buildToolsVersion to 25.0.0 in the build.gradle of OpenCVLibrary320

Copied the contents of ..\OpenCV-android-sdk\sdk\native to app\main\src\jniLibs (After creating a jni folder)

Wrote a snippet of code to test if it was working

But I got the error:

Error:Execution failed for task ':app:compileDebugNdk'.
     Error: Your project contains C++ files but it is not using a supported native build system.
  Consider using CMake or ndk-build integration with the stable Android Gradle plugin:
   https://developer.android.com/studio/projects/add-native-code.html
  or use the experimental plugin:
   https://developer.android.com/studio/build/experimental-plugin.html.

How can I fix this problem?

Note: In step 4, I created the jniLibs folder but it did not show up in the 'Android' view so I had to copy the contents to the jniLibs folder in the 'Project' view.

答:
In gradle add module dependency:

```<code>include ':libraries:opencv'
</code>```

add in build.gradle with this content

```<code>apply plugin: 'android-library'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
    classpath 'com.android.tools.build:gradle:2.3.2'

    }
}

android {
    compileSdkVersion 25
buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 25
        versionCode 1
        versionName "1.0.0"
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            res.srcDirs = ['res']
            aidl.srcDirs = ['src']
        }
    }
}
</code>```

Body:
In gradle add module dependency:

include ':libraries:opencv'

add in build.gradle with this content

apply plugin: 'android-library'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
    classpath 'com.android.tools.build:gradle:2.3.2'

    }
}

android {
    compileSdkVersion 25
buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 25
        versionCode 1
        versionName "1.0.0"
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            res.srcDirs = ['res']
            aidl.srcDirs = ['src']
        }
    }
}