问:
Enable form button when radio button is checked
I am using this line to (try) to enable a disabled submit button by removing a class. There is no result or error shown. Is this the way to go or do I need to write an separate script for this?</p>

```<code><label><input type="checkbox" value="ja" echo onclick=\"document.getElementById(\'submit_delete\').removeClass(\'disabled\')\">Ja ik wil deze toolbox verwijderen</label>';

<button type="button" id="submit_delete" class="btn btn-primary disabled">Opslaan</button>
</code>```

答:
Use can write it like onclick="document.getElementById('submit_delete').classList.remove('disabled')"

.disabled{
  opacity:.5;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label><input type="checkbox" value="ja" onclick="document.getElementById('submit_delete').classList.remove('disabled')">Ja ik wil deze toolbox verwijderen</label>';

<button type="button" id="submit_delete" class="btn btn-primary disabled">Opslaan</button></code>```

Or use external script and call a function on click

function changeButton(event){
  if(event.target.checked){
    document.getElementById('submit_delete').classList.remove('disabled')
  }else{
   document.getElementById('submit_delete').classList.add('disabled')
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.disabled{
      opacity:.5;
    }</code>```

<input type="checkbox" value="ja" onclick="changeButton(event)">Ja ik wil deze toolbox verwijderen';

    <button type="button" id="submit_delete" class="btn btn-primary disabled">Opslaan</button>```

Body:
I am using this line to (try) to enable a disabled submit button by removing a class. There is no result or error shown. Is this the way to go or do I need to write an separate script for this?

<input type="checkbox" value="ja" echo onclick=\"document.getElementById(\'submit_delete\').removeClass(\'disabled\')\">Ja ik wil deze toolbox verwijderen';

<button type="button" id="submit_delete" class="btn btn-primary disabled">Opslaan</button>

Body:
Use can write it like onclick="document.getElementById('submit_delete').classList.remove('disabled')"

.disabled{
  opacity:.5;
}

<label><input type="checkbox" value="ja" onclick="document.getElementById('submit_delete').classList.remove('disabled')">Ja ik wil deze toolbox verwijderen</label>';

<button type="button" id="submit_delete" class="btn btn-primary disabled">Opslaan</button>

Or use external script and call a function on click

function changeButton(event){
  if(event.target.checked){
    document.getElementById('submit_delete').classList.remove('disabled')
  }else{
   document.getElementById('submit_delete').classList.add('disabled')
  }
}

.disabled{
      opacity:.5;
    }

<label><input type="checkbox" value="ja" onclick="changeButton(event)">Ja ik wil deze toolbox verwijderen</label>';

    <button type="button" id="submit_delete" class="btn btn-primary disabled">Opslaan</button>


来源: stackexchange

问:
How to initialize stanfordNLP pipeline once and use many times without initializing again?
I want to initialize stanfordNLP pipelince once and use it many times without initializing it again, to improve the execution time.

Is it possible?

I have code:

```<code>    public static boolean isHeaderMatched(String string) {

    // creates a StanfordCoreNLP object.
    Properties props = new Properties();
    props.put("annotators", "tokenize, ssplit, pos, lemma, ner");

    RedwoodConfiguration.current().clear().apply();
    StanfordCoreNLP pipeline = new StanfordCoreNLP(props);

    Env env = TokenSequencePattern.getNewEnv();
    env.setDefaultStringMatchFlags(NodePattern.CASE_INSENSITIVE);
    env.setDefaultStringPatternFlags(Pattern.CASE_INSENSITIVE);

    Annotation document = new Annotation(string);

    // use the pipeline to annotate the document we created
    pipeline.annotate(document);
    List<CoreMap> sentences = document.get(SentencesAnnotation.class);

    CoreMapExpressionExtractor extractor = CoreMapExpressionExtractor.createExtractorFromFiles(env, "./app/utils/Summarizer/mapping/career_objective.rule", "./app/utils/Summarizer/mapping/personal_info.rule", "./app/utils/Summarizer/mapping/education.rule", "./app/utils/Summarizer/mapping/work_experience.rule", "./app/utils/Summarizer/mapping/certification.rule", "./app/utils/Summarizer/mapping/publication.rule", "./app/utils/Summarizer/mapping/award_achievement.rule", "./app/utils/Summarizer/mapping/hobbies_interest.rule", "./app/utils/Summarizer/mapping/lang_known.rule", "./app/utils/Summarizer/mapping/project_details.rule", "./app/utils/Summarizer/mapping/skill-set.rule", "./app/utils/Summarizer/mapping/misc_header.rule");

    boolean flag = false;
    for (CoreMap sentence : sentences) {
        List<MatchedExpression> matched = extractor.extractExpressions(sentence);
        //System.out.println("Probable Header is : " + matched);
        Set<String> uniqueMatchedKeyWordSet = DocumentParserUtil.removeDuplicate(matched);
        System.out.println("Matched: " + uniqueMatchedKeyWordSet + " and Size of MatchedSet: " + uniqueMatchedKeyWordSet.size());

        //checked if the more than half the no. of word in header(string) is matched
        if ((matched.size() >= uniqueMatchedKeyWordSet.size()) && !matched.isEmpty() && matched.size() >= Math.floorDiv(string.split("\\s").length, 2)) {
                //System.out.println("This is sure a header!");
            flag = true;
        } else {
            flag = false;
        }
  /*for(MatchedExpression phrase: matched){
    System.out.println("matched header type: " + phrase.getValue().get());
  }*/
    }
    return flag;
}
</code>```

I want to execute this part of code to be executed only at first call of above method to load the model.

```<code>    // creates a StanfordCoreNLP object.
    Properties props = new Properties();
    props.put("annotators", "tokenize, ssplit, pos, lemma, ner");

    RedwoodConfiguration.current().clear().apply();
    StanfordCoreNLP pipeline = new StanfordCoreNLP(props);

    Env env = TokenSequencePattern.getNewEnv();
    env.setDefaultStringMatchFlags(NodePattern.CASE_INSENSITIVE);
    env.setDefaultStringPatternFlags(Pattern.CASE_INSENSITIVE);
</code>```

Thanks in advance.

答:
The following is an example of what you can do:

```<code>public class Example {
    private static StanfordCoreNLP pipeline;
    private static Env env;

    static {
        // creates a StanfordCoreNLP object.
        Properties props = new Properties();
        props.put("annotators", "tokenize, ssplit, pos, lemma, ner");

        RedwoodConfiguration.current().clear().apply();
        pipeline = new StanfordCoreNLP(props);

        env = TokenSequencePattern.getNewEnv();
        env.setDefaultStringMatchFlags(NodePattern.CASE_INSENSITIVE);
        env.setDefaultStringPatternFlags(Pattern.CASE_INSENSITIVE);
    }

    public static boolean isHeaderMatched(String string) {
        Annotation document = new Annotation(string);

        // use the pipeline to annotate the document we created
        pipeline.annotate(document);
        List<CoreMap> sentences = document.get(SentencesAnnotation.class);

        CoreMapExpressionExtractor extractor = CoreMapExpressionExtractor.createExtractorFromFiles(env, "./app/utils/Summarizer/mapping/career_objective.rule", "./app/utils/Summarizer/mapping/personal_info.rule", "./app/utils/Summarizer/mapping/education.rule", "./app/utils/Summarizer/mapping/work_experience.rule", "./app/utils/Summarizer/mapping/certification.rule", "./app/utils/Summarizer/mapping/publication.rule", "./app/utils/Summarizer/mapping/award_achievement.rule", "./app/utils/Summarizer/mapping/hobbies_interest.rule", "./app/utils/Summarizer/mapping/lang_known.rule", "./app/utils/Summarizer/mapping/project_details.rule", "./app/utils/Summarizer/mapping/skill-set.rule", "./app/utils/Summarizer/mapping/misc_header.rule");

        boolean flag = false;
        for (CoreMap sentence : sentences) {
            List<MatchedExpression> matched = extractor.extractExpressions(sentence);
            //System.out.println("Probable Header is : " + matched);
            Set<String> uniqueMatchedKeyWordSet = DocumentParserUtil.removeDuplicate(matched);
            System.out.println("Matched: " + uniqueMatchedKeyWordSet + " and Size of MatchedSet: " + uniqueMatchedKeyWordSet.size());

            // checked if the more than half the no. of word in header(string) is matched
            if ((matched.size() >= uniqueMatchedKeyWordSet.size()) && !matched.isEmpty() && matched.size() >= Math.floorDiv(string.split("\\s").length, 2)) {
                flag = true;
            } else {
                flag = false;
            }

        }

        return flag;
    }

}
</code>```

In the above code the static block will be executed when the class is loaded. If you do not wish for this behavior then allow access to an init method, like the following:

```<code>public class Example {
    private static StanfordCoreNLP pipeline;
    private static Env env;

    public static init() {
        // creates a StanfordCoreNLP object.
        Properties props = new Properties();
        props.put("annotators", "tokenize, ssplit, pos, lemma, ner");

        RedwoodConfiguration.current().clear().apply();
        pipeline = new StanfordCoreNLP(props);

        env = TokenSequencePattern.getNewEnv();
        env.setDefaultStringMatchFlags(NodePattern.CASE_INSENSITIVE);
        env.setDefaultStringPatternFlags(Pattern.CASE_INSENSITIVE);
    }

    public static boolean isHeaderMatched(String string) {
        // code left out for brevity
    }

}
</code>```

Which can be called from another class using:

```<code>Example.init();
Example.isHeaderMatched("foobar");
</code>```

While writing this answer I noticed a possible flaw in your logic. The following code may not produce the behavior you desire.

```<code>boolean flag = false;
for (CoreMap sentence : sentences) {
    List<MatchedExpression> matched = extractor.extractExpressions(sentence);
    //System.out.println("Probable Header is : " + matched);
    Set<String> uniqueMatchedKeyWordSet = DocumentParserUtil.removeDuplicate(matched);
    System.out.println("Matched: " + uniqueMatchedKeyWordSet + " and Size of MatchedSet: " + uniqueMatchedKeyWordSet.size());

    // checked if the more than half the no. of word in header(string) is matched
    if ((matched.size() >= uniqueMatchedKeyWordSet.size()) && !matched.isEmpty() && matched.size() >= Math.floorDiv(string.split("\\s").length, 2)) {
        flag = true;
    } else {
        flag = false;
    }

}
</code>```

You're iterating over every CoreMap in the List<CoreMap> collection sentences. Every iteration you set flag to the result of the conditional, this is where the problem lies. The boolean flag will only reflect the result of the last sentence run through the conditional. If you need to know the result for each sentence then you should have a list of booleans to keep track of the results, otherwise remove the loop and just check the last sentence (because that's what your loop is doing anyways).

ContentLicense: CC BY-SA 3.0

Body:
I want to initialize stanfordNLP pipelince once and use it many times without initializing it again, to improve the execution time.

Is it possible?

I have code:

    public static boolean isHeaderMatched(String string) {

    // creates a StanfordCoreNLP object.
    Properties props = new Properties();
    props.put("annotators", "tokenize, ssplit, pos, lemma, ner");

    RedwoodConfiguration.current().clear().apply();
    StanfordCoreNLP pipeline = new StanfordCoreNLP(props);

    Env env = TokenSequencePattern.getNewEnv();
    env.setDefaultStringMatchFlags(NodePattern.CASE_INSENSITIVE);
    env.setDefaultStringPatternFlags(Pattern.CASE_INSENSITIVE);

    Annotation document = new Annotation(string);

    // use the pipeline to annotate the document we created
    pipeline.annotate(document);
    List<CoreMap> sentences = document.get(SentencesAnnotation.class);

    CoreMapExpressionExtractor extractor = CoreMapExpressionExtractor.createExtractorFromFiles(env, "./app/utils/Summarizer/mapping/career_objective.rule", "./app/utils/Summarizer/mapping/personal_info.rule", "./app/utils/Summarizer/mapping/education.rule", "./app/utils/Summarizer/mapping/work_experience.rule", "./app/utils/Summarizer/mapping/certification.rule", "./app/utils/Summarizer/mapping/publication.rule", "./app/utils/Summarizer/mapping/award_achievement.rule", "./app/utils/Summarizer/mapping/hobbies_interest.rule", "./app/utils/Summarizer/mapping/lang_known.rule", "./app/utils/Summarizer/mapping/project_details.rule", "./app/utils/Summarizer/mapping/skill-set.rule", "./app/utils/Summarizer/mapping/misc_header.rule");

    boolean flag = false;
    for (CoreMap sentence : sentences) {
        List<MatchedExpression> matched = extractor.extractExpressions(sentence);
        //System.out.println("Probable Header is : " + matched);
        Set<String> uniqueMatchedKeyWordSet = DocumentParserUtil.removeDuplicate(matched);
        System.out.println("Matched: " + uniqueMatchedKeyWordSet + " and Size of MatchedSet: " + uniqueMatchedKeyWordSet.size());

        //checked if the more than half the no. of word in header(string) is matched
        if ((matched.size() >= uniqueMatchedKeyWordSet.size()) && !matched.isEmpty() && matched.size() >= Math.floorDiv(string.split("\\s").length, 2)) {
                //System.out.println("This is sure a header!");
            flag = true;
        } else {
            flag = false;
        }
  /*for(MatchedExpression phrase: matched){
    System.out.println("matched header type: " + phrase.getValue().get());
  }*/
    }
    return flag;
}

I want to execute this part of code to be executed only at first call of above method to load the model.

    // creates a StanfordCoreNLP object.
    Properties props = new Properties();
    props.put("annotators", "tokenize, ssplit, pos, lemma, ner");

    RedwoodConfiguration.current().clear().apply();
    StanfordCoreNLP pipeline = new StanfordCoreNLP(props);

    Env env = TokenSequencePattern.getNewEnv();
    env.setDefaultStringMatchFlags(NodePattern.CASE_INSENSITIVE);
    env.setDefaultStringPatternFlags(Pattern.CASE_INSENSITIVE);

Thanks in advance.

Body:
The following is an example of what you can do:

public class Example {
    private static StanfordCoreNLP pipeline;
    private static Env env;

    static {
        // creates a StanfordCoreNLP object.
        Properties props = new Properties();
        props.put("annotators", "tokenize, ssplit, pos, lemma, ner");

        RedwoodConfiguration.current().clear().apply();
        pipeline = new StanfordCoreNLP(props);

        env = TokenSequencePattern.getNewEnv();
        env.setDefaultStringMatchFlags(NodePattern.CASE_INSENSITIVE);
        env.setDefaultStringPatternFlags(Pattern.CASE_INSENSITIVE);
    }

    public static boolean isHeaderMatched(String string) {
        Annotation document = new Annotation(string);

        // use the pipeline to annotate the document we created
        pipeline.annotate(document);
        List<CoreMap> sentences = document.get(SentencesAnnotation.class);

        CoreMapExpressionExtractor extractor = CoreMapExpressionExtractor.createExtractorFromFiles(env, "./app/utils/Summarizer/mapping/career_objective.rule", "./app/utils/Summarizer/mapping/personal_info.rule", "./app/utils/Summarizer/mapping/education.rule", "./app/utils/Summarizer/mapping/work_experience.rule", "./app/utils/Summarizer/mapping/certification.rule", "./app/utils/Summarizer/mapping/publication.rule", "./app/utils/Summarizer/mapping/award_achievement.rule", "./app/utils/Summarizer/mapping/hobbies_interest.rule", "./app/utils/Summarizer/mapping/lang_known.rule", "./app/utils/Summarizer/mapping/project_details.rule", "./app/utils/Summarizer/mapping/skill-set.rule", "./app/utils/Summarizer/mapping/misc_header.rule");

        boolean flag = false;
        for (CoreMap sentence : sentences) {
            List<MatchedExpression> matched = extractor.extractExpressions(sentence);
            //System.out.println("Probable Header is : " + matched);
            Set<String> uniqueMatchedKeyWordSet = DocumentParserUtil.removeDuplicate(matched);
            System.out.println("Matched: " + uniqueMatchedKeyWordSet + " and Size of MatchedSet: " + uniqueMatchedKeyWordSet.size());

            // checked if the more than half the no. of word in header(string) is matched
            if ((matched.size() >= uniqueMatchedKeyWordSet.size()) && !matched.isEmpty() && matched.size() >= Math.floorDiv(string.split("\\s").length, 2)) {
                flag = true;
            } else {
                flag = false;
            }

        }

        return flag;
    }

}

In the above code the static block will be executed when the class is loaded. If you do not wish for this behavior then allow access to an init method, like the following:

public class Example {
    private static StanfordCoreNLP pipeline;
    private static Env env;

    public static init() {
        // creates a StanfordCoreNLP object.
        Properties props = new Properties();
        props.put("annotators", "tokenize, ssplit, pos, lemma, ner");

        RedwoodConfiguration.current().clear().apply();
        pipeline = new StanfordCoreNLP(props);

        env = TokenSequencePattern.getNewEnv();
        env.setDefaultStringMatchFlags(NodePattern.CASE_INSENSITIVE);
        env.setDefaultStringPatternFlags(Pattern.CASE_INSENSITIVE);
    }

    public static boolean isHeaderMatched(String string) {
        // code left out for brevity
    }

}

Which can be called from another class using:

Example.init();
Example.isHeaderMatched("foobar");

While writing this answer I noticed a possible flaw in your logic. The following code may not produce the behavior you desire.

boolean flag = false;
for (CoreMap sentence : sentences) {
    List<MatchedExpression> matched = extractor.extractExpressions(sentence);
    //System.out.println("Probable Header is : " + matched);
    Set<String> uniqueMatchedKeyWordSet = DocumentParserUtil.removeDuplicate(matched);
    System.out.println("Matched: " + uniqueMatchedKeyWordSet + " and Size of MatchedSet: " + uniqueMatchedKeyWordSet.size());

    // checked if the more than half the no. of word in header(string) is matched
    if ((matched.size() >= uniqueMatchedKeyWordSet.size()) && !matched.isEmpty() && matched.size() >= Math.floorDiv(string.split("\\s").length, 2)) {
        flag = true;
    } else {
        flag = false;
    }

}

You're iterating over every CoreMap in the List<CoreMap> collection sentences. Every iteration you set flag to the result of the conditional, this is where the problem lies. The boolean flag will only reflect the result of the last sentence run through the conditional. If you need to know the result for each sentence then you should have a list of booleans to keep track of the results, otherwise remove the loop and just check the last sentence (because that's what your loop is doing anyways).


问:
Post a message AFTER the user click the mouse button
I use SetWindowsHookEx to monitor another application. When the user click the mouse in the program I use PostMessage to send a message to the program.

The problem I have is that sometimes my message arrive before WM_LBUTTONUP. How do I ensure that my message will arrive after WM_LBUTTONUP?

I use Gma.UserActivityMonitor for monitoring and following code to send messages:

```<code>HookManager.MouseUp += HookManagerMouseUp;

void HookManagerMouseUp(object sender, MouseEventArgs e)
{
   uint ret;
   uint attachedThredId = GetCurrentThreadId();
   uint attachedProcessId = GetWindowThreadProcessId(ActiveWindow, out ret);
   AttachThreadInputSafe(attachedThredId, attachedProcessId, true);

   PostMessage(ActiveControlInWindow, Message.KeyDown, 'A', 0x1);
   PostMessage(ActiveControlInWindow, Message.KeyUp,   'A', 0xC0010001);

   AttachThreadInputSafe(attachedThredId, attachedProcessId, false);
}
</code>```

I am using PostMessage to send keystrokes is because I want to do it even if host application is not active.

The hook in Gma.UserActivityMonitor is as follows:

```<code>s_MouseDelegate = MouseHookProc;
s_MouseHookHandle = SetWindowsHookEx(
  WH_MOUSE_LL,
  s_MouseDelegate,
  Marshal.GetHINSTANCE(
    Assembly.GetExecutingAssembly().GetModules()[0]),
    0);
</code>```

I use Spy++ to monitor the messages that arrives to the application. When the messages arrives in the right order I get following result:

```<code>S   WM_MOUSEACTIVATE hwndTopLevel:00030A46 nHittest:HTCLIENT uMsg:WM_LBUTTONDOWN
R   WM_MOUSEACTIVATE fuActivate:MA_ACTIVATE
S   WM_KILLFOCUS hwndGetFocus:00020A32
R   WM_KILLFOCUS
S   WM_IME_SETCONTEXT fSet:1 iShow:C000000F
R   WM_IME_SETCONTEXT
S   WM_SETFOCUS hwndLoseFocus:00030A46
R   WM_SETFOCUS
P   WM_LBUTTONDOWN fwKeys:MK_LBUTTON xPos:278 yPos:73
S   WM_ERASEBKGND hdc:0E010DEE
R   WM_ERASEBKGND fErased:True
P   WM_LBUTTONUP fwKeys:0000 xPos:278 yPos:73
S   WM_CAPTURECHANGED hwndNewCapture:00000000
R   WM_CAPTURECHANGED
P   WM_KEYDOWN nVirtKey:VK_OEM_5 cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_KEYUP nVirtKey:VK_OEM_5 cRepeat:1 ScanCode:01 fExtended:0 fAltDown:0 fRepeat:1 fUp:1
P   WM_CHAR chCharCode:'167' (167) cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_KEYDOWN nVirtKey:'2' cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_KEYUP nVirtKey:'2' cRepeat:1 ScanCode:01 fExtended:0 fAltDown:0 fRepeat:1 fUp:1
P   WM_KEYDOWN nVirtKey:'2' cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_KEYUP nVirtKey:'2' cRepeat:1 ScanCode:01 fExtended:0 fAltDown:0 fRepeat:1 fUp:1
P   WM_CHAR chCharCode:'50' (50) cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_CHAR chCharCode:'50' (50) cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
S   WM_KILLFOCUS hwndGetFocus:(null)
R   WM_KILLFOCUS
S   WM_IME_SETCONTEXT fSet:0 iShow:C000000F
R   WM_IME_SETCONTEXT
</code>```

When the messages arrives in the wrong order I get following result (Note that WM_LBUTTONUP arrive after WM_CHAR have been handled):

```<code>S   WM_MOUSEACTIVATE hwndTopLevel:00030A46 nHittest:HTCLIENT uMsg:WM_LBUTTONDOWN
R   WM_MOUSEACTIVATE fuActivate:MA_ACTIVATE
S   WM_KILLFOCUS hwndGetFocus:00020A32
R   WM_KILLFOCUS
S   WM_IME_SETCONTEXT fSet:1 iShow:C000000F
R   WM_IME_SETCONTEXT
S   WM_SETFOCUS hwndLoseFocus:00030A46
R   WM_SETFOCUS
P   WM_LBUTTONDOWN fwKeys:MK_LBUTTON xPos:329 yPos:166
S   WM_ERASEBKGND hdc:1E0117FD
R   WM_ERASEBKGND fErased:True
P   WM_KEYDOWN nVirtKey:VK_OEM_5 cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_KEYUP nVirtKey:VK_OEM_5 cRepeat:1 ScanCode:01 fExtended:0 fAltDown:0 fRepeat:1 fUp:1
P   WM_KEYDOWN nVirtKey:'2' cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_KEYUP nVirtKey:'2' cRepeat:1 ScanCode:01 fExtended:0 fAltDown:0 fRepeat:1 fUp:1
P   WM_KEYDOWN nVirtKey:'2' cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_KEYUP nVirtKey:'2' cRepeat:1 ScanCode:01 fExtended:0 fAltDown:0 fRepeat:1 fUp:1
P   WM_CHAR chCharCode:'167' (167) cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_CHAR chCharCode:'50' (50) cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_CHAR chCharCode:'50' (50) cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_LBUTTONUP fwKeys:0000 xPos:329 yPos:166
S   WM_CAPTURECHANGED hwndNewCapture:00000000
R   WM_CAPTURECHANGED
S   WM_KILLFOCUS hwndGetFocus:(null)
R   WM_KILLFOCUS
S   WM_IME_SETCONTEXT fSet:0 iShow:C000000F
R   WM_IME_SETCONTEXT
</code>```

What I can see it is random when one or the other occurs. If I add a delay before I post the messages, it works. But I don't want to use a delay.

答:
Use a MOUSE_LL hook, and post the message when you receive the WM_*BUTTONUP.

http://msdn.microsoft.com/en-us/library/ms644986(VS.85).aspx

ContentLicense: CC BY-SA 2.5

Body:
I use SetWindowsHookEx to monitor another application. When the user click the mouse in the program I use PostMessage to send a message to the program.

The problem I have is that sometimes my message arrive before WM_LBUTTONUP. How do I ensure that my message will arrive after WM_LBUTTONUP?

I use Gma.UserActivityMonitor for monitoring and following code to send messages:

HookManager.MouseUp += HookManagerMouseUp;

void HookManagerMouseUp(object sender, MouseEventArgs e)
{
   uint ret;
   uint attachedThredId = GetCurrentThreadId();
   uint attachedProcessId = GetWindowThreadProcessId(ActiveWindow, out ret);
   AttachThreadInputSafe(attachedThredId, attachedProcessId, true);

   PostMessage(ActiveControlInWindow, Message.KeyDown, 'A', 0x1);
   PostMessage(ActiveControlInWindow, Message.KeyUp,   'A', 0xC0010001);

   AttachThreadInputSafe(attachedThredId, attachedProcessId, false);
}

I am using PostMessage to send keystrokes is because I want to do it even if host application is not active.

The hook in Gma.UserActivityMonitor is as follows:

s_MouseDelegate = MouseHookProc;
s_MouseHookHandle = SetWindowsHookEx(
  WH_MOUSE_LL,
  s_MouseDelegate,
  Marshal.GetHINSTANCE(
    Assembly.GetExecutingAssembly().GetModules()[0]),
    0);

I use Spy++ to monitor the messages that arrives to the application. When the messages arrives in the right order I get following result:

S   WM_MOUSEACTIVATE hwndTopLevel:00030A46 nHittest:HTCLIENT uMsg:WM_LBUTTONDOWN
R   WM_MOUSEACTIVATE fuActivate:MA_ACTIVATE
S   WM_KILLFOCUS hwndGetFocus:00020A32
R   WM_KILLFOCUS
S   WM_IME_SETCONTEXT fSet:1 iShow:C000000F
R   WM_IME_SETCONTEXT
S   WM_SETFOCUS hwndLoseFocus:00030A46
R   WM_SETFOCUS
P   WM_LBUTTONDOWN fwKeys:MK_LBUTTON xPos:278 yPos:73
S   WM_ERASEBKGND hdc:0E010DEE
R   WM_ERASEBKGND fErased:True
P   WM_LBUTTONUP fwKeys:0000 xPos:278 yPos:73
S   WM_CAPTURECHANGED hwndNewCapture:00000000
R   WM_CAPTURECHANGED
P   WM_KEYDOWN nVirtKey:VK_OEM_5 cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_KEYUP nVirtKey:VK_OEM_5 cRepeat:1 ScanCode:01 fExtended:0 fAltDown:0 fRepeat:1 fUp:1
P   WM_CHAR chCharCode:'167' (167) cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_KEYDOWN nVirtKey:'2' cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_KEYUP nVirtKey:'2' cRepeat:1 ScanCode:01 fExtended:0 fAltDown:0 fRepeat:1 fUp:1
P   WM_KEYDOWN nVirtKey:'2' cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_KEYUP nVirtKey:'2' cRepeat:1 ScanCode:01 fExtended:0 fAltDown:0 fRepeat:1 fUp:1
P   WM_CHAR chCharCode:'50' (50) cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_CHAR chCharCode:'50' (50) cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
S   WM_KILLFOCUS hwndGetFocus:(null)
R   WM_KILLFOCUS
S   WM_IME_SETCONTEXT fSet:0 iShow:C000000F
R   WM_IME_SETCONTEXT

When the messages arrives in the wrong order I get following result (Note that WM_LBUTTONUP arrive after WM_CHAR have been handled):

S   WM_MOUSEACTIVATE hwndTopLevel:00030A46 nHittest:HTCLIENT uMsg:WM_LBUTTONDOWN
R   WM_MOUSEACTIVATE fuActivate:MA_ACTIVATE
S   WM_KILLFOCUS hwndGetFocus:00020A32
R   WM_KILLFOCUS
S   WM_IME_SETCONTEXT fSet:1 iShow:C000000F
R   WM_IME_SETCONTEXT
S   WM_SETFOCUS hwndLoseFocus:00030A46
R   WM_SETFOCUS
P   WM_LBUTTONDOWN fwKeys:MK_LBUTTON xPos:329 yPos:166
S   WM_ERASEBKGND hdc:1E0117FD
R   WM_ERASEBKGND fErased:True
P   WM_KEYDOWN nVirtKey:VK_OEM_5 cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_KEYUP nVirtKey:VK_OEM_5 cRepeat:1 ScanCode:01 fExtended:0 fAltDown:0 fRepeat:1 fUp:1
P   WM_KEYDOWN nVirtKey:'2' cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_KEYUP nVirtKey:'2' cRepeat:1 ScanCode:01 fExtended:0 fAltDown:0 fRepeat:1 fUp:1
P   WM_KEYDOWN nVirtKey:'2' cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_KEYUP nVirtKey:'2' cRepeat:1 ScanCode:01 fExtended:0 fAltDown:0 fRepeat:1 fUp:1
P   WM_CHAR chCharCode:'167' (167) cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_CHAR chCharCode:'50' (50) cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_CHAR chCharCode:'50' (50) cRepeat:1 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P   WM_LBUTTONUP fwKeys:0000 xPos:329 yPos:166
S   WM_CAPTURECHANGED hwndNewCapture:00000000
R   WM_CAPTURECHANGED
S   WM_KILLFOCUS hwndGetFocus:(null)
R   WM_KILLFOCUS
S   WM_IME_SETCONTEXT fSet:0 iShow:C000000F
R   WM_IME_SETCONTEXT

What I can see it is random when one or the other occurs. If I add a delay before I post the messages, it works. But I don't want to use a delay.


问:
How to store multiple return values?
I just came to know that in Python 3.5 we can return multiple values.
So I tried to work out a piece of code that can use this feature , But the problem is that how do I store these multiple values? Kindly refer to the followig code.

```<code>def input1():
    stu=input("Enter Student Name")
    marks=int(input("Enter Student marks"))
    return stu,marks

def assign():
    s=[]
    m=[]
    i=0
    while True:
        #s[i],m[i]=input1()
        a=int(input("0 to exit"))
        i+=1
        if a==0:
            print(s)
            print(m)
            break
</code>```

stu is a string and marks is an integer.
I want to store both the values simultaneously in the arrays s[] and m[].
Just below the while block is the syntax I intended to use, but it obviously doesn't work.

Output:

Enter Student NameR
Enter Student marks45

Traceback (most recent call last):
    File "School_Rank.py", line 19, in <module>
        assign()
    File "School_Rank.py", line 12, in assign
        s[i],m[i]=input1()
    IndexError: list assignment index out of range
```

答:
What you have to do is:

```<code>s_var,m_var=input1()
s.append(s_var)
m.append(m_var)
</code>```

You have a problem assigning a value to an empty list.

Title: How to store multiple return values?

Body:
I just came to know that in Python 3.5 we can return multiple values.
So I tried to work out a piece of code that can use this feature , But the problem is that how do I store these multiple values? Kindly refer to the followig code.

def input1():
    stu=input("Enter Student Name")
    marks=int(input("Enter Student marks"))
    return stu,marks

def assign():
    s=[]
    m=[]
    i=0
    while True:
        #s[i],m[i]=input1()
        a=int(input("0 to exit"))
        i+=1
        if a==0:
            print(s)
            print(m)
            break

stu is a string and marks is an integer.
I want to store both the values simultaneously in the arrays s[] and m[].
Just below the while block is the syntax I intended to use, but it obviously doesn't work.

Output:

Enter Student NameR
Enter Student marks45

Traceback (most recent call last):
    File "School_Rank.py", line 19, in <module>
        assign()
    File "School_Rank.py", line 12, in assign
        s[i],m[i]=input1()
    IndexError: list assignment index out of range

Body:
What you have to do is:

s_var,m_var=input1()
s.append(s_var)
m.append(m_var)

You have a problem assigning a value to an empty list.


问:
How to stack submatrices of a matrix to reduce dimensionality
I couldn't find a good solution for this:

I have a matrix of this size: 60x10x3

And I want to transform it into a matrix of this size: 600x3

Basically I want to stack the 10 matrices with the dimension 60x3 next to each other in the first dimension.

How can I achieve that elegantly in matlab?

答:
Here is a solution that

stack[s] the 10 matrices with the dimension 60x3 next to each other in the first dimension.

```<code>a = rand(60,3,10);
% swap the 2nd and 3rd dimention
b = permute(a,[1,3,2]);
% condense to 2d
c = b(:,:);
% reshape x, y and z seperately so each group of 60 xs/ys/zs appends to the end of the previous group
x=reshape(c(:,1:3:end),[],1);
y=reshape(c(:,2:3:end),[],1);
z=reshape(c(:,3:3:end),[],1);
% condense to one 600*3 matrix
d = [x y z];
</code>```

Body:
Here is a solution that

stack[s] the 10 matrices with the dimension 60x3 next to each other in the first dimension.

a = rand(60,3,10);
% swap the 2nd and 3rd dimention
b = permute(a,[1,3,2]);
% condense to 2d
c = b(:,:);
% reshape x, y and z seperately so each group of 60 xs/ys/zs appends to the end of the previous group
x=reshape(c(:,1:3:end),[],1);
y=reshape(c(:,2:3:end),[],1);
z=reshape(c(:,3:3:end),[],1);
% condense to one 600*3 matrix
d = [x y z];


问:
How do I Encapsulate a WPF ViewModel/View UserControl as a Control
I've built a WPF UserControl View/ViewModel pair:  the view XAML handles the layout and bindings, and the ViewModel handles the logic, in-line with the recommended MVVM pattern.

I would like to be able to re-use this as a control.

How do I hide/encapsulate the ViewModel associated with the view, so that I can use the control as I would a standard control [such as a button] ?

i.e. How do I hide the control's viewmodel ?

答:
depends on how you bind ViewModel class to the control.
if you do like this:

```<code> YourControl()
{
   DataContex = new ViewModel();
}
</code>```

then I don't see any problems. add reference to your control and use it.

Body:
depends on how you bind ViewModel class to the control.
if you do like this:

 YourControl()
{
   DataContex = new ViewModel();
}

then I don't see any problems. add reference to your control and use it.


问:
SQLite Connection string unrecognized C#?
I'm trying to connect to SQLite database but the connection string is not recognized and gives me this error. This database file is in my project folder along with other files and for the copy option, I have "copy always" in the debug folder. The error is this:

"valid parameters: Data Source = ..."

Code is:

```<code>SQLiteConnection con = new SQLiteConnection("Data Source=db.sqlite;version=3;");
</code>```

What could be wrong?

答:
```<code>SQLiteConnection con = new SQLiteConnection("Data Source=" + System.Windows.Forms.Application.StartupPath + "\\db.sqlite;Version=3;");
</code>```

Specify the location of the database in the drive.

Body:
I'm trying to connect to SQLite database but the connection string is not recognized and gives me this error. This database file is in my project folder along with other files and for the copy option, I have "copy always" in the debug folder. The error is this:

"valid parameters: Data Source = ..."

Code is:

SQLiteConnection con = new SQLiteConnection("Data Source=db.sqlite;version=3;");

What could be wrong?

Body:
SQLiteConnection con = new SQLiteConnection("Data Source=" + System.Windows.Forms.Application.StartupPath + "\\db.sqlite;Version=3;");

Specify the location of the database in the drive.


问:
Bootstrap menu styling
I cant for the life of me figure out how to style the bootstrap dropdown menus using CSS.

I can manage to get the background color to change but that's it. The links don't have an underline and the Hover background colour does not change. I haven't even started with the down arrows yet either!! Any advice?

Heres the code im trying:

```<code>#NAV .dropdown-menu { background-color:#273961; border-bottom: 5px solid #CCC;}
#NAV .dropdown-menu>li>a:link { background-color:#273961;}
#NAV .dropdown-menu>li>a:hover{ text-decoration: underline;}
</code>```

答:
Hopefully this helps.

```<code>ul.dropdown-menu {
    border-bottom: 5px solid #CCC;
}

.dropdown-menu li:hover {
    text-decoration: underline;
}
</code>```

I was a little confused what you wanted to do with the background-color of the list items in your dropdown menu.  Here's an example of one way to change the background color when hovering over each link.  Using !important after a CSS attribute might help in some circumstances when you want to override any subsequent rules (but it might not be the BEST way to do this).
I recommend opening up your Chrome dev tools and playing around a bit until you get the desired results. I'm assuming you want to change the background-color of your list items when hovering to a different color than what you specified (#273961) since it is already that color to begin with?

```<code>.dropdown-menu li a:hover {
    background-color: red !important;
}
</code>```

Title: Bootstrap menu styling

Body:
I cant for the life of me figure out how to style the bootstrap dropdown menus using CSS.

I can manage to get the background color to change but that's it. The links don't have an underline and the Hover background colour does not change. I haven't even started with the down arrows yet either!! Any advice?

Heres the code im trying:

#NAV .dropdown-menu { background-color:#273961; border-bottom: 5px solid #CCC;}
#NAV .dropdown-menu>li>a:link { background-color:#273961;}
#NAV .dropdown-menu>li>a:hover{ text-decoration: underline;}

Body:
Hopefully this helps.

ul.dropdown-menu {
    border-bottom: 5px solid #CCC;
}

.dropdown-menu li:hover {
    text-decoration: underline;
}

I was a little confused what you wanted to do with the background-color of the list items in your dropdown menu.  Here's an example of one way to change the background color when hovering over each link.  Using !important after a CSS attribute might help in some circumstances when you want to override any subsequent rules (but it might not be the BEST way to do this).
I recommend opening up your Chrome dev tools and playing around a bit until you get the desired results. I'm assuming you want to change the background-color of your list items when hovering to a different color than what you specified (#273961) since it is already that color to begin with?

.dropdown-menu li a:hover {
    background-color: red !important;
}


问:
Django Rest Framework partial update
I'm trying to implement partial_update with Django Rest Framework but I need some clarification because I'm stuck.

Why do we need to specify partial=True?

In my understanding, we could easily update Demo object inside of partial_update method. What is the purpose of this?

What is inside of serialized variable?

What is inside of serialized variable in partial_update method? Is that a Demo object? What function is called behind the scenes?

How would one finish the implementation here?

Viewset

```<code>class DemoViewSet(viewsets.ModelViewSet):
    serializer_class = DemoSerializer

    def partial_update(self, request, pk=None):
        serialized = DemoSerializer(request.user, data=request.data, partial=True)
        return Response(status=status.HTTP_202_ACCEPTED)
</code>```

Serializer

```<code>class DemoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Demo
        fields = '__all__'

    def update(self, instance, validated_data):
        print 'this - here'
        demo = Demo.objects.get(pk=instance.id)
        Demo.objects.filter(pk=instance.id)\
                           .update(**validated_data)
        return demo
</code>```

答:
You forgot serializer.save()

You can finish it the following way . . .

```<code>class DemoViewSet(viewsets.ModelViewSet):
    serializer_class = DemoSerializer

    def partial_update(self, request, pk=None):
        serializer = DemoSerializer(request.user, data=request.data, partial=True)
        serializer.save()
        serializer.is_valid(raise_exception=True)
        return Response(serializer.data)
</code>```

Also, you shouldn't need to override the update method in the serializer.

Title: Django Rest Framework partial update

Body:
I'm trying to implement partial_update with Django Rest Framework but I need some clarification because I'm stuck.

Why do we need to specify partial=True?

In my understanding, we could easily update Demo object inside of partial_update method. What is the purpose of this?

What is inside of serialized variable?

What is inside of serialized variable in partial_update method? Is that a Demo object? What function is called behind the scenes?

How would one finish the implementation here?

Viewset

class DemoViewSet(viewsets.ModelViewSet):
    serializer_class = DemoSerializer

    def partial_update(self, request, pk=None):
        serialized = DemoSerializer(request.user, data=request.data, partial=True)
        return Response(status=status.HTTP_202_ACCEPTED)

Serializer

class DemoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Demo
        fields = '__all__'

    def update(self, instance, validated_data):
        print 'this - here'
        demo = Demo.objects.get(pk=instance.id)
        Demo.objects.filter(pk=instance.id)\
                           .update(**validated_data)
        return demo

Body:
You forgot serializer.save()

You can finish it the following way . . .

class DemoViewSet(viewsets.ModelViewSet):
    serializer_class = DemoSerializer

    def partial_update(self, request, pk=None):
        serializer = DemoSerializer(request.user, data=request.data, partial=True)
        serializer.save()
        serializer.is_valid(raise_exception=True)
        return Response(serializer.data)

Also, you shouldn't need to override the update method in the serializer.


问:
hdf5: Check to create group
I would like automatically create a group, if a group does not yet exist. I am however not successfull in checking if the group exists.

Failing attempt 1

```<code>#include <iostream>
#include <string>
#include "H5Cpp.h"

int main(void)
{
  H5::H5File file("test.h5",H5F_ACC_TRUNC);

  std::string group_name = "/test";

  H5::Group group = file.createGroup(group_name.c_str());

  if ( !file.attrExists(group_name.c_str()) )
    H5::Group group = file.createGroup(group_name.c_str());

  return 0;
}
</code>```

Compilation with

```<code>$ h5c++ -o test test.cpp
</code>```

Fails because file.attrExists(name) always returns false. For reference, the error occurs at createGroup:

```<code>...

#006: H5L.c line 1733 in H5L_link_cb(): name already exists
  major: Symbol table
  minor: Object already exists
</code>```

Failing attempt 2

```<code>#include <iostream>
#include <string>
#include "H5Cpp.h"

int main(void)
{
  H5::H5File file("test.h5",H5F_ACC_TRUNC);

  std::string group_name = "/test";

  try         { H5::Group group = file.openGroup  (group_name.c_str()); }
  catch (...) { H5::Group group = file.createGroup(group_name.c_str()); }

  return 0;
}
</code>```

Compilation with

```<code>$ h5c++ -o test test.cpp
</code>```

Somehow, the catch is not successful, and an error is produced when openGroup fails:

```<code>...

#005: H5Gloc.c line 385 in H5G_loc_find_cb(): object 'test' doesn't exist
  major: Symbol table
  minor: Object not found
</code>```

答:
Your attempt 1, fails because a H5::Group is not an attribute, so

```<code>if ( !file.attrExists(group_name.c_str()) )
</code>```

does not what you thought it does. AFAIK, there is no simpler way to check for the existence of a group than trying to open it. This leads us to

Your attempt 2 is actually not failing, but works (why did you think otherwise?) Unfortunately, HDF5 spits out a lot of error blurb (in addition to throw an exception), but you can suppress that

```<code>int main(void)
{
  H5::Exception::dontPrint();                             // suppress error messages
  H5::H5File file("test.h5",H5F_ACC_TRUNC);
  std::string group_name = "/test";
  try         {
    H5::Group group = file.openGroup  (group_name.c_str());
    std::cerr<<" TEST: opened group\n";                   // for debugging
  } catch (...) {
    std::cerr<<" TEST: caught something\n";               // for debugging
    H5::Group group = file.createGroup(group_name.c_str());
    std::cerr<<" TEST: created group\n";                  // for debugging
  }
  H5::Group group = file.openGroup  (group_name.c_str()); // for debugging
  std::cerr<<" TEST: opened group\n";                     // for debugging
}
</code>```

generates

TEST: caught something

  TEST: created group

  TEST: opened group

Title: hdf5: Check to create group

Body:
I would like automatically create a group, if a group does not yet exist. I am however not successfull in checking if the group exists.

Failing attempt 1

#include <iostream>
#include <string>
#include "H5Cpp.h"

int main(void)
{
  H5::H5File file("test.h5",H5F_ACC_TRUNC);

  std::string group_name = "/test";

  H5::Group group = file.createGroup(group_name.c_str());

  if ( !file.attrExists(group_name.c_str()) )
    H5::Group group = file.createGroup(group_name.c_str());

  return 0;
}

Compilation with

$ h5c++ -o test test.cpp

Fails because file.attrExists(name) always returns false. For reference, the error occurs at createGroup:

...

#006: H5L.c line 1733 in H5L_link_cb(): name already exists
  major: Symbol table
  minor: Object already exists

Failing attempt 2

#include <iostream>
#include <string>
#include "H5Cpp.h"

int main(void)
{
  H5::H5File file("test.h5",H5F_ACC_TRUNC);

  std::string group_name = "/test";

  try         { H5::Group group = file.openGroup  (group_name.c_str()); }
  catch (...) { H5::Group group = file.createGroup(group_name.c_str()); }

  return 0;
}

Compilation with

$ h5c++ -o test test.cpp

Somehow, the catch is not successful, and an error is produced when openGroup fails:

...

#005: H5Gloc.c line 385 in H5G_loc_find_cb(): object 'test' doesn't exist
  major: Symbol table
  minor: Object not found

Body:
Your attempt 1, fails because a H5::Group is not an attribute, so

if ( !file.attrExists(group_name.c_str()) )

does not what you thought it does. AFAIK, there is no simpler way to check for the existence of a group than trying to open it. This leads us to

Your attempt 2 is actually not failing, but works (why did you think otherwise?) Unfortunately, HDF5 spits out a lot of error blurb (in addition to throw an exception), but you can suppress that

int main(void)
{
  H5::Exception::dontPrint();                             // suppress error messages
  H5::H5File file("test.h5",H5F_ACC_TRUNC);
  std::string group_name = "/test";
  try         {
    H5::Group group = file.openGroup  (group_name.c_str());
    std::cerr<<" TEST: opened group\n";                   // for debugging
  } catch (...) {
    std::cerr<<" TEST: caught something\n";               // for debugging
    H5::Group group = file.createGroup(group_name.c_str());
    std::cerr<<" TEST: created group\n";                  // for debugging
  }
  H5::Group group = file.openGroup  (group_name.c_str()); // for debugging
  std::cerr<<" TEST: opened group\n";                     // for debugging
}

generates

TEST: caught something

  TEST: created group

  TEST: opened group


问:
How can I identify users who have a performed an action X times? [keen-io]
We plan to use Keen as our tracking core, but combining requests and extracting data is a big deal for us.

If we have for example one collection named pageviews, with a user as a property of it (like so : {"name": "pageviews", "properties":{"user":{"id":"4242"},"url":"https://keen.io/"}}), and another collection named purchases with the same user property inside :

How can we get the number of unique users who have visited at least 3 times one url and that have completed one other event "purchases" ?

How can we extract those persons ? Is it possible to do it with the Amazon S3 data replication ? (with Amazon Athena ?). The "extraction" feature does not seem to satisfy our extraction problematic as we can't apply "group by" statements and we can't combine multiple event for the extraction (am I wrong ?).

Our goal is to use Keen not only as a statistic analyser but also as a powerful data support for our segmentation/extraction use.

答:
Here are a variety of options to solve this problem:

Solution 1: Could you use a simpler criteria set? Keen's funnel analysis type has a natural syntax for a identifying a specific inventory of users who have done (or not done) action A, B, C, etc. It doesn't, however, have the ability to quickly filter based on the number of times the action has been done. How critical is that part of your criteria? Could you instead identify users who have:

Funnel Steps

viewed /keen.io/ and

viewed /keen.io/products and

made a purchase

This simplification would instantly make your question answerable in a single funnel query.

Solution 2: Two-step query process.
In this solution, we'll run two separate queries to arrive at the result. First, we'll use select_unique to identify the users who have performed the more rare action (purchase). In the next query, we'll count all the views of that particular page and group_by user.id to get a count of how many times each user viewed that page. We'll use the results of query 1 as a part of our filters in query 2, so that we only query on the relevant users who have made a purchase. Then, we can pick out which users have purchased and viewed the page 3 or more times.

var client = new Keen({
  projectId: "PROJECT_ID",
  readKey: "READ_KEY"
});

var usersWhoPurchased = []

// Query 1
var usersWhoPurchasedQuery = new Keen.Query("select_unique", {
  event_collection: "purchases",
  target_property: "user.id",
  timeframe: "this_7_days"
});

// Get Query 1 Results
client.run(usersWhoPurchasedQuery, function(err, response){
  usersWhoPurchased = response['result']
});

// Query 2
var activityCountsByUserQuery = new Keen.Query("count", {
  event_collection: "pageviews",
  group_by: "user.id",
  timeframe: "this_7_days",
  filters: [
   {
     property_name: "url",
     operator: "eq",
     property_value: https://keen.io/
   },
   {
     property_name: "user.id",
     operator: "in",
     property_value: usersWhoPurchased
   }
  ]
});

// Get Query 2 Results
client.run(activityCountsByUserQuery, function(err, response){
  console.log(response)
  var countsByUser = response['result']
});

// countsByUser = [
//   {
//     "user.id": "A",
//     "result": 1
//   },
//   {
//     "user.id": "B",
//     "result": 0
//   },
//   {
//     "user.id": "C",
//     "result": 3
//   }
// ]
// Sort countsByUser to identfy those with >3```
</div>
</div>
</p>

<p>This method has some considerations as you scale and start to max out the number of users you can include in a filter (hundreds or thousands depending on ID length). They can be broken down and queried in batches.</p>

<p><strong>Solution 3:</strong> Include counts on events.
This method doesn't work in all situations, but when it does it can be really powerful and elegant. The idea is to run counts on the client side and include them as user properties on your events. For example, your user object on your pageview event might contain a property like:</p>

```{
   "collection_name":"pageviews",
   "properties":{
      "user":{
         "id":"4242"
      },
      "url":"https://keen.io/",
      "product_views_this_session":4
   }
}
```

<p>With that kind of data, you can again use a simple funnel with filters to identify users who meet your criteria</p>

<p>Funnel Steps</p>

<ol>
<li>viewed page 'https://keen.io' where <code>product_views_this_session</code> <code>gt</code> <code>4</code></li>
<li>made a purchase</li>
</ol>

<p><strong>Solution 4:</strong> Implement counters using S3 Streaming + AWS Lambda + RDS or DynamoDB</p>

<p>If you don't already have it turned on, enable streaming of all of your raw Keen data to Amazon S3. Once it's there, you can do all sorts of additional steps on incoming data and data at rest.</p>

<p>Your process could be something like this:</p>

<ol>
<li>Turn on Keen IO Streaming to S3 </li>
<li>Write an AWS Lambda job that reviews the incoming data and </li>
<li>Counts how many times each user did each action</li>
<li>Looks up each user in an RDS table</li>
<li>Increments the count for that user and that action</li>
<li>Within the same Lambda job, re-post to the event back to Keen in a new collection, with a new property, like the following. </li>
</ol>

<p>New event:</p>

```{
   "collection_name":"user_product_view_enriched",
   "properties":{
      "user":{
         "id":"4242"
      },
      "url":"https://store.io/productA45",
      "view_history":{
         "product":"A45",
         "lifetime_views":5,
         "counting_since":"<timestamp>"
      }
   }
}
```

Putting the data back into Keen in this format allows you to use standard funnels as described in Solution 3:

Funnel Steps

users with events in user_product_view_enriched with product "A45" and lifetime_views > X

users who made a purchase

Limitation to this method is that you can't arbitrarily change when and how counters "start". For example, maybe you decide later that you only want to count views within the last 3 weeks rather than lifetime. You'd have to query the raw data in S3 to arrive at a new count like that, but you already have the data there so it's not that bigga deal.

Solution 5: Implement more complex querying on raw S3 data using EMR and/or Athena

Write a regular batch job to query your raw S3 data and identify the users that you are interested in. There are a variety of options here that I am not an expert on, but I know are possible.

Body:
Here are a variety of options to solve this problem:

Solution 1: Could you use a simpler criteria set? Keen's funnel analysis type has a natural syntax for a identifying a specific inventory of users who have done (or not done) action A, B, C, etc. It doesn't, however, have the ability to quickly filter based on the number of times the action has been done. How critical is that part of your criteria? Could you instead identify users who have:

Funnel Steps

viewed /keen.io/ and

viewed /keen.io/products and

made a purchase

This simplification would instantly make your question answerable in a single funnel query.

Solution 2: Two-step query process.
In this solution, we'll run two separate queries to arrive at the result. First, we'll use select_unique to identify the users who have performed the more rare action (purchase). In the next query, we'll count all the views of that particular page and group_by user.id to get a count of how many times each user viewed that page. We'll use the results of query 1 as a part of our filters in query 2, so that we only query on the relevant users who have made a purchase. Then, we can pick out which users have purchased and viewed the page 3 or more times.

var client = new Keen({
  projectId: "PROJECT_ID",
  readKey: "READ_KEY"
});

var usersWhoPurchased = []

// Query 1
var usersWhoPurchasedQuery = new Keen.Query("select_unique", {
  event_collection: "purchases",
  target_property: "user.id",
  timeframe: "this_7_days"
});

// Get Query 1 Results
client.run(usersWhoPurchasedQuery, function(err, response){
  usersWhoPurchased = response['result']
});

// Query 2
var activityCountsByUserQuery = new Keen.Query("count", {
  event_collection: "pageviews",
  group_by: "user.id",
  timeframe: "this_7_days",
  filters: [
   {
     property_name: "url",
     operator: "eq",
     property_value: https://keen.io/
   },
   {
     property_name: "user.id",
     operator: "in",
     property_value: usersWhoPurchased
   }
  ]
});

// Get Query 2 Results
client.run(activityCountsByUserQuery, function(err, response){
  console.log(response)
  var countsByUser = response['result']
});

// countsByUser = [
//   {
//     "user.id": "A",
//     "result": 1
//   },
//   {
//     "user.id": "B",
//     "result": 0
//   },
//   {
//     "user.id": "C",
//     "result": 3
//   }
// ]
// Sort countsByUser to identfy those with >3

This method has some considerations as you scale and start to max out the number of users you can include in a filter (hundreds or thousands depending on ID length). They can be broken down and queried in batches.

Solution 3: Include counts on events.
This method doesn't work in all situations, but when it does it can be really powerful and elegant. The idea is to run counts on the client side and include them as user properties on your events. For example, your user object on your pageview event might contain a property like:

{
   "collection_name":"pageviews",
   "properties":{
      "user":{
         "id":"4242"
      },
      "url":"https://keen.io/",
      "product_views_this_session":4
   }
}

With that kind of data, you can again use a simple funnel with filters to identify users who meet your criteria

Funnel Steps

viewed page 'https://keen.io' where product_views_this_session gt 4

made a purchase

Solution 4: Implement counters using S3 Streaming + AWS Lambda + RDS or DynamoDB

If you don't already have it turned on, enable streaming of all of your raw Keen data to Amazon S3. Once it's there, you can do all sorts of additional steps on incoming data and data at rest.

Your process could be something like this:

Turn on Keen IO Streaming to S3

Write an AWS Lambda job that reviews the incoming data and

Counts how many times each user did each action

Looks up each user in an RDS table

Increments the count for that user and that action

Within the same Lambda job, re-post to the event back to Keen in a new collection, with a new property, like the following.

New event:

{
   "collection_name":"user_product_view_enriched",
   "properties":{
      "user":{
         "id":"4242"
      },
      "url":"https://store.io/productA45",
      "view_history":{
         "product":"A45",
         "lifetime_views":5,
         "counting_since":"<timestamp>"
      }
   }
}

Putting the data back into Keen in this format allows you to use standard funnels as described in Solution 3:

Funnel Steps

users with events in user_product_view_enriched with product "A45" and lifetime_views > X

users who made a purchase

Limitation to this method is that you can't arbitrarily change when and how counters "start". For example, maybe you decide later that you only want to count views within the last 3 weeks rather than lifetime. You'd have to query the raw data in S3 to arrive at a new count like that, but you already have the data there so it's not that bigga deal.

Solution 5: Implement more complex querying on raw S3 data using EMR and/or Athena

Write a regular batch job to query your raw S3 data and identify the users that you are interested in. There are a variety of options here that I am not an expert on, but I know are possible.


问:
Is using COUNT(*) or SELECT * a good idea?
I've heard several times that you shouldn't perform COUNT(*) or SELECT * for performance reasons, but wasn't able to dig up some further information about it.

I can imagine that the database is then using all columns for the action, which can be an impressive performance loss, but I'm not sure about that. Does somebody have further information about the topic?

答:
It's absolutely true that "*" is "all columns". And you're right in the point of if you've a table with an incredible number of columns (say 100+), these kind of queries can be bad in terms of efficiency.

I believe that the best solution is creating database views previously filtering the amount of records evolved in the count operation, so, the performance impact isn't a big problem, because views can be cached.

In the other hand, it seems that "*" operator should be avoided when returning records, and it's brutally better to select the fields you really need to use in some business.


问:
How can I add index number in the front of output when using grep?
I am studying a simulated chemical reaction and hope to track atom motion. This motion was written in a big file with different timestep. I want to get the atom ID(unique in each timestep) in each time step. However, the output of

```<code>`grep -ni " 6557 " filename`
</code>```

has different line number which is hard to associate with timestep.

1117:      O       6557    0.000000    0.000000

5189:      O       6557    0.000000    0.000000

21491:      Fe      6557    0.000000   0.000000

How can I add index number (NOT line number) in the front of output when using grep command? like below:

1     O       6557    0.000000    0.000000

2     O       6557    0.000000    0.000000

3    Fe      6557    0.000000    0.000000

Many thanks.

答:
I would suggest awk solution:

```<code>awk '$0~/ 6557 /{ print ++c, $0}' filename
</code>```

If you still want to deal with grep command - combine it with GNU nl command (used to number lines of files):

```<code>grep -i ' 6557 ' filename | nl -n ln
</code>```

Body:
I am studying a simulated chemical reaction and hope to track atom motion. This motion was written in a big file with different timestep. I want to get the atom ID(unique in each timestep) in each time step. However, the output of

`grep -ni " 6557 " filename`

has different line number which is hard to associate with timestep.

1117:      O       6557    0.000000    0.000000

5189:      O       6557    0.000000    0.000000

21491:      Fe      6557    0.000000   0.000000

How can I add index number (NOT line number) in the front of output when using grep command? like below:

1     O       6557    0.000000    0.000000

2     O       6557    0.000000    0.000000

3    Fe      6557    0.000000    0.000000

Many thanks.

Body:
I would suggest awk solution:

awk '$0~/ 6557 /{ print ++c, $0}' filename

If you still want to deal with grep command - combine it with GNU nl command (used to number lines of files):

grep -i ' 6557 ' filename | nl -n ln


问:
issues deleting an image using Cloud Functions for Firebase and @google-cloud/storage
I'm trying to create a script in Cloud Functions for Firebase that will react to a db event and remove an image that has its path in one of the params ("fullPath").

this is the code i'm using:

```<code>'use strict';

const functions = require('firebase-functions');
const request = require('request-promise');
const admin = require('firebase-admin');
const gcs = require('@google-cloud/storage')({
    projectId: 'XXXXXXX',
    credentials: {
        // removed actual credentials from here
    }});

admin.initializeApp(functions.config().firebase);

// Deletes the user data in the Realtime Datastore when the accounts are deleted.
exports.removeImageOnNodeRemoval = functions.database
    .ref("images/{imageId}")
    .onWrite(function (event) {

        // exit if we are creating a new record (when no previous data exists)
        if (!event.data.previous.exists()) {
            console.log("a new image added");
            return;
        }

        // exit if we are just trying to update the image
        if (event.data.exists()) {
            console.log("image is been modified");
            return;
        }

        let previousData = event.data.previous.val();
        if(!previousData || !previousData.fullPath){
            console.log("no data in the previous");
            return;
        }

        let bucketName = 'XXXXXXX';
        console.log("default bucketName", gcs.bucket(bucketName));
        let file = gcs.bucket(bucketName).file(previousData.fullPath);
        console.log('the file /'+previousData.fullPath, file);

        file.exists().then(function(data) {
            let exists = data[0];
            console.info("file exists", exists);
        });

        file.delete().then(function() {
            // File deleted successfully
            console.log("image removed from project", previousData.fullPath);

        }).catch(function(error) {
            // Uh-oh, an error occurred!
            console.error("failed removing image from project", error, previousData);
        });

    });
</code>```

the error i'm getting:

```<code>failed removing image from project { ApiError: Not Found
    at Object.parseHttpRespBody (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:192:30)
    at Object.handleResp (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:132:18)
    at /user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:465:12
    at Request.onResponse [as _callback] (/user_code/node_modules/@google-cloud/storage/node_modules/retry-request/index.js:120:7)
    at Request.self.callback (/user_code/node_modules/@google-cloud/storage/node_modules/request/request.js:188:22)
    at emitTwo (events.js:106:13)
    at Request.emit (events.js:191:7)
    at Request.<anonymous> (/user_code/node_modules/@google-cloud/storage/node_modules/request/request.js:1171:10)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:188:7)
    at IncomingMessage.<anonymous> (/user_code/node_modules/@google-cloud/storage/node_modules/request/request.js:1091:12)
    at IncomingMessage.g (events.js:291:16)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)
  code: 404,
  errors: [ { domain: 'global', reason: 'notFound', message: 'Not Found' } ],
  response: undefined,
  message: 'Not Found' } { contentType: 'image/png',
  fullPath: 'images/1491162408464hznsjdt6oaqtqmukrzfr.png',
  name: '1491162408464hznsjdt6oaqtqmukrzfr.png',
  size: '44.0 KB',
  timeCreated: '2017-04-02T19:46:48.855Z',
  updated: '2017-04-02T19:46:48.855Z' }
</code>```

i have tried with and without credentials to google-cloud/storage (thinking they might get auto filled while im in firebase.functions - do i need them?). i have tried adding a slash to the file's path. i have validated that the file actually exists in the bucket (even tho file.exists() returns false). the credentials i provided are for an iam i created with admin privileges for the storage service.

i have also enable the billing account on the free plan.

any ideas?

答:
Make sure your bucket name doesn't include gs://

Eg. instead of gs://my-project-id.appspot.com use my-project-id.appspot.com

let bucket = gcs.bucket('my-project-id.appspot.com')

This may happen to you (as it did to me) if you copy your bucket name from, for instance, Android code, where you can use full URL to connect with storage, ie. storage.getReferenceFromUrl('gs://my-proj...

.

Also, it seems the projectId variable you use to initialise gcs doesn't need the appspot.com suffix (but it shouldn't break if you have it included). Ie. projectId:'my-project-id' should be suffice.

Lastly, the GCS node package docs states you need to generate separate JSON to pass as keyFilename to test things locally. Good news is - you can use the Firebase Admin SDK key, as described in the Get Started Server/Admin docs instead.

Body:
I'm trying to create a script in Cloud Functions for Firebase that will react to a db event and remove an image that has its path in one of the params ("fullPath").

this is the code i'm using:

'use strict';

const functions = require('firebase-functions');
const request = require('request-promise');
const admin = require('firebase-admin');
const gcs = require('@google-cloud/storage')({
    projectId: 'XXXXXXX',
    credentials: {
        // removed actual credentials from here
    }});

admin.initializeApp(functions.config().firebase);

// Deletes the user data in the Realtime Datastore when the accounts are deleted.
exports.removeImageOnNodeRemoval = functions.database
    .ref("images/{imageId}")
    .onWrite(function (event) {

        // exit if we are creating a new record (when no previous data exists)
        if (!event.data.previous.exists()) {
            console.log("a new image added");
            return;
        }

        // exit if we are just trying to update the image
        if (event.data.exists()) {
            console.log("image is been modified");
            return;
        }

        let previousData = event.data.previous.val();
        if(!previousData || !previousData.fullPath){
            console.log("no data in the previous");
            return;
        }

        let bucketName = 'XXXXXXX';
        console.log("default bucketName", gcs.bucket(bucketName));
        let file = gcs.bucket(bucketName).file(previousData.fullPath);
        console.log('the file /'+previousData.fullPath, file);

        file.exists().then(function(data) {
            let exists = data[0];
            console.info("file exists", exists);
        });

        file.delete().then(function() {
            // File deleted successfully
            console.log("image removed from project", previousData.fullPath);

        }).catch(function(error) {
            // Uh-oh, an error occurred!
            console.error("failed removing image from project", error, previousData);
        });

    });

the error i'm getting:

failed removing image from project { ApiError: Not Found
    at Object.parseHttpRespBody (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:192:30)
    at Object.handleResp (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:132:18)
    at /user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:465:12
    at Request.onResponse [as _callback] (/user_code/node_modules/@google-cloud/storage/node_modules/retry-request/index.js:120:7)
    at Request.self.callback (/user_code/node_modules/@google-cloud/storage/node_modules/request/request.js:188:22)
    at emitTwo (events.js:106:13)
    at Request.emit (events.js:191:7)
    at Request.<anonymous> (/user_code/node_modules/@google-cloud/storage/node_modules/request/request.js:1171:10)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:188:7)
    at IncomingMessage.<anonymous> (/user_code/node_modules/@google-cloud/storage/node_modules/request/request.js:1091:12)
    at IncomingMessage.g (events.js:291:16)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)
  code: 404,
  errors: [ { domain: 'global', reason: 'notFound', message: 'Not Found' } ],
  response: undefined,
  message: 'Not Found' } { contentType: 'image/png',
  fullPath: 'images/1491162408464hznsjdt6oaqtqmukrzfr.png',
  name: '1491162408464hznsjdt6oaqtqmukrzfr.png',
  size: '44.0 KB',
  timeCreated: '2017-04-02T19:46:48.855Z',
  updated: '2017-04-02T19:46:48.855Z' }

i have tried with and without credentials to google-cloud/storage (thinking they might get auto filled while im in firebase.functions - do i need them?). i have tried adding a slash to the file's path. i have validated that the file actually exists in the bucket (even tho file.exists() returns false). the credentials i provided are for an iam i created with admin privileges for the storage service.

i have also enable the billing account on the free plan.

any ideas?


问:
Clean dirty data
I have three variables (ID, Name and City) and need to generate a new variable flag.

There are something wrong with the observations. I need to find the wrong observations and create the flag.  The variable flag indicates which column contains the wrong observation.

Suppose just one bad observation at most in each row.

Given dirty data!!!!!

```<code>|ID      |Name             |City
|1       |IBM              |D
|1       |IBM              |D
|2       |IBM              |D
|3       |Google           |F
|3       |Microsoft        |F
|3       |Google           |F
|8       |Microsoft        |A
|8       |Microsoft        |B
|8       |Microsoft        |A
</code>```

Result

```<code>|ID      |Name             |City |flag
|1       |IBM              |D    |0
|1       |IBM              |D    |0
|2       |IBM              |D    |1
|3       |Google           |F    |0
|3       |Microsoft        |F    |2
|3       |Google           |F    |0
|8       |Microsoft        |A    |0
|8       |Microsoft        |B    |3
|8       |Microsoft        |A    |0
</code>```

答:
Here is an answer in Stata that rests on many assumptions that you pointed out in the comments but not the initial quesiton:

```<code>clear all
input float ID str9 Name str1 City
1 "IBM"       "D"
1 "IBM"       "D"
2 "IBM"       "D"
3 "Google"    "F"
3 "Microsoft" "F"
3 "Google"    "F"
8 "Microsoft" "A"
8 "Microsoft" "B"
8 "Microsoft" "A"
end

// get dummy variable for
duplicates tag, gen(right)

gen flag = 0

encode Name, gen(Name_n)
encode City, gen(City_n)

qui sum
forvalues start = 1(3)`r(N)' {
    local end = `start'+2

    // check if ID is all same
    qui sum ID in `start'/`end'
    if `r(sd)' != 0 {
        replace flag = 1 in `start'/`end' if right == 0
        continue
    }

    // check if name is all same
    qui sum Name_n in `start'/`end'
    if `r(sd)' != 0 {
        replace flag = 2 in `start'/`end' if right == 0
        continue
    }

    // chech if city is all same
    qui sum City_n in `start'/`end'
    if `r(sd)' != 0 {
        replace flag = 3 in `start'/`end' if right == 0
        continue
    }
}

drop right Name_n City_n
</code>```

The intuition is that because they are grouped in 3s, two are always right, there is only one issue per group of 3, and they are sorted by ID which can be wrong but not greater than the next greatest right ID we can first check for duplicates, if there is a duplicate observation then that observation is right.

Next, (in the forvalues loop) we go through each group of three to see which of the variables has the wrong value, when we find it, we replace flag with the appropriate number.

Title: Clean dirty data

Body:
I have three variables (ID, Name and City) and need to generate a new variable flag.

There are something wrong with the observations. I need to find the wrong observations and create the flag.  The variable flag indicates which column contains the wrong observation.

Suppose just one bad observation at most in each row.

Given dirty data!!!!!

|ID      |Name             |City
|1       |IBM              |D
|1       |IBM              |D
|2       |IBM              |D
|3       |Google           |F
|3       |Microsoft        |F
|3       |Google           |F
|8       |Microsoft        |A
|8       |Microsoft        |B
|8       |Microsoft        |A

Result

|ID      |Name             |City |flag
|1       |IBM              |D    |0
|1       |IBM              |D    |0
|2       |IBM              |D    |1
|3       |Google           |F    |0
|3       |Microsoft        |F    |2
|3       |Google           |F    |0
|8       |Microsoft        |A    |0
|8       |Microsoft        |B    |3
|8       |Microsoft        |A    |0

Body:
Here is an answer in Stata that rests on many assumptions that you pointed out in the comments but not the initial quesiton:

clear all
input float ID str9 Name str1 City
1 "IBM"       "D"
1 "IBM"       "D"
2 "IBM"       "D"
3 "Google"    "F"
3 "Microsoft" "F"
3 "Google"    "F"
8 "Microsoft" "A"
8 "Microsoft" "B"
8 "Microsoft" "A"
end

// get dummy variable for
duplicates tag, gen(right)

gen flag = 0

encode Name, gen(Name_n)
encode City, gen(City_n)

qui sum
forvalues start = 1(3)`r(N)' {
    local end = `start'+2

    // check if ID is all same
    qui sum ID in `start'/`end'
    if `r(sd)' != 0 {
        replace flag = 1 in `start'/`end' if right == 0
        continue
    }

    // check if name is all same
    qui sum Name_n in `start'/`end'
    if `r(sd)' != 0 {
        replace flag = 2 in `start'/`end' if right == 0
        continue
    }

    // chech if city is all same
    qui sum City_n in `start'/`end'
    if `r(sd)' != 0 {
        replace flag = 3 in `start'/`end' if right == 0
        continue
    }
}

drop right Name_n City_n

The intuition is that because they are grouped in 3s, two are always right, there is only one issue per group of 3, and they are sorted by ID which can be wrong but not greater than the next greatest right ID we can first check for duplicates, if there is a duplicate observation then that observation is right.

Next, (in the forvalues loop) we go through each group of three to see which of the variables has the wrong value, when we find it, we replace flag with the appropriate number.


问:
How to execute a batch of Selenium tests in parallel on a Selenium Grid
I have a Selenium Grid host on machine H and I have two grid nodes: machine N1 and machine N2. Both nodes have the same capabilities.

I have four tests: test1 => test4. I launch the tests on the host machine using nunit console: nunit3-console Test.dll --where="method =~ Test".

All tests are executed on machine N1. When I launch them again, all tests are executed on machine N2. Next time on machine N1 and so on.

I expected to have test1 executed on N1, test2 on N2, test3 on N1 and test4 on N2.

I tried to put "[assembly: Parallelizable(ParallelScope.Fixtures)]" in AssemblyInfo.cs but that didn't help. The tests are still all executed on the same node.

What am I missing?

答: Use the NUnit3 Parallelizable attribute. If you put the [Parallelizable] annotation above each test fixture (class), then each class's tests will run as a group on a separate browser/tab. To get a Test to run on a specific node, you'll need to define a desiredCapability. I use the undocumented applicationName capability to do so.


问:
HTML display image on top-left of page
I want to display an image on the top-left corner of my page. There should be a space of 10 pixels to the top and a space of 10 pixels to the left. I searched the web and found two possible answers. The first one uses the margin property while the second top and left with position: absolute;:

```<code><body>
<img src="x.jpg" style="margin-top: 10px; margin-left: 10px;">
</body>
</code>```

and

```<code><body>
<img src="x.jpg" style="top: 10px; left: 10px; position: absolute;">
</body>
</code>```

Both seem to work but is there any difference between them? Which one should I use?

答: Which one to use is up to you. The difference is that the absolutely positioned one will remove the image from the flow of the document and the other elements will act like it doesn't exist.</p>

Title: HTML display image on top-left of page

Body:
I want to display an image on the top-left corner of my page. There should be a space of 10 pixels to the top and a space of 10 pixels to the left. I searched the web and found two possible answers. The first one uses the margin property while the second top and left with position: absolute;:

and

Both seem to work but is there any difference between them? Which one should I use?


问:
Inconsistent Tkinter behavior at runtime after code changes
Note: I am not a programmer by trade or education, so bear with me. Take the following simple application:

```<code>import tkinter as tk
root = tk.Tk()

class app(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.button1= tk.Button(self, text='1')
        self.button1.pack(side='top')

        self.quit_button= tk.Button(self, text='quit', command=self.quit_button.destroy())
        self.quit_button.pack(side='bottom')

application = app(root)
application.mainloop()
</code>```

When I run this code, I am told destroy() isn't an method of quit_button. If I change it to:

```<code>self.quit_button= tk.Button(self, text='quit', command=self.dest)
</code>```

and I add the method:

```<code>def dest(self):
    self.quit_button.destroy()
</code>```

then it works - I assume this has something to do with the button being unable to reference itself while it's being created (please correct/enlighten me on this if you can since I don't fully understand this behavior).

However, what I'm really asking about is that the first time the program is run after I get this error, I get one window with both buttons, and X extra windows with only button1 (packed appropriately) where X is the number of times I incurred the error. Obviously I can just "not do that" but it would be extremely educative for me to understand how tkinter could be behaving this way. Is anyone here familiar enough with OOP to help? I create the root window before anything else, so there should be only one in any case.

答:
You've got a couple of problems in your code. All in the line:

```<code>self.quit_button= tk.Button(self, text='quit', command=self.quit_button.destroy())
</code>```

The first is you're trying to reference self.quit_button at the same time you're creating it. The second, somewhat related issue, is the command=self.quit_button.destroy() part actually tries to call one of this non-existent Button's methods rather than just supplying a reference to it (because of the ()s following its name).

Here's a version with those problems fixed:

```<code>import tkinter as tk
root = tk.Tk()

class app(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.button1= tk.Button(self, text='1')
        self.button1.pack(side='top')

        self.quit_button = tk.Button(self, text='quit')
        self.quit_button.config(command=self.quit_button.destroy)  # set function to execute
        self.quit_button.pack(side='bottom')

application = app(root)
application.mainloop()
</code>```

Body:
Note: I am not a programmer by trade or education, so bear with me. Take the following simple application:

import tkinter as tk
root = tk.Tk()

class app(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.button1= tk.Button(self, text='1')
        self.button1.pack(side='top')

        self.quit_button= tk.Button(self, text='quit', command=self.quit_button.destroy())
        self.quit_button.pack(side='bottom')

application = app(root)
application.mainloop()

When I run this code, I am told destroy() isn't an method of quit_button. If I change it to:

self.quit_button= tk.Button(self, text='quit', command=self.dest)

and I add the method:

def dest(self):
    self.quit_button.destroy()

then it works - I assume this has something to do with the button being unable to reference itself while it's being created (please correct/enlighten me on this if you can since I don't fully understand this behavior).

However, what I'm really asking about is that the first time the program is run after I get this error, I get one window with both buttons, and X extra windows with only button1 (packed appropriately) where X is the number of times I incurred the error. Obviously I can just "not do that" but it would be extremely educative for me to understand how tkinter could be behaving this way. Is anyone here familiar enough with OOP to help? I create the root window before anything else, so there should be only one in any case.

Body:
You've got a couple of problems in your code. All in the line:

self.quit_button= tk.Button(self, text='quit', command=self.quit_button.destroy())

The first is you're trying to reference self.quit_button at the same time you're creating it. The second, somewhat related issue, is the command=self.quit_button.destroy() part actually tries to call one of this non-existent Button's methods rather than just supplying a reference to it (because of the ()s following its name).

Here's a version with those problems fixed:

import tkinter as tk
root = tk.Tk()

class app(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.button1= tk.Button(self, text='1')
        self.button1.pack(side='top')

        self.quit_button = tk.Button(self, text='quit')
        self.quit_button.config(command=self.quit_button.destroy)  # set function to execute
        self.quit_button.pack(side='bottom')

application = app(root)
application.mainloop()


问:
A stored procedure required to bulk delete tables that are more than 1 hour old
I have created the following MySQL (v5.7.14) stored procedure. It successfully DROPS all the tables in my database that are prefixed 'members_list_'. However, I would only like to DROP the tables that are prefixed 'members_list_' AND are older than 1 hour.

```<code>BEGIN
SET @tables = NULL;
SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name, '`') INTO @tables
FROM information_schema.tables
WHERE table_schema = 'my_database_name'
AND table_name LIKE 'members_list_%'; -- AND CREATE_TIME < (NOW() - INTERVAL 1 HOUR);

SET @tables = CONCAT('DROP TABLE ', @tables);
PREPARE stmt1 FROM @tables;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END
</code>```

You will see that I have dummied-out a command in the WHERE clause. It uses the CREATE_TIME feature but when I 'make-live' that segment of code (by removing the '; --' part), I get the following error message:

Procedure execution failed
  1064 - You have an error in your SQL syntax; check the manual that corresponds >to your MySQL server version for the right syntax to use near 'NULL' at line 1

Is it even possible to bulk delete prefixed tables that are older than 1 hour?

答:
To answer my own question. The reason for the '1064' error message was that the GROUP_CONCAT string length has a default limit of 1024 characters. This meant that because I was sometimes deleting a lot of tables, this 1024 limit was breached.

To rectify this I needed set the GROUP_CONCAT command to a much higher number, thus:

SET SESSION group_concat_max_len = 1000000;

The stored procedure worked fine after this. Here is my whole revised stored procedure. It also includes a 'CASE' routine that will ensure that it doesn't fail if a NULL condition is met.

```<code>BEGIN
SET SESSION group_concat_max_len = 1000000;

SET @tables = NULL;
SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name, '`') INTO @tables FROM information_schema.tables
    WHERE table_schema = 'indexingwebsite2017' AND table_name LIKE 'ma_members_list_%' AND CREATE_TIME < (NOW() - INTERVAL 1 HOUR);

CASE
    WHEN ISNULL(@tables) THEN
        SELECT 'NULL VALUE DETECTED' AS Verification;
    ELSE
        SET @tables = CONCAT('DROP TABLE ', @tables);
        select @tables;
        PREPARE stmt1 FROM @tables;
        EXECUTE stmt1;
        DEALLOCATE PREPARE stmt1;
END CASE;
</code>```

END

Body:
I have created the following MySQL (v5.7.14) stored procedure. It successfully DROPS all the tables in my database that are prefixed 'members_list_'. However, I would only like to DROP the tables that are prefixed 'members_list_' AND are older than 1 hour.

BEGIN
SET @tables = NULL;
SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name, '`') INTO @tables
FROM information_schema.tables
WHERE table_schema = 'my_database_name'
AND table_name LIKE 'members_list_%'; -- AND CREATE_TIME < (NOW() - INTERVAL 1 HOUR);

SET @tables = CONCAT('DROP TABLE ', @tables);
PREPARE stmt1 FROM @tables;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END

You will see that I have dummied-out a command in the WHERE clause. It uses the CREATE_TIME feature but when I 'make-live' that segment of code (by removing the '; --' part), I get the following error message:

Procedure execution failed
  1064 - You have an error in your SQL syntax; check the manual that corresponds >to your MySQL server version for the right syntax to use near 'NULL' at line 1

Is it even possible to bulk delete prefixed tables that are older than 1 hour?

Body:
To answer my own question. The reason for the '1064' error message was that the GROUP_CONCAT string length has a default limit of 1024 characters. This meant that because I was sometimes deleting a lot of tables, this 1024 limit was breached.

To rectify this I needed set the GROUP_CONCAT command to a much higher number, thus:

SET SESSION group_concat_max_len = 1000000;

The stored procedure worked fine after this. Here is my whole revised stored procedure. It also includes a 'CASE' routine that will ensure that it doesn't fail if a NULL condition is met.

BEGIN
SET SESSION group_concat_max_len = 1000000;

SET @tables = NULL;
SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name, '`') INTO @tables FROM information_schema.tables
    WHERE table_schema = 'indexingwebsite2017' AND table_name LIKE 'ma_members_list_%' AND CREATE_TIME < (NOW() - INTERVAL 1 HOUR);

CASE
    WHEN ISNULL(@tables) THEN
        SELECT 'NULL VALUE DETECTED' AS Verification;
    ELSE
        SET @tables = CONCAT('DROP TABLE ', @tables);
        select @tables;
        PREPARE stmt1 FROM @tables;
        EXECUTE stmt1;
        DEALLOCATE PREPARE stmt1;
END CASE;

END


问:
Python, tuple arguments playing nicely with others
For example:

```<code>mytuple = ("Hello","World")
def printstuff(one,two,three):
    print one,two,three

printstuff(mytuple," How are you")
</code>```

This naturally crashes out with a TypeError because I'm only giving it two arguments when it expects three.

Is there a simple way of effectively 'splitting' a tuple in a tider way than expanding everything? Like:

```<code>printstuff(mytuple[0],mytuple[1]," How are you")
</code>```

答:
Actually, it is possible to do it without changing the order of the arguments. First you have to transform your string to a tuple, add it to your tuple mytuple and then pass your larger tuple as argument.

```<code>printstuff(*(mytuple+(" How are you",)))
# With your example, it returns: "Hello World  How are you"
</code>```

Body:
For example:

mytuple = ("Hello","World")
def printstuff(one,two,three):
    print one,two,three

printstuff(mytuple," How are you")

This naturally crashes out with a TypeError because I'm only giving it two arguments when it expects three.

Is there a simple way of effectively 'splitting' a tuple in a tider way than expanding everything? Like:

printstuff(mytuple[0],mytuple[1]," How are you")

Body:
Actually, it is possible to do it without changing the order of the arguments. First you have to transform your string to a tuple, add it to your tuple mytuple and then pass your larger tuple as argument.

printstuff(*(mytuple+(" How are you",)))
# With your example, it returns: "Hello World  How are you"


问:
Help in Streaming Video from IP Camera in android
Dear All:
 i am making an application in which we can connect wireless IP camera with my android mobile and then can get images from the IP camera in my application
please guide me through any tutorial that how to get connected to external hardware or to an IP camera through android application
please guide me through some code snippet or any tutorial.. for connecting my android with IP camera </p>

<p>Thanks
waiting........... </p>

答: Most of the IP Camera Streams using MJPEG (Motion JPEG), You will need to create a motion jpeg decoder (its simple, check out these sources http://www.charliemouse.com/code/cambozola/) </p>

Body:
Dear All:
 i am making an application in which we can connect wireless IP camera with my android mobile and then can get images from the IP camera in my application
please guide me through any tutorial that how to get connected to external hardware or to an IP camera through android application
please guide me through some code snippet or any tutorial.. for connecting my android with IP camera

Thanks
waiting...........


问:
Calculate GPS bearing if POI falls within the threshold
The use case that I am doing is to show POI's within the current position based on current bearing. For example if I am heading North I will not show POI's from South but only show POI's according to the bearing within the threshold.

答:
Here is my solution for now. While working to simplify it. Suggestions are welcome.</p>

```<code>public static boolean isBearingWithinRange(double heading, double alertHeading, double threshold) {
    boolean status = false;
    double leftThresholdMin = heading - threshold;
    double leftThresholdMax = FULL_CIRCLE;
    double rightThresholdMin = 0.0d;
    double rightThresholdMax = 0.0d;

    double total = heading + threshold;

    if(total > FULL_CIRCLE) {
        rightThresholdMax = threshold - (FULL_CIRCLE - heading);

        if((alertHeading >= leftThresholdMin && alertHeading <= leftThresholdMax) ||
                (alertHeading >= rightThresholdMin && alertHeading <= rightThresholdMax)) {
            status =  true;
        }

    } else if(heading < threshold) {
        double diff =  (threshold - heading);
        leftThresholdMin = FULL_CIRCLE - diff;
        rightThresholdMax = threshold + heading;

        if((alertHeading >= leftThresholdMin && alertHeading <= leftThresholdMax) ||
        (alertHeading >= rightThresholdMin && alertHeading <= rightThresholdMax)) {
            status =  true;
        }

    } else {
        rightThresholdMax = heading + threshold;

        if(alertHeading >= leftThresholdMin && alertHeading <= rightThresholdMax) {
            status = true;
        }
    }
    return status;
}
</code>```

Body:
Here is my solution for now. While working to simplify it. Suggestions are welcome.

public static boolean isBearingWithinRange(double heading, double alertHeading, double threshold) {
    boolean status = false;
    double leftThresholdMin = heading - threshold;
    double leftThresholdMax = FULL_CIRCLE;
    double rightThresholdMin = 0.0d;
    double rightThresholdMax = 0.0d;

    double total = heading + threshold;

    if(total > FULL_CIRCLE) {
        rightThresholdMax = threshold - (FULL_CIRCLE - heading);

        if((alertHeading >= leftThresholdMin && alertHeading <= leftThresholdMax) ||
                (alertHeading >= rightThresholdMin && alertHeading <= rightThresholdMax)) {
            status =  true;
        }

    } else if(heading < threshold) {
        double diff =  (threshold - heading);
        leftThresholdMin = FULL_CIRCLE - diff;
        rightThresholdMax = threshold + heading;

        if((alertHeading >= leftThresholdMin && alertHeading <= leftThresholdMax) ||
        (alertHeading >= rightThresholdMin && alertHeading <= rightThresholdMax)) {
            status =  true;
        }

    } else {
        rightThresholdMax = heading + threshold;

        if(alertHeading >= leftThresholdMin && alertHeading <= rightThresholdMax) {
            status = true;
        }
    }
    return status;
}


问:
Trying to get a picture and text side by side inside a div
I've been searching around for this and found a lot of similar cases but for whatever reason, the solution doesn't work in my scenario.

The text and picture are being stacked on top of each other. I'm having trouble keeping it inside the headerBlock div but side by side.

#wrap {
  width: 800px;
  margin: 0 auto;
  overflow: hidden;
  float: left;
}

#headerBlock {
  height: 200px;
  background:  #776b68;
}

div.headerText {
  vertical-align: middle;
  text-align: justify;
}

div.headerImg img {
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrap">
  <div id="headerBlock">
    <div class="headerText">Some text here</div>
    <div class="headerImg"><img src="/somepicturehere">
    </div>
  </div>

  <!--Ignore these, it's for future use-->
  <div id="leftBlock"></div>

  <div id="rightBlock"></div>

  <div id="footerBlock"></div>

</div></code>```

答:
Use display: flex on the parent and that will create a row with the children side by side. Then you can also use other flex properties like align-items and justify-content to align horizontally/vertically.

#wrap {
width: 800px;
margin: 0 auto;
overflow: hidden;
float: left;
}

#headerBlock {
height: 200px;
background:  #776b68;
display: flex;
align-items: center;
}

div.headerText {
text-align: justify;
}

div.headerImg img {
vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrap">
<div id="headerBlock">
    <div class="headerText">Some text here</div>
    <div class="headerImg"><img src="/somepicturehere">
    </div>
</div>

<!--Ignore these, it's for future use-->
<div id="leftBlock"></div>

<div id="rightBlock"></div>

<div id="footerBlock"></div>

</div></code>```

Body:
I've been searching around for this and found a lot of similar cases but for whatever reason, the solution doesn't work in my scenario.

The text and picture are being stacked on top of each other. I'm having trouble keeping it inside the headerBlock div but side by side.

#wrap {
  width: 800px;
  margin: 0 auto;
  overflow: hidden;
  float: left;
}

#headerBlock {
  height: 200px;
  background:  #776b68;
}

div.headerText {
  vertical-align: middle;
  text-align: justify;
}

div.headerImg img {
  vertical-align: middle;
}

Some text here

Body:
Use display: flex on the parent and that will create a row with the children side by side. Then you can also use other flex properties like align-items and justify-content to align horizontally/vertically.

#wrap {
width: 800px;
margin: 0 auto;
overflow: hidden;
float: left;
}

#headerBlock {
height: 200px;
background:  #776b68;
display: flex;
align-items: center;
}

div.headerText {
text-align: justify;
}

div.headerImg img {
vertical-align: middle;
}

<div id="wrap">
<div id="headerBlock">
    <div class="headerText">Some text here</div>
    <div class="headerImg"><img src="/somepicturehere">
    </div>
</div>

<!--Ignore these, it's for future use-->
<div id="leftBlock"></div>

<div id="rightBlock"></div>

<div id="footerBlock"></div>

</div>


问:
Enable form button when radio button is checked
I am using this line to (try) to enable a disabled submit button by removing a class. There is no result or error shown. Is this the way to go or do I need to write an separate script for this?</p>

```<code><label><input type="checkbox" value="ja" echo onclick=\"document.getElementById(\'submit_delete\').removeClass(\'disabled\')\">Ja ik wil deze toolbox verwijderen</label>';

<button type="button" id="submit_delete" class="btn btn-primary disabled">Opslaan</button>
</code>```

答:
You shouldn't mix presentation (HTML) and logic (JavaScript). You should create an external script and bind the event inside it:

document.querySelector('input[type="checkbox"]').addEventListener('click', () =>
  document.querySelector('#submit_delete').classList.remove('disabled')
)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button.disabled::after {
  content: " (disabled)";
}
button::after {
  content: " (not disabled)";
}</code>```

<input type="checkbox" value="ja">Ja ik wil deze toolbox verwijderen';

<button type="button" id="submit_delete" class="btn btn-primary disabled">Opslaan</button>```

Body:
I am using this line to (try) to enable a disabled submit button by removing a class. There is no result or error shown. Is this the way to go or do I need to write an separate script for this?

<input type="checkbox" value="ja" echo onclick=\"document.getElementById(\'submit_delete\').removeClass(\'disabled\')\">Ja ik wil deze toolbox verwijderen';

<button type="button" id="submit_delete" class="btn btn-primary disabled">Opslaan</button>

Body:
You shouldn't mix presentation (HTML) and logic (JavaScript). You should create an external script and bind the event inside it:

document.querySelector('input[type="checkbox"]').addEventListener('click', () =>
  document.querySelector('#submit_delete').classList.remove('disabled')
)

button.disabled::after {
  content: " (disabled)";
}
button::after {
  content: " (not disabled)";
}

<label><input type="checkbox" value="ja">Ja ik wil deze toolbox verwijderen</label>';

<button type="button" id="submit_delete" class="btn btn-primary disabled">Opslaan</button>