问:
Build minimum height BST from a sorted std::list<float> with C++
I'm having trouble writing the code to build minimum height BST from a sorted std::list.
For the node class:

```<code>class cBTNode
{
private:
    cBTNode* m_LeftChild;
    cBTNode* m_RightChild;
    float m_Data;
}
</code>```

For the BST class:

```<code>class cBTNodeTree
{
private:
    cBTNode* m_Root;
public:
    void LoadBalancedMain(std::list<float>& ls)；
    void LoadBalanced(std::list<float>& ls, cBTNode* root);
}
</code>```

Implementation: (basically my method is to find the middle element of the list ls, put that into the root, put all the elements smaller than the middle element into ls_left, and all the elements bigger than it into ls_right. Then recursively build up the left and right subtree by recursively calling the same function on ls_left and ls_right)

```<code>void cBTNodeTree::LoadBalancedMain(std::list<float>& ls)
{
    LoadBalanced(ls, m_Root); // m_Root is the root of the tree
}

void cBTNodeTree::LoadBalanced(std::list<float>& ls, cBTNode* root)
{
     // Stopping Condition I:
    if (ls.size() <= 0)
    {
        root = nullptr;
        return;
    }

    //  Stopping Condition II:
    if (ls.size() == 1)
    {
        root = new cBTNode(ls.front());
        return;
    }

    //  When we have at least 2 elements in the list
    //  Step 1: Locate the middle element

    if (ls.size() % 2 == 0)
    {
        //  Only consider the case of even numbers for the moment
        int middle = ls.size() / 2;
        std::list<float> ls_left;
        std::list<float> ls_right;
        int index = 0;

        // Obtain ls_left consisting elements smaller than the middle one
        while (index < middle)
        {
            ls_left.push_back(ls.front());
            ls.pop_front();
            index += 1;
        }
        //  Now we reach the middle element
        root = new cBTNode(ls.front());
        ls.pop_front();
        //  The rest is actually ls_right
        while (ls.size() > 0)
        {
            ls_right.push_back(ls.front());
            ls.pop_front();
        }
        //  Now we have the root and two lists
        cBTNode* left = root->GetLeftChild();
        cBTNode* right = root->GetRightChild();
        if (ls_left.size() > 0)
        {
            LoadBalanced(ls_left, left);
            root->SetLeftChild(left);
        }
        else
        {
            left = nullptr;
        }
        if (ls_right.size() > 0)
        {
            LoadBalanced(ls_right, right);
            root->SetRightChild(left);
        }
        else
        {
            right = nullptr;
        }
    }
}
</code>```

My Question: Somehow I found that actually none of the elements has been inserted into the tree. For example, if I check the value of m_Root, the root of the tree, I got an error because it's still nullprt. I'm not sure where did I go wrong? I hope it's some stupid pointer mistake because I haven't slept well. (I'm pretty sure the 'new cBTNode(ls.front())' line works)

BTW although I have written a dozen functions for the BST, I'm still struggling with BST recursion. I noticed that in all the textbooks that I read, for the linked list version of BST, the insertion ALWAYS need a helper function that return a pointer to a node. I begin to feel that I don't actually understand the things going on behind the recursion...

答: You pass the pointer to the root by value. Pass it by reference instead by changing the signature of LoadBalanced() appropriately.

Body:
I'm having trouble writing the code to build minimum height BST from a sorted std::list.
For the node class:

class cBTNode
{
private:
    cBTNode* m_LeftChild;
    cBTNode* m_RightChild;
    float m_Data;
}

For the BST class:

class cBTNodeTree
{
private:
    cBTNode* m_Root;
public:
    void LoadBalancedMain(std::list<float>& ls)；
    void LoadBalanced(std::list<float>& ls, cBTNode* root);
}

Implementation: (basically my method is to find the middle element of the list ls, put that into the root, put all the elements smaller than the middle element into ls_left, and all the elements bigger than it into ls_right. Then recursively build up the left and right subtree by recursively calling the same function on ls_left and ls_right)

void cBTNodeTree::LoadBalancedMain(std::list<float>& ls)
{
    LoadBalanced(ls, m_Root); // m_Root is the root of the tree
}

void cBTNodeTree::LoadBalanced(std::list<float>& ls, cBTNode* root)
{
     // Stopping Condition I:
    if (ls.size() <= 0)
    {
        root = nullptr;
        return;
    }

    //  Stopping Condition II:
    if (ls.size() == 1)
    {
        root = new cBTNode(ls.front());
        return;
    }

    //  When we have at least 2 elements in the list
    //  Step 1: Locate the middle element

    if (ls.size() % 2 == 0)
    {
        //  Only consider the case of even numbers for the moment
        int middle = ls.size() / 2;
        std::list<float> ls_left;
        std::list<float> ls_right;
        int index = 0;

        // Obtain ls_left consisting elements smaller than the middle one
        while (index < middle)
        {
            ls_left.push_back(ls.front());
            ls.pop_front();
            index += 1;
        }
        //  Now we reach the middle element
        root = new cBTNode(ls.front());
        ls.pop_front();
        //  The rest is actually ls_right
        while (ls.size() > 0)
        {
            ls_right.push_back(ls.front());
            ls.pop_front();
        }
        //  Now we have the root and two lists
        cBTNode* left = root->GetLeftChild();
        cBTNode* right = root->GetRightChild();
        if (ls_left.size() > 0)
        {
            LoadBalanced(ls_left, left);
            root->SetLeftChild(left);
        }
        else
        {
            left = nullptr;
        }
        if (ls_right.size() > 0)
        {
            LoadBalanced(ls_right, right);
            root->SetRightChild(left);
        }
        else
        {
            right = nullptr;
        }
    }
}

My Question: Somehow I found that actually none of the elements has been inserted into the tree. For example, if I check the value of m_Root, the root of the tree, I got an error because it's still nullprt. I'm not sure where did I go wrong? I hope it's some stupid pointer mistake because I haven't slept well. (I'm pretty sure the 'new cBTNode(ls.front())' line works)

BTW although I have written a dozen functions for the BST, I'm still struggling with BST recursion. I noticed that in all the textbooks that I read, for the linked list version of BST, the insertion ALWAYS need a helper function that return a pointer to a node. I begin to feel that I don't actually understand the things going on behind the recursion...


来源: stackexchange

问:
Test method delegation in Elixir
I've got two modules:

```<code>defmodule Base.ModuleOne do
  def do_stuff(opts) do
    "some stuff with opts"
  end
end

defmodule Base.ModuleTwo do
  defdelegate do_stuff(opts), to: Base.ModuleOne
end
</code>```

What is the proper way of testing delegation without copy-pasting tests for Base.ModuleOne.do_stuff/1 function under different namespace?

答:
As of the writing of this answer, I haven't found an "official" way to test defdelegate either.  The only choices I can think of in your case are:

Just ignore testing of Base.ModuleTwo.do_stuff(opts), assuming you have your bases covered in tests for Base.ModuleOne.do_stuff(opts).

Move the bulk of (if not all of) the tests in Base.ModuleOne.do_stuff(opts) up to the tests for Base.ModuleTwo.do_stuff(opts) so your tests become directly concerned with the public interface of your module, relegating Base.ModuleOne to be "private" implementation detail.

Since mocking would seem to be generally out of favour in Elixir, consider replacing defdelegate with dependency injection (using a function or module; see previous link for details), which would then allow you to write tests in the following kind of way:

Module:

```<code>defmodule Base.ModuleTwo do
  def do_stuff(opts, dependency \\ Base.ModuleOne)
    dependency.do_stuff(opts)
  end
end
</code>```

Test:

```<code>defmodule ModuleTwoTest do
  use ExUnit.Case

  describe "Base.ModuleTwo.do_stuff/2" do
    defmodule TestDependency do
      def do_stuff(_opts) do
        send self(), :do_stuff
      end
    end

    test "calls do_stuff/1 on its dependency" do
      opts = %{foo: "bar"} # or whatever the `opts` should be
      Base.ModuleTwo.do_stuff(opts, TestDependency)
      assert_received :do_stuff
    end
  end
end
</code>```

ContentLicense: CC BY-SA 3.0

Title: Test method delegation in Elixir

Body:
I've got two modules:

defmodule Base.ModuleOne do
  def do_stuff(opts) do
    "some stuff with opts"
  end
end

defmodule Base.ModuleTwo do
  defdelegate do_stuff(opts), to: Base.ModuleOne
end

What is the proper way of testing delegation without copy-pasting tests for Base.ModuleOne.do_stuff/1 function under different namespace?

Body:
As of the writing of this answer, I haven't found an "official" way to test defdelegate either.  The only choices I can think of in your case are:

Just ignore testing of Base.ModuleTwo.do_stuff(opts), assuming you have your bases covered in tests for Base.ModuleOne.do_stuff(opts).

Move the bulk of (if not all of) the tests in Base.ModuleOne.do_stuff(opts) up to the tests for Base.ModuleTwo.do_stuff(opts) so your tests become directly concerned with the public interface of your module, relegating Base.ModuleOne to be "private" implementation detail.

Since mocking would seem to be generally out of favour in Elixir, consider replacing defdelegate with dependency injection (using a function or module; see previous link for details), which would then allow you to write tests in the following kind of way:

Module:

defmodule Base.ModuleTwo do
  def do_stuff(opts, dependency \\ Base.ModuleOne)
    dependency.do_stuff(opts)
  end
end

Test:

defmodule ModuleTwoTest do
  use ExUnit.Case

  describe "Base.ModuleTwo.do_stuff/2" do
    defmodule TestDependency do
      def do_stuff(_opts) do
        send self(), :do_stuff
      end
    end

    test "calls do_stuff/1 on its dependency" do
      opts = %{foo: "bar"} # or whatever the `opts` should be
      Base.ModuleTwo.do_stuff(opts, TestDependency)
      assert_received :do_stuff
    end
  end
end


问:
Tensorflow: Word2vec CBOW model
I am new to tensorflow and to word2vec. I just studied the word2vec_basic.py which trains the model using Skip-Gram algorithm. Now I want to train using CBOW algorithm. Is it true that this can be achieved if I simply reverse the train_inputs and train_labels?

答:
For CBOW, You need to change only few parts of the code word2vec_basic.py. Overall the training structure and method are the same.

Which parts should I change in word2vec_basic.py?

1) The way it generates training data pairs. Because in CBOW, you are predicting the center word, not the context words.

The new version for generate_batch will be

```<code>def generate_batch(batch_size, bag_window):
  global data_index
  span = 2 * bag_window + 1 # [ bag_window target bag_window ]
  batch = np.ndarray(shape=(batch_size, span - 1), dtype=np.int32)
  labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
  buffer = collections.deque(maxlen=span)
  for _ in range(span):
    buffer.append(data[data_index])
    data_index = (data_index + 1) % len(data)
  for i in range(batch_size):
    # just for testing
    buffer_list = list(buffer)
    labels[i, 0] = buffer_list.pop(bag_window)
    batch[i] = buffer_list
    # iterate to the next buffer
    buffer.append(data[data_index])
    data_index = (data_index + 1) % len(data)
  return batch, labels
</code>```

Then new training data for CBOW would be

```<code>data: ['anarchism', 'originated', 'as', 'a', 'term', 'of', 'abuse', 'first', 'used', 'against', 'early', 'working', 'class', 'radicals', 'including', 'the']

#with bag_window = 1:
    batch: [['anarchism', 'as'], ['originated', 'a'], ['as', 'term'], ['a', 'of']]
    labels: ['originated', 'as', 'a', 'term']
</code>```

compared to Skip-gram's data

```<code>#with num_skips = 2 and skip_window = 1:
    batch: ['originated', 'originated', 'as', 'as', 'a', 'a', 'term', 'term', 'of', 'of', 'abuse', 'abuse', 'first', 'first', 'used', 'used']
    labels: ['as', 'anarchism', 'originated', 'a', 'term', 'as', 'a', 'of', 'term', 'abuse', 'of', 'first', 'used', 'abuse', 'against', 'first']
</code>```

2) Therefore you also need to change the variable shape

```<code>train_dataset = tf.placeholder(tf.int32, shape=[batch_size])
</code>```

to

```<code>train_dataset = tf.placeholder(tf.int32, shape=[batch_size, bag_window * 2])
</code>```

3) loss function

```<code> loss = tf.reduce_mean(tf.nn.sampled_softmax_loss(
  weights = softmax_weights, biases = softmax_biases, inputs = tf.reduce_sum(embed, 1), labels = train_labels, num_sampled= num_sampled, num_classes= vocabulary_size))
</code>```

Notice inputs = tf.reduce_sum(embed, 1) as Zichen Wang mentioned it.

This is it!

Title: Tensorflow: Word2vec CBOW model

Body:
For CBOW, You need to change only few parts of the code word2vec_basic.py. Overall the training structure and method are the same.

Which parts should I change in word2vec_basic.py?

1) The way it generates training data pairs. Because in CBOW, you are predicting the center word, not the context words.

The new version for generate_batch will be

def generate_batch(batch_size, bag_window):
  global data_index
  span = 2 * bag_window + 1 # [ bag_window target bag_window ]
  batch = np.ndarray(shape=(batch_size, span - 1), dtype=np.int32)
  labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
  buffer = collections.deque(maxlen=span)
  for _ in range(span):
    buffer.append(data[data_index])
    data_index = (data_index + 1) % len(data)
  for i in range(batch_size):
    # just for testing
    buffer_list = list(buffer)
    labels[i, 0] = buffer_list.pop(bag_window)
    batch[i] = buffer_list
    # iterate to the next buffer
    buffer.append(data[data_index])
    data_index = (data_index + 1) % len(data)
  return batch, labels

Then new training data for CBOW would be

data: ['anarchism', 'originated', 'as', 'a', 'term', 'of', 'abuse', 'first', 'used', 'against', 'early', 'working', 'class', 'radicals', 'including', 'the']

#with bag_window = 1:
    batch: [['anarchism', 'as'], ['originated', 'a'], ['as', 'term'], ['a', 'of']]
    labels: ['originated', 'as', 'a', 'term']

compared to Skip-gram's data

#with num_skips = 2 and skip_window = 1:
    batch: ['originated', 'originated', 'as', 'as', 'a', 'a', 'term', 'term', 'of', 'of', 'abuse', 'abuse', 'first', 'first', 'used', 'used']
    labels: ['as', 'anarchism', 'originated', 'a', 'term', 'as', 'a', 'of', 'term', 'abuse', 'of', 'first', 'used', 'abuse', 'against', 'first']

2) Therefore you also need to change the variable shape

train_dataset = tf.placeholder(tf.int32, shape=[batch_size])

to

train_dataset = tf.placeholder(tf.int32, shape=[batch_size, bag_window * 2])

3) loss function

 loss = tf.reduce_mean(tf.nn.sampled_softmax_loss(
  weights = softmax_weights, biases = softmax_biases, inputs = tf.reduce_sum(embed, 1), labels = train_labels, num_sampled= num_sampled, num_classes= vocabulary_size))

Notice inputs = tf.reduce_sum(embed, 1) as Zichen Wang mentioned it.

This is it!


问:
How to get jQuery to submit a form to a post
I have a form that I am validating with jQuery.

```<code><form id="target" class="center-block" action="/" method="POST">
    <textarea class="form-control" id="name" rows="3" name="name" placeholder="Enter a burger you would like to devour!"></textarea>
    <button type="button" id="submit" class="center-block btn btn-default top">Submit</button>
</form>
</code>```

After validation I am also trying to submit the form via jQuery.

```<code>if (validateForm() == true) {
   $("#target").submit();
}
</code>```

The validation is working however, it doesn't seem like the form is submitting to the post route.  I was able to get the form to post using ajax, but the post wouldn't redirect after finishing.  Was hoping this method would give the desired effect.

The app is running on Express and using MySQL.

答:
I don't think your jquery submit will work ,because an element id or name submit will replace the form.submit method, you should simply change id (name also shouldn't give that).

```<code><button type="button" id="changeThisId" class="center-block btn btn-default top">Submit</button>
</code>```

Body:
I have a form that I am validating with jQuery.

<form id="target" class="center-block" action="/" method="POST">
    <textarea class="form-control" id="name" rows="3" name="name" placeholder="Enter a burger you would like to devour!"></textarea>
    <button type="button" id="submit" class="center-block btn btn-default top">Submit</button>
</form>

After validation I am also trying to submit the form via jQuery.

if (validateForm() == true) {
   $("#target").submit();
}

The validation is working however, it doesn't seem like the form is submitting to the post route.  I was able to get the form to post using ajax, but the post wouldn't redirect after finishing.  Was hoping this method would give the desired effect.

The app is running on Express and using MySQL.

Body:
I don't think your jquery submit will work ,because an element id or name submit will replace the form.submit method, you should simply change id (name also shouldn't give that).

<button type="button" id="changeThisId" class="center-block btn btn-default top">Submit</button>


问:
Using a string argument to represent an object
If I have the following code:

```<code>TextBox txtUsername = new TextBox();
void setEnabled(string str, bool enable)
{
    // use str to find the TextBox object
    // str.Enabled = enable;
}
</code>```

Is this kinda thing even possible?

I want to be passing in 'Username' and then be prepending it with 'txt'.

答:
Yes,

```<code>   TextBox txtUsername = new TextBox();
   txtUsername.Name = "txtUsername ";

  void SetEnable(string str, bool enable)
  {
    this.Controls.Item("txt" + str).Enabled = enabled;
  }
</code>```

Little modification from "Bobby" answer.

ContentLicense: CC BY-SA 2.5

Body:
If I have the following code:

TextBox txtUsername = new TextBox();
void setEnabled(string str, bool enable)
{
    // use str to find the TextBox object
    // str.Enabled = enable;
}

Is this kinda thing even possible?

I want to be passing in 'Username' and then be prepending it with 'txt'.

Body:
Yes,

   TextBox txtUsername = new TextBox();
   txtUsername.Name = "txtUsername ";

  void SetEnable(string str, bool enable)
  {
    this.Controls.Item("txt" + str).Enabled = enabled;
  }

Little modification from "Bobby" answer.


问:
How to import a module for all functions?
I have a main file, called 'main.py' and two subfolders. One is called 'externals' and contains 'easygui.py' and the other one is called 'modules' and contains a file called 'gui.py'.

The program is started via main.py

I import easygui in main.py with import externals.easygui. The same way I import modules.gui

But when I call the welcome-function, It does not know easygui, I have to import it in the function. As I want to call more easygui-functions, I don't want to import easygui in every def.

How can this be solved?

Thanks in advance!

Steffen

Examples (for readability without try/except and comment stuff):

main.py:

```<code>#!/usr/bin/env python

import externals.easygui
import modules.gui

main():
    gui.welcome()
</code>```

gui.py:

```<code>def welcome():
    msgbox("Welcome!", ok_button="Ok")
</code>```

答:
What we have here...

Import the gui.py module and give it the name gui, so that you just have to use gui label to access to the functions in gui.

In the gui.py module import only the function msgbox, so that you don't have no other stuff imported (as you wanted this).

Now, when the program runs it shows the message calling the gui.welcome function.

main.py

```<code>import modules.gui as gui

def main():
    gui.welcome()

if __name__ == "__main__":
    main()
</code>```

gui.py in subfolder modules

```<code>from externals.easygui import msgbox

def welcome():
    msgbox("Welcome!", ok_button = "Ok")
</code>```

Body:
I have a main file, called 'main.py' and two subfolders. One is called 'externals' and contains 'easygui.py' and the other one is called 'modules' and contains a file called 'gui.py'.

The program is started via main.py

I import easygui in main.py with import externals.easygui. The same way I import modules.gui

But when I call the welcome-function, It does not know easygui, I have to import it in the function. As I want to call more easygui-functions, I don't want to import easygui in every def.

How can this be solved?

Thanks in advance!

Steffen

Examples (for readability without try/except and comment stuff):

main.py:

#!/usr/bin/env python

import externals.easygui
import modules.gui

main():
    gui.welcome()

gui.py:

def welcome():
    msgbox("Welcome!", ok_button="Ok")

Body:
What we have here...

Import the gui.py module and give it the name gui, so that you just have to use gui label to access to the functions in gui.

In the gui.py module import only the function msgbox, so that you don't have no other stuff imported (as you wanted this).

Now, when the program runs it shows the message calling the gui.welcome function.

main.py

import modules.gui as gui

def main():
    gui.welcome()

if __name__ == "__main__":
    main()

gui.py in subfolder modules

from externals.easygui import msgbox

def welcome():
    msgbox("Welcome!", ok_button = "Ok")


问:
Loop over every name and check to see if name begins with 'A'
Loop over every name and check to see if name begins with 'A'
If it does add a message to output array saying No gift for {person's name}
Otherwise, add a message to output array saying {Person's name} loved their gift!

var person;
var gift;
function christmasTree(people){
   var output = [];
for (var i =0; i<person.length; i++){
    if (person.startsWith ("Aimee")){
      output.push(No gift for Aimee.);
    }
    if (person.startsWith ("Ariana"){
       output.push(No gift for Ariana.);
    }
    else {
    output.push(person[i] loved their gift);
    }
    return output;
}
person = ['Aimee', 'Ariana', 'Billy', 'Joel', 'Zaire', 'Lily']
gift = christmasTree [person, 'gift'];
console.log(gift);
//Output should look like:
// This should be output:
  //   [
  //     "Billy loved their gift!",
  //     "Joel loved their gift!",
 //     "No gift for Aimee",
 //     "No gift for Ariana",
 //     "Zaire loved their gift!",
 //     "Lily loved their gift!",
 //  ]
 ```

*Having trouble getting the required output. Please advise on what how I can fix this.

答:
there are  a few issues with your code, you should check for people.length inside christmasTree(people). And thats not how you call a function, to call use christmasTree(person). Then if you are iterating over people you need to actually check for each element inside the array use people[i] for that.

var person;
var gift;
function christmasTree(people){
   var output = [];
for (var i=0; i<people.length; i++){
    if (people[i].toUpperCase().startsWith("A")){
      output.push("No gift for " + person[i]);
    }
    else {
      output.push(people[i] + " loved their gift");
    }
  }
    return output;
}
person = ['Aimee', 'Ariana', 'Billy', 'Joel', 'Zaire', 'Lily'];
gift = christmasTree(person);
console.log(gift);
//Output should look like:
// This should be output:
  //   [
  //     "Billy loved their gift!",
  //     "Joel loved their gift!",
 //     "No gift for Aimee",
 //     "No gift for Ariana",
 //     "Zaire loved their gift!",
 //     "Lily loved their gift!",
 //  ]
 ```

Body:
Loop over every name and check to see if name begins with 'A'
If it does add a message to output array saying No gift for {person's name}
Otherwise, add a message to output array saying {Person's name} loved their gift!

var person;
var gift;
function christmasTree(people){
   var output = [];
for (var i =0; i<person.length; i++){
    if (person.startsWith ("Aimee")){
      output.push(No gift for Aimee.);
    }
    if (person.startsWith ("Ariana"){
       output.push(No gift for Ariana.);
    }
    else {
    output.push(person[i] loved their gift);
    }
    return output;
}
person = ['Aimee', 'Ariana', 'Billy', 'Joel', 'Zaire', 'Lily']
gift = christmasTree [person, 'gift'];
console.log(gift);
//Output should look like:
// This should be output:
  //   [
  //     "Billy loved their gift!",
  //     "Joel loved their gift!",
 //     "No gift for Aimee",
 //     "No gift for Ariana",
 //     "Zaire loved their gift!",
 //     "Lily loved their gift!",
 //  ]

*Having trouble getting the required output. Please advise on what how I can fix this.


问:
creating a grouping ID based on values in another column
Trying to figure out how to do this in Oracle PL/SQL.

I want to create values in a column that would group records based on when a certain value appears in another column.  For example, based on the values in the first column in this image, I want to create the values in the 'Group' column.  The value of 'red' is always the first value in a group of records.  Any subsequent color value other than 'red' belongs to the same group.  The next 'red' value means a new 'group' value needs to be created.

Any ideas on how to create the values in the 'Group' column?  Thanks in advance.

答:
SQL tables represent unordered sets.  So, let me assume that you have a column that specifies the ordering.  I'll just call it id.

Your grp column is simply the sum of the reds up to and including any row.  This is easy:

```<code>select t.*,
       sum(case when colors = 'red' then 1 else 0 end) over (order by id) as grp
from t;
</code>```

Body:
SQL tables represent unordered sets.  So, let me assume that you have a column that specifies the ordering.  I'll just call it id.

Your grp column is simply the sum of the reds up to and including any row.  This is easy:

select t.*,
       sum(case when colors = 'red' then 1 else 0 end) over (order by id) as grp
from t;


问:
Where should I .catch promise errors between separate functions?
I'm new to promises, but as I understand it, .catch usually belongs at the end of a chain of promises:

```<code>promiseFunc()
   .then( ... )
   .then( ... )
   .catch( // catch any errors along the chain )
</code>```

What if the promises are split in between functions? Do I catch at the end of every function?

```<code>func1 () {
promiseFunc1()
    .then((result) => {
        promiseFunc2()
    )
    // should I .catch here?
}

func2 () {
    func1()
        .then((result) => {
            // do stuff
        })
        .catch(console.log.bind(console)); // this also catches errors from func1
}
</code>```

Maybe this is a symptom of another error (in which I'd love to hear if I'm doing this wrong), but when I try catching at the end of func1, I end up reaching the .then block of func2, with result = undefined. After deleting the catch in func1, it works -- but it feels wrong that func1 should expect any functions calling it to catch its errors.

答:
.catch() works very much like try/catch.  You should .catch() wherever you want or need to handle the error and either log something or change the course of the chain.

If all you want is for the promise chain to abort when an error occurs, then you can just put one .catch() at the very end of the chain and deal with the error there.

If, on the other hand, you have some sub-part of the chain that, if it has a rejection you want to do something different and allow the chain to continue or to take a different path, then you need to .catch() at that level where you want to influence things if there's an error.

All or Nothing Catch at the End

So, let's say you have four functions that all return promises.

If you do this:

```<code>a().then(b).then(c).then(d).then(finalResult => {
    // final result here
}).catch(err => {
    // deal with error here
});
</code>```

Then, if anyone of your four promises rejects, then the rest of the chain will abort and it will skip to your one .catch().  For some operations, this is the desired behavior.  If you intend to fetch some data from an external server, use that data to then fetch some other data from another external server and then write that data to disk, the whole process is pretty much all or nothing.  If any of the earlier steps fails, there's nothing else you can do as the whole operation has failed, you may as well just use one .catch() at the end and report that error.

Intervening Catch to Change the Behavior Mid-Chain upon Error

On, the other hand suppose you have a situation were you want to fetch some data from an external server, but if that server is down, then you want to fetch the data from an alternate server.  In that case, you want to catch the error from the first fetch and try something else.  So, you'd use a .catch() on the very first step and attempt something different:

```<code>fetch1().catch(fetch2).then(b).then(c).then(finalResult => {
   // final result here
}).catch(err => {
   // deal with error here
});
</code>```

Logging and Rethrow

When building sub-systems that others will use, it is often useful to log certain types of errors.  So, even the whole promise chain might be all or nothing, you still may want to log an error earlier in the chain and then rethrow the error so that the chain continues in the rejected state:

```<code>function someFuncOthersUse() {
    return a().then(b).then(c).catch(err => {
        // you want your own logging any time a or b or c rejects
        console.log("Error on fetchB", err);
        throw err;
    });
}
</code>```

The caller will then be doing:

```<code>someFuncOthersUse().then(finalResult => {
   // final result here
}).catch(err => {
   // deal with error here
});
</code>```

Body:
I'm new to promises, but as I understand it, .catch usually belongs at the end of a chain of promises:

promiseFunc()
   .then( ... )
   .then( ... )
   .catch( // catch any errors along the chain )

What if the promises are split in between functions? Do I catch at the end of every function?

func1 () {
promiseFunc1()
    .then((result) => {
        promiseFunc2()
    )
    // should I .catch here?
}

func2 () {
    func1()
        .then((result) => {
            // do stuff
        })
        .catch(console.log.bind(console)); // this also catches errors from func1
}

Maybe this is a symptom of another error (in which I'd love to hear if I'm doing this wrong), but when I try catching at the end of func1, I end up reaching the .then block of func2, with result = undefined. After deleting the catch in func1, it works -- but it feels wrong that func1 should expect any functions calling it to catch its errors.

Body:
.catch() works very much like try/catch.  You should .catch() wherever you want or need to handle the error and either log something or change the course of the chain.

If all you want is for the promise chain to abort when an error occurs, then you can just put one .catch() at the very end of the chain and deal with the error there.

If, on the other hand, you have some sub-part of the chain that, if it has a rejection you want to do something different and allow the chain to continue or to take a different path, then you need to .catch() at that level where you want to influence things if there's an error.

All or Nothing Catch at the End

So, let's say you have four functions that all return promises.

If you do this:

a().then(b).then(c).then(d).then(finalResult => {
    // final result here
}).catch(err => {
    // deal with error here
});

Then, if anyone of your four promises rejects, then the rest of the chain will abort and it will skip to your one .catch().  For some operations, this is the desired behavior.  If you intend to fetch some data from an external server, use that data to then fetch some other data from another external server and then write that data to disk, the whole process is pretty much all or nothing.  If any of the earlier steps fails, there's nothing else you can do as the whole operation has failed, you may as well just use one .catch() at the end and report that error.

Intervening Catch to Change the Behavior Mid-Chain upon Error

On, the other hand suppose you have a situation were you want to fetch some data from an external server, but if that server is down, then you want to fetch the data from an alternate server.  In that case, you want to catch the error from the first fetch and try something else.  So, you'd use a .catch() on the very first step and attempt something different:

fetch1().catch(fetch2).then(b).then(c).then(finalResult => {
   // final result here
}).catch(err => {
   // deal with error here
});

Logging and Rethrow

When building sub-systems that others will use, it is often useful to log certain types of errors.  So, even the whole promise chain might be all or nothing, you still may want to log an error earlier in the chain and then rethrow the error so that the chain continues in the rejected state:

function someFuncOthersUse() {
    return a().then(b).then(c).catch(err => {
        // you want your own logging any time a or b or c rejects
        console.log("Error on fetchB", err);
        throw err;
    });
}

The caller will then be doing:

someFuncOthersUse().then(finalResult => {
   // final result here
}).catch(err => {
   // deal with error here
});


问:
Execute a method of a different namspace by dynamic code in C# winforms
I am implementing a dynamic code execution in C# which allows users to write their own c# for that particular application.

I am using C# code compiler for executing the dynamic codes. The C# compiler reads the code file and construct the code in new namespace (a complete new code), compiles and runs it. In other view the base application host all these.

I have few methods that are present in host application that I want to be executed by the dynamic code. Is there any way by which the method of other namespace or application can be executed?

答:
You can use reflection.
Something like this:</p>

```<code>Type objType = null;
objType = _Assemblies.GetType(className);
MethodInfo methodInfo = null;
methodInfo = objType.GetMethod(TheCommandString);
methodInfo.Invoke(objType, userParameters);
</code>```

Body:
You can use reflection.
Something like this:

Type objType = null;
objType = _Assemblies.GetType(className);
MethodInfo methodInfo = null;
methodInfo = objType.GetMethod(TheCommandString);
methodInfo.Invoke(objType, userParameters);


问:
Why this while loop does not work?
Thanks everyone! I changed my code, and it still gives the error:

list index out of range.

Why?

```<code>M  = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    if B[0] <= C[0]:
        M.append(B.pop(0))
    if C[0] <= B[0]:
        M.append(C.pop(0))

print('Updated list: ', M)
</code>```

`

答:
What Went Wrong:
the third time of the while loop after you do B.pop(0) the list B becomes empty. So when you call B[0] on the next line when list B is already empty you get an error IndexError: list index out of range

Explain with Print Statement:

I added some print statements in your code

```<code>M  = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    print("==============")
    if B[0] <= C[0]:
        M.append(B.pop(0))
    print("B: " + str(B))
    if C[0] <= B[0]:
        M.append(C.pop(0))
    print("C: " + str(C))
</code>```

the result I get is:

```<code>==============
B: [3, 5]
C: [4, 6]
==============
B: [5]
C: [6]
==============
B: []
Traceback (most recent call last):
  File "python", line 9, in <module>
IndexError: list index out of range
</code>```

see when B is already empty you cannot call B[0]. When you try to get an element from a list with list[x]. x has to be between 0 and size of the list - 1.

Suggestion:
I would strongly encourage you to learn how to use print to debug your code. It is very useful. especially in a procedural language like Python.

Title: Why this while loop does not work?

Body:
Thanks everyone! I changed my code, and it still gives the error:

list index out of range.

Why?

M  = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    if B[0] <= C[0]:
        M.append(B.pop(0))
    if C[0] <= B[0]:
        M.append(C.pop(0))

print('Updated list: ', M)

`

Body:
What Went Wrong:
the third time of the while loop after you do B.pop(0) the list B becomes empty. So when you call B[0] on the next line when list B is already empty you get an error IndexError: list index out of range

Explain with Print Statement:

I added some print statements in your code

M  = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    print("==============")
    if B[0] <= C[0]:
        M.append(B.pop(0))
    print("B: " + str(B))
    if C[0] <= B[0]:
        M.append(C.pop(0))
    print("C: " + str(C))

the result I get is:

==============
B: [3, 5]
C: [4, 6]
==============
B: [5]
C: [6]
==============
B: []
Traceback (most recent call last):
  File "python", line 9, in <module>
IndexError: list index out of range

see when B is already empty you cannot call B[0]. When you try to get an element from a list with list[x]. x has to be between 0 and size of the list - 1.

Suggestion:
I would strongly encourage you to learn how to use print to debug your code. It is very useful. especially in a procedural language like Python.


问:
How to prevent links to open in Gmail's integrated mini-browser
On Android, when the user opens a mail with Gmail and clicks a link contained in the mail, then this URL is opened in sort-of a "mini browser", with a special bar at the top.

In my case the URL is a Portable Web Application (PWA) and should be opened in the Chrome browser itself (giving the user the possibility to manually add the URL to the home screen).

Is there a way to tell Gmail to always open the URL in the normal Chrome Mobile browser (or the standard browser)?

target="_blank" doesn't seem to help...

答: In Gmail go to settings --) General, and uncheck the option to open links in gmail. </p>


问:
SVN vs. Team Foundation Server
A few months back my team switched our source control over to Apache Subversion from Visual SourceSafe, and we haven't been happier.

Recently I've been looking at Team Foundation Server, and at least on the surface, it seems very impressive.  There is some great integration with Visual Studio, and lots of great tools for DBAs, testers, project managers, etc.

The most obvious difference between these two products is price.  It's hard to beat Apache Subversion (free).  Team Foundation Server is quite expensive, so the extra features would really have to kick Subversion in the pants.

Does anyone have practical experience with both?

How do they compare?

Is Team Foundation Server actually worth the expense?

答:
TFS is great for project management and tracking, however I feel the source control is not as good as SVN. Here are my beefs with TFS:

Check-in/Check-out model

This is a huge con for TFS source control. Unfortunately, VS automatically checks out items for you, even if you don't want to. I've been in a situation where someone checked out some files and then went on vacation. I was in charge of restructuring the directory structure, but was unable to because a bunch of files were checked out to that person. There is no way in the GUI to undo the checkout, which meant it had to be done one by one in the command line. Or I had to figure out how to write a power shell script for this.

VS is required to do everything

Sometimes I want to edit a text file and check it in. This requires me to startup VS 2010, which is a huge beast, just to edit a file and check it in. Something that took a few seconds with SVN now takes me a minute.

As some others pointed out, files are marked read only if they are not checked out. If you make it writable and edit it outside of VS, TFS won't recognize this. This makes editing something outside of VS annoying. This means, firing up VS, checking out the file, editing it another editor, checking in in VS.

Some operations that were easy in SVN are now a pain

Maybe I haven't figured it out yet, but I found that rolling back a changeset was very tedious with TFS.

Adding files to source control, which are not part of a solution, is a huge pain. The TFS source control explorer only shows which files are in source control, not which ones are not (maybe there's a setting somewhere for this, I don't know). With Tortoise SVN, I could simply press Commit on a folder and select which files to add.

Title: SVN vs. Team Foundation Server

LastEditorDisplayName: Mark Biek


问:
Possible to highlight matching quotes in vim?
With the syntax highlighting in vim, I get the handy feature where the matching paren or bracket will be highlighted when I put the cursor over it. Is it possible to do the same thing for quotes?</p>

答:
The solution is here: Stackoverflow in matchquote except it has the unfortunate limitation that only the current line is considered.
matchit seems to comes close by allowing defining of multi-line matches of words such as if/endif but still no multi-line possibility that I can figure out to get matching for " and '.


问:
React-native Scrollview not work
I've the following layout, and it need scroll when data is greater of screen:

Image:

Code:

```<code>export default  () => (
  <Container hasNavBar={false}>
    <View style={{flex: 1}}>
      <View style={Styles.container}>
        <View style={{
          flex: 1, backgroundColor: 'red',
          alignItems: 'center',
          justifyContent: 'center',
        }}>
          <Text>Area 1</Text>
        </View>

        <View style={{
          flex: 2, backgroundColor: 'yellow',
          alignItems: 'center',
          justifyContent: 'center',
        }}>
          <Text>Area 2</Text>
        </View>
      </View>

    </View>
  </Container>
);
</code>```

Following the documentation of react-native for add scroll I need create a wraper of my layout using ScrollView component, but when added scrollView component my layout broke:

Image:

Code:

```<code>export default  () => (
  <Container hasNavBar={false}>
    <ScrollView style={{flex: 1}}>
      <View style={Styles.container}>
        <View style={{
          flex: 1, backgroundColor: 'red',
          alignItems: 'center',
          justifyContent: 'center',
        }}>
          <Text>Area 1</Text>
        </View>

        <View style={{
          flex: 2, backgroundColor: 'yellow',
          alignItems: 'center',
          justifyContent: 'center',
        }}>
          <Text>Area 2</Text>
        </View>
      </View>

    </ScrollView>
  </Container>
);
</code>```

Container Component

```<code><View style={flex: 1}>
        {this.props.children}
        <DropdownAlert
          closeInterval={10000}
          updateStatusBar={false}
          ref={(ref) => this.dropdown = ref}
          onClose={() => null}/>
      </View>
</code>```

How i solve it ?

答:
After re-reading the question with better understanding of your complete code it became obvious that the quickest fix would be to define minHeight on Area 1 and Area 2's views. We can calculate it from window's Dimensions. This allows you to obtain the 33%/66% ratio with minimal content and expand either Area as needed with additional content.

Place this at the top of render():

const { height } = Dimensions.get('window');

Add to Area 1's style

minHeight: height / 3

And to Area 2's style

minHeight: (height / 3) * 2

Title: React-native Scrollview not work

Body:
I've the following layout, and it need scroll when data is greater of screen:

Image:

Code:

export default  () => (
  <Container hasNavBar={false}>
    <View style={{flex: 1}}>
      <View style={Styles.container}>
        <View style={{
          flex: 1, backgroundColor: 'red',
          alignItems: 'center',
          justifyContent: 'center',
        }}>
          <Text>Area 1</Text>
        </View>

        <View style={{
          flex: 2, backgroundColor: 'yellow',
          alignItems: 'center',
          justifyContent: 'center',
        }}>
          <Text>Area 2</Text>
        </View>
      </View>

    </View>
  </Container>
);

Following the documentation of react-native for add scroll I need create a wraper of my layout using ScrollView component, but when added scrollView component my layout broke:

Image:

Code:

export default  () => (
  <Container hasNavBar={false}>
    <ScrollView style={{flex: 1}}>
      <View style={Styles.container}>
        <View style={{
          flex: 1, backgroundColor: 'red',
          alignItems: 'center',
          justifyContent: 'center',
        }}>
          <Text>Area 1</Text>
        </View>

        <View style={{
          flex: 2, backgroundColor: 'yellow',
          alignItems: 'center',
          justifyContent: 'center',
        }}>
          <Text>Area 2</Text>
        </View>
      </View>

    </ScrollView>
  </Container>
);

Container Component

<View style={flex: 1}>
        {this.props.children}
        <DropdownAlert
          closeInterval={10000}
          updateStatusBar={false}
          ref={(ref) => this.dropdown = ref}
          onClose={() => null}/>
      </View>

How i solve it ?


问:
What will happen when React encounter an array nested in another?
When React render an array, a key should be provided for every item in this array. Otherwise, a warning will be given:

```<code>Warning: Each child in an array or iterator should have a unique "key" prop
</code>```

There is detailed explanation in React Doc about how to identify keys and why we do this.

But in this case, I find that no warning is given when render an array nested in another.

```<code>const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((numbers) =>
  <li>{numbers}</li>
);

// 'listItems' is wrapped in an array
ReactDOM.render(
  <ul>{[listItems]}</ul>,
  document.getElementById('container')
);
</code>```

After debugging, in React, I find function validateChildKeys, which is used to validate children's keys:

```<code>/**
 * file path: react/lib/ReactElementValidator.js
 * Ensure that every element either is passed in a static location, in an
 * array with an explicit keys property defined, or in an object literal
 * with valid key property.
 *
 * @internal
 * @param {ReactNode} node Statically passed child of any type.
 * @param {*} parentType node's parent's type.
 */
function validateChildKeys(node, parentType) {
  if (typeof node !== 'object') {
    return;
  }
  if (Array.isArray(node)) {
    for (var i = 0; i < node.length; i++) {
      var child = node[i];
      if (ReactElement.isValidElement(child)) {
        validateExplicitKey(child, parentType);
      }
    }
  } else {
    // do some other validation
    // ..................
  }
}
</code>```

function ReactElement.isValidElement(child) is used to check if a child node should be checked.

```<code>ReactElement.isValidElement = function (object) {
  return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
</code>```

When checking nesting array, e.g. array = [array0,array1,array2], array0, array1, array2 are Array objects, which have no property named $$typeof, so function validateExplicitKey will never be called, child node will never be checked, of course, warning message will never be thrown.

I wonder:

Does React acquiesce this?

What impact that would have when re-render happens?

Does it have impact on performance? If does, how to avoid this case when I want to render this code:

```<code>const Page = (tables) => (
   tables.map((table, idx) => (
      [<Title/>,
        ...(table.get('forms').map((form, aidx) => (<Form/>)))
      ]
   ))
);
</code>```

答:
I think the case you're bringing up is actually described in the comment above validateChildKeys:

Ensure that every element either is passed in a static location, in an array with an explicit keys property defined, or in an object literal with valid key property.

Since your listItems array is only declared once and not recalculated on renders, React assumes it won't need keys to differentiate elements in subsequent renders.

If you move your array declaration into the render function you will see the error again, even if the array is nested:

```<code>const numbers = [1, 2, 3, 4, 5];

// 'listItems' is wrapped in an array
ReactDOM.render(
  <ul>
    {[numbers.map((numbers) => <li>{numbers}</li>)]}
  </ul>,
  document.getElementById('container')
);
</code>```

Body:
When React render an array, a key should be provided for every item in this array. Otherwise, a warning will be given:

Warning: Each child in an array or iterator should have a unique "key" prop

There is detailed explanation in React Doc about how to identify keys and why we do this.

But in this case, I find that no warning is given when render an array nested in another.

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((numbers) =>

{numbers}

);

// 'listItems' is wrapped in an array
ReactDOM.render(

{[listItems]}
,
  document.getElementById('container')
);

After debugging, in React, I find function validateChildKeys, which is used to validate children's keys:

/**
 * file path: react/lib/ReactElementValidator.js
 * Ensure that every element either is passed in a static location, in an
 * array with an explicit keys property defined, or in an object literal
 * with valid key property.
 *
 * @internal
 * @param {ReactNode} node Statically passed child of any type.
 * @param {*} parentType node's parent's type.
 */
function validateChildKeys(node, parentType) {
  if (typeof node !== 'object') {
    return;
  }
  if (Array.isArray(node)) {
    for (var i = 0; i < node.length; i++) {
      var child = node[i];
      if (ReactElement.isValidElement(child)) {
        validateExplicitKey(child, parentType);
      }
    }
  } else {
    // do some other validation
    // ..................
  }
}

function ReactElement.isValidElement(child) is used to check if a child node should be checked.

ReactElement.isValidElement = function (object) {
  return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}

When checking nesting array, e.g. array = [array0,array1,array2], array0, array1, array2 are Array objects, which have no property named $$typeof, so function validateExplicitKey will never be called, child node will never be checked, of course, warning message will never be thrown.

I wonder:

Does React acquiesce this?

What impact that would have when re-render happens?

Does it have impact on performance? If does, how to avoid this case when I want to render this code:

const Page = (tables) => (
   tables.map((table, idx) => (
      [<Title/>,
        ...(table.get('forms').map((form, aidx) => (<Form/>)))
      ]
   ))
);

Body:
I think the case you're bringing up is actually described in the comment above validateChildKeys:

Ensure that every element either is passed in a static location, in an array with an explicit keys property defined, or in an object literal with valid key property.

Since your listItems array is only declared once and not recalculated on renders, React assumes it won't need keys to differentiate elements in subsequent renders.

If you move your array declaration into the render function you will see the error again, even if the array is nested:

const numbers = [1, 2, 3, 4, 5];

// 'listItems' is wrapped in an array
ReactDOM.render(
  <ul>
    {[numbers.map((numbers) => <li>{numbers}</li>)]}
  </ul>,
  document.getElementById('container')
);


问:
Creating a resizable sidebar in Qt4
I want to create a sidebar in QMainWindow that is resizable any idea how can I do it ? thanks :)

PS : Here is an example from Qt Assistant

答: well, you might wanna download Visual Studio Professional and make it "dialog based" while you set up the project. and open the file filename.rc to edit the dialog. There are lots of controls that I've haevn't used yet. To get to the controls menu, go to toolbars on the side of the IDE, and you should see something with the word controls in it.</p>

Title: Creating a resizable sidebar in Qt4


问:
Error while using both module.exports and exports
I have read couple of posts on SO before posting this question. One thing that's not clear to me is why I'm not able to use multiply function when importing this as module. Isn't module.exports and exports refer to the same object?

Shouldn't multiply be added to the object that is referenced by module.exports. Since exports is an alias for module.exports, I was expecting I'm adding multiply to the same object as I'm not reassigning exports to refer to something else.

```<code>module.exports = {
  sum : function(a,b){
    return a+b;
  }
};

exports.multiply = function(a,b){
  return a*b;
};
</code>```

答:
Note that at the start of each nodejs module file, both exports and module.exports point at the same empty object. And you can assign properties to them like below:

```<code>exports.item1 = "hi1"

module.exports.item2 = "hi2"
</code>```

Now both of the exports and module.exports have the same value:

```<code>{item1:"hi1", item2: "hi2"}
</code>```

But when you assign objects to them, only the object that you have given to module.exports matters! In your case if you want to assign an object to module.exports and then add other functions to it, you should first assign the same object to both of them! Now they will point to the same object and if you assign another function to your exports object, it will be accessible via module.exports object, too.

Change the first line of your code and it will work fine!

```<code>exports = module.exports = {
    sum : function(a,b){
    return a+b;
    }
};

exports.multiply = function(a,b){
    return a*b;
};
</code>```

Body:
I have read couple of posts on SO before posting this question. One thing that's not clear to me is why I'm not able to use multiply function when importing this as module. Isn't module.exports and exports refer to the same object?

Shouldn't multiply be added to the object that is referenced by module.exports. Since exports is an alias for module.exports, I was expecting I'm adding multiply to the same object as I'm not reassigning exports to refer to something else.

module.exports = {
  sum : function(a,b){
    return a+b;
  }
};

exports.multiply = function(a,b){
  return a*b;
};

Body:
Note that at the start of each nodejs module file, both exports and module.exports point at the same empty object. And you can assign properties to them like below:

exports.item1 = "hi1"

module.exports.item2 = "hi2"

Now both of the exports and module.exports have the same value:

{item1:"hi1", item2: "hi2"}

But when you assign objects to them, only the object that you have given to module.exports matters! In your case if you want to assign an object to module.exports and then add other functions to it, you should first assign the same object to both of them! Now they will point to the same object and if you assign another function to your exports object, it will be accessible via module.exports object, too.

Change the first line of your code and it will work fine!

exports = module.exports = {
    sum : function(a,b){
    return a+b;
    }
};

exports.multiply = function(a,b){
    return a*b;
};


问:
How can I group by the count number of column values and sort it?
How can I group by the count number of column values and sort it?

I am a pandas learner.

I have original dataframe called data.log. Now I want to count the numbers group by 'c-ip-1', and sort the result.

The original data.log:

```<code>   sc-status  sc-substatus  sc-win32-status  time-taken       c-ip-1
0        200             0                0         986  31.7.188.55
1        200             0                0        2539  31.7.188.55
2        200             0                0        1172  31.7.188.56
3        200             0                0        3152  31.7.188.80
4        200             0                0        1091  31.7.188.80
...
99       200             0                0        1115  31.9.200.60
100      200             0                0        2000  31.9.200.61
</code>```

The expect result is as follows:

```<code>         c-ip-1                 count
0        31.7.188.56            1
1        31.9.200.61            1
2        31.7.188.55            2
...
34       31.9.200.60            5
</code>```

I tried to write python code and run it, but it failed:

```<code>import pandas as pd

df = pd.read_table('data.log', sep=" ")

print(df[['c-ip-1']].groupby(['c-ip-1']).agg(['count'])
</code>```

How can I use python solve the problem?

答:
I think you need aggregate by GroupBy.size, then Series.sort_values and last Series.reset_index:

```<code>#better is more general separator `\s+` - one or more whitespaces
df = pd.read_table('data.log', sep="\s+")

df1 = df.groupby('c-ip-1').size().sort_values().reset_index(name='count')
print (df1)
        c-ip-1  count
0  31.7.188.56      1
1  31.9.200.60      1
2  31.9.200.61      1
3  31.7.188.55      2
4  31.7.188.80      2
</code>```

What is the difference between size and count in pandas?

Body:
How can I group by the count number of column values and sort it?

I am a pandas learner.

I have original dataframe called data.log. Now I want to count the numbers group by 'c-ip-1', and sort the result.

The original data.log:

   sc-status  sc-substatus  sc-win32-status  time-taken       c-ip-1
0        200             0                0         986  31.7.188.55
1        200             0                0        2539  31.7.188.55
2        200             0                0        1172  31.7.188.56
3        200             0                0        3152  31.7.188.80
4        200             0                0        1091  31.7.188.80
...
99       200             0                0        1115  31.9.200.60
100      200             0                0        2000  31.9.200.61

The expect result is as follows:

         c-ip-1                 count
0        31.7.188.56            1
1        31.9.200.61            1
2        31.7.188.55            2
...
34       31.9.200.60            5

I tried to write python code and run it, but it failed:

import pandas as pd

df = pd.read_table('data.log', sep=" ")

print(df[['c-ip-1']].groupby(['c-ip-1']).agg(['count'])

How can I use python solve the problem?

Body:
I think you need aggregate by GroupBy.size, then Series.sort_values and last Series.reset_index:

#better is more general separator `\s+` - one or more whitespaces
df = pd.read_table('data.log', sep="\s+")

df1 = df.groupby('c-ip-1').size().sort_values().reset_index(name='count')
print (df1)
        c-ip-1  count
0  31.7.188.56      1
1  31.9.200.60      1
2  31.9.200.61      1
3  31.7.188.55      2
4  31.7.188.80      2

What is the difference between size and count in pandas?


问:
openwrt/lighttpd cleaning up CGI: process died with signal 6
I setup OpenWrt/lighttpd with lighttpd-mod-cgi on 3020 according to documentation. But when I connect to router and open the test.sh script's url from browser, just a white page is shown.
Checked lighttpd error log to find this:

(mod_cgi.c.1313) cleaning up CGI: process died with signal 6

test.sh:

```<code>#!/bin/bash
echo "Content-type: text/html"
echo ""

echo 'Hello World'
</code>```

lighttpd.conf:

```<code>server.modules              = ( "mod_cgi" )

server.errorlog             = "/var/logs/lighttpd/error.log"

index-file.names            = ( "index.php", "index.html",

                                "index.htm", "default.htm" )

# mimetype mapping

mimetype.assign             = (

  ".pdf"          =>      "application/pdf",

  ".sig"          =>      "application/pgp-signature",

  ".spl"          =>      "application/futuresplash",

  ".class"        =>      "application/octet-stream",

  ".ps"           =>      "application/postscript",

  ".torrent"      =>      "application/x-bittorrent",

  ".dvi"          =>      "application/x-dvi",

  ".gz"           =>      "application/x-gzip",

  ".pac"          =>      "application/x-ns-proxy-autoconfig",

  ".swf"          =>      "application/x-shockwave-flash",

  ".tar.gz"       =>      "application/x-tgz",

  ".tgz"          =>      "application/x-tgz",

  ".tar"          =>      "application/x-tar",

  ".zip"          =>      "application/zip",

  ".mp3"          =>      "audio/mpeg",

  ".m3u"          =>      "audio/x-mpegurl",

  ".wma"          =>      "audio/x-ms-wma",

  ".wax"          =>      "audio/x-ms-wax",

  ".ogg"          =>      "application/ogg",

  ".wav"          =>      "audio/x-wav",

  ".gif"          =>      "image/gif",

  ".jpg"          =>      "image/jpeg",

  ".jpeg"         =>      "image/jpeg",

  ".png"          =>      "image/png",

  ".xbm"          =>      "image/x-xbitmap",

  ".xpm"          =>      "image/x-xpixmap",

  ".xwd"          =>      "image/x-xwindowdump",

  ".css"          =>      "text/css",

  ".html"         =>      "text/html",

  ".htm"          =>      "text/html",

  ".js"           =>      "text/javascript",

  ".asc"          =>      "text/plain",

  ".c"            =>      "text/plain",

  ".cpp"          =>      "text/plain",

  ".log"          =>      "text/plain",

  ".conf"         =>      "text/plain",

  ".text"         =>      "text/plain",

  ".txt"          =>      "text/plain",

  ".dtd"          =>      "text/xml",

  ".xml"          =>      "text/xml",

  ".mpeg"         =>      "video/mpeg",

  ".mpg"          =>      "video/mpeg",

  ".mov"          =>      "video/quicktime",

  ".qt"           =>      "video/quicktime",

  ".avi"          =>      "video/x-msvideo",

  ".asf"          =>      "video/x-ms-asf",

  ".asx"          =>      "video/x-ms-asf",

  ".wmv"          =>      "video/x-ms-wmv",

  ".bz2"          =>      "application/x-bzip",

  ".tbz"          =>      "application/x-bzip-compressed-tar",

  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"

 )

static-file.exclude-extensions = ( ".php", ".pl", ".fcgi", ".sh" )

dir-listing.activate       = "enable"

cgi.assign                 = ( ".sh"  => "" )
</code>```

Any help? TIA.

p.s:
yes, the script is executable.

答: Try running the script by hand on the server.  Does it run?  Verify that the first line is '#!/bin/bash' and that /bin/bash is installed on your system.  I am going to guess that it is not installed.  Try "#!/bin/sh" instead on your embedded system.</p>

Body:
I setup OpenWrt/lighttpd with lighttpd-mod-cgi on 3020 according to documentation. But when I connect to router and open the test.sh script's url from browser, just a white page is shown.
Checked lighttpd error log to find this:

(mod_cgi.c.1313) cleaning up CGI: process died with signal 6

test.sh:

#!/bin/bash
echo "Content-type: text/html"
echo ""

echo 'Hello World'

lighttpd.conf:

server.modules              = ( "mod_cgi" )

server.errorlog             = "/var/logs/lighttpd/error.log"

index-file.names            = ( "index.php", "index.html",

                                "index.htm", "default.htm" )

# mimetype mapping

mimetype.assign             = (

  ".pdf"          =>      "application/pdf",

  ".sig"          =>      "application/pgp-signature",

  ".spl"          =>      "application/futuresplash",

  ".class"        =>      "application/octet-stream",

  ".ps"           =>      "application/postscript",

  ".torrent"      =>      "application/x-bittorrent",

  ".dvi"          =>      "application/x-dvi",

  ".gz"           =>      "application/x-gzip",

  ".pac"          =>      "application/x-ns-proxy-autoconfig",

  ".swf"          =>      "application/x-shockwave-flash",

  ".tar.gz"       =>      "application/x-tgz",

  ".tgz"          =>      "application/x-tgz",

  ".tar"          =>      "application/x-tar",

  ".zip"          =>      "application/zip",

  ".mp3"          =>      "audio/mpeg",

  ".m3u"          =>      "audio/x-mpegurl",

  ".wma"          =>      "audio/x-ms-wma",

  ".wax"          =>      "audio/x-ms-wax",

  ".ogg"          =>      "application/ogg",

  ".wav"          =>      "audio/x-wav",

  ".gif"          =>      "image/gif",

  ".jpg"          =>      "image/jpeg",

  ".jpeg"         =>      "image/jpeg",

  ".png"          =>      "image/png",

  ".xbm"          =>      "image/x-xbitmap",

  ".xpm"          =>      "image/x-xpixmap",

  ".xwd"          =>      "image/x-xwindowdump",

  ".css"          =>      "text/css",

  ".html"         =>      "text/html",

  ".htm"          =>      "text/html",

  ".js"           =>      "text/javascript",

  ".asc"          =>      "text/plain",

  ".c"            =>      "text/plain",

  ".cpp"          =>      "text/plain",

  ".log"          =>      "text/plain",

  ".conf"         =>      "text/plain",

  ".text"         =>      "text/plain",

  ".txt"          =>      "text/plain",

  ".dtd"          =>      "text/xml",

  ".xml"          =>      "text/xml",

  ".mpeg"         =>      "video/mpeg",

  ".mpg"          =>      "video/mpeg",

  ".mov"          =>      "video/quicktime",

  ".qt"           =>      "video/quicktime",

  ".avi"          =>      "video/x-msvideo",

  ".asf"          =>      "video/x-ms-asf",

  ".asx"          =>      "video/x-ms-asf",

  ".wmv"          =>      "video/x-ms-wmv",

  ".bz2"          =>      "application/x-bzip",

  ".tbz"          =>      "application/x-bzip-compressed-tar",

  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"

 )

static-file.exclude-extensions = ( ".php", ".pl", ".fcgi", ".sh" )

dir-listing.activate       = "enable"

cgi.assign                 = ( ".sh"  => "" )

Any help? TIA.

p.s:
yes, the script is executable.


问:
Implementing Disjoint Sets (Union Find) in C++
I am trying to implement Disjoint Sets for use in Kruskal's algorithm, but I am having trouble understanding exactly how it should be done and in particular, how to manage the forest of trees. After reading the Wikipedia description of Disjoint Sets and after reading the description in Introduction to Algorithms (Cormen et al) I have come up with the following:

```<code>    class DisjointSet
    {
    public:
        class   Node
        {
        public:
            int         data;
            int         rank;

            Node*       parent;

            Node() : data(0),
                     rank(0),
                     parent(this) { } // the constructor does MakeSet
        };

        Node*   find(Node*);
        Node*   merge(Node*, Node*); // Union
    };

    DisjointSet::Node*   DisjointSet::find(DisjointSet::Node* n)
    {
        if (n != n->parent) {
            n->parent = find(n->parent);
        }
        return n->parent;
    }

    DisjointSet::Node* DisjointSet::merge(DisjointSet::Node* x,
                                          DisjointSet::Node* y)
    {
        x = find(x);
        y = find(y);

        if (x->rank > y->rank) {
            y->parent = x;
        } else {
            x->parent = y;
            if (x->rank == y->rank) {
                ++(y->rank);
            }
        }
    }
</code>```

I am pretty sure this is incomplete though and that I am missing something.

Introduction to Algorithms mentions that there should be a forest of trees, but it does not give any explanation for a practical implementation of this forest. I watched CS 61B Lecture 31: Disjoint Sets ( http://www.youtube.com/watch?v=wSPAjGfDl7Q ) and here the lecturer uses only an array to store both the forest and all its trees and values. There is no explicit 'Node' type of class as I have, mentioned. I have also found many other sources (I cannot post more than one link), which also use this technique. I would be happy to do this, except that this relies on the indices of the array for lookup and since I want to store values of type other than int, I need to use something else (std::map comes to mind).

Another issue that I am unsure about is memory allocation because I am using C++. I am storing trees of pointers and my MakeSet operation will be: new DisjointSet::Node; . Now, these Nodes only have pointers to their parents, so I'm not sure how to find the bottom of a tree. How will I be able to traverse my trees to deallocate them all?

I understand the basic concept of this data structure, but I'm just a bit confused about the implementation. Any advice and suggestions would be most welcome, thank you.

答:
Not a perfect implementation by any means (I did write it after all!), but does this help?</p>

```<code>/***
 * millipede: DisjointSetForest.h
 * Copyright Stuart Golodetz, 2009. All rights reserved.
 ***/

#ifndef H_MILLIPEDE_DISJOINTSETFOREST
#define H_MILLIPEDE_DISJOINTSETFOREST

#include <map>

#include <common/exceptions/Exception.h>
#include <common/io/util/OSSWrapper.h>
#include <common/util/NullType.h>

namespace mp {

/**
@brief  A disjoint set forest is a fairly standard data structure used to represent the partition of
        a set of elements into disjoint sets in such a way that common operations such as merging two
        sets together are computationally efficient.

This implementation uses the well-known union-by-rank and path compression optimizations, which together
yield an amortised complexity for key operations of O(a(n)), where a is the (extremely slow-growing)
inverse of the Ackermann function.

The implementation also allows clients to attach arbitrary data to each element, which can be useful for
some algorithms.

@tparam T   The type of data to attach to each element (arbitrary)
*/
template <typename T = NullType>
class DisjointSetForest
{
    //#################### NESTED CLASSES ####################
private:
    struct Element
    {
        T m_value;
        int m_parent;
        int m_rank;

        Element(const T& value, int parent)
        :   m_value(value), m_parent(parent), m_rank(0)
        {}
    };

    //#################### PRIVATE VARIABLES ####################
private:
    mutable std::map<int,Element> m_elements;
    int m_setCount;

    //#################### CONSTRUCTORS ####################
public:
    /**
    @brief  Constructs an empty disjoint set forest.
    */
    DisjointSetForest()
    :   m_setCount(0)
    {}

    /**
    @brief  Constructs a disjoint set forest from an initial set of elements and their associated values.

    @param[in]  initialElements     A map from the initial elements to their associated values
    */
    explicit DisjointSetForest(const std::map<int,T>& initialElements)
    :   m_setCount(0)
    {
        add_elements(initialElements);
    }

    //#################### PUBLIC METHODS ####################
public:
    /**
    @brief  Adds a single element x (and its associated value) to the disjoint set forest.

    @param[in]  x       The index of the element
    @param[in]  value   The value to initially associate with the element
    @pre
        -   x must not already be in the disjoint set forest
    */
    void add_element(int x, const T& value = T())
    {
        m_elements.insert(std::make_pair(x, Element(value, x)));
        ++m_setCount;
    }

    /**
    @brief  Adds multiple elements (and their associated values) to the disjoint set forest.

    @param[in]  elements    A map from the elements to add to their associated values
    @pre
        -   None of the elements to be added must already be in the disjoint set forest
    */
    void add_elements(const std::map<int,T>& elements)
    {
        for(typename std::map<int,T>::const_iterator it=elements.begin(), iend=elements.end(); it!=iend; ++it)
        {
            m_elements.insert(std::make_pair(it->first, Element(it->second, it->first)));
        }
        m_setCount += elements.size();
    }

    /**
    @brief  Returns the number of elements in the disjoint set forest.

    @return As described
    */
    int element_count() const
    {
        return static_cast<int>(m_elements.size());
    }

    /**
    @brief  Finds the index of the root element of the tree containing x in the disjoint set forest.

    @param[in]  x   The element whose set to determine
    @pre
        -   x must be an element in the disjoint set forest
    @throw Exception
        -   If the precondition is violated
    @return As described
    */
    int find_set(int x) const
    {
        Element& element = get_element(x);
        int& parent = element.m_parent;
        if(parent != x)
        {
            parent = find_set(parent);
        }
        return parent;
    }

    /**
    @brief  Returns the current number of disjoint sets in the forest (i.e. the current number of trees).

    @return As described
    */
    int set_count() const
    {
        return m_setCount;
    }

    /**
    @brief  Merges the disjoint sets containing elements x and y.

    If both elements are already in the same disjoint set, this is a no-op.

    @param[in]  x   The first element
    @param[in]  y   The second element
    @pre
        -   Both x and y must be elements in the disjoint set forest
    @throw Exception
        -   If the precondition is violated
    */
    void union_sets(int x, int y)
    {
        int setX = find_set(x);
        int setY = find_set(y);
        if(setX != setY) link(setX, setY);
    }

    /**
    @brief  Returns the value associated with element x.

    @param[in]  x   The element whose value to return
    @pre
        -   x must be an element in the disjoint set forest
    @throw Exception
        -   If the precondition is violated
    @return As described
    */
    T& value_of(int x)
    {
        return get_element(x).m_value;
    }

    /**
    @brief  Returns the value associated with element x.

    @param[in]  x   The element whose value to return
    @pre
        -   x must be an element in the disjoint set forest
    @throw Exception
        -   If the precondition is violated
    @return As described
    */
    const T& value_of(int x) const
    {
        return get_element(x).m_value;
    }

    //#################### PRIVATE METHODS ####################
private:
    Element& get_element(int x) const
    {
        typename std::map<int,Element>::iterator it = m_elements.find(x);
        if(it != m_elements.end()) return it->second;
        else throw Exception(OSSWrapper() << "No such element: " << x);
    }

    void link(int x, int y)
    {
        Element& elementX = get_element(x);
        Element& elementY = get_element(y);
        int& rankX = elementX.m_rank;
        int& rankY = elementY.m_rank;
        if(rankX > rankY)
        {
            elementY.m_parent = x;
        }
        else
        {
            elementX.m_parent = y;
            if(rankX == rankY) ++rankY;
        }
        --m_setCount;
    }
};

}

#endif
</code>```

Body:
I am trying to implement Disjoint Sets for use in Kruskal's algorithm, but I am having trouble understanding exactly how it should be done and in particular, how to manage the forest of trees. After reading the Wikipedia description of Disjoint Sets and after reading the description in Introduction to Algorithms (Cormen et al) I have come up with the following:

    class DisjointSet
    {
    public:
        class   Node
        {
        public:
            int         data;
            int         rank;

            Node*       parent;

            Node() : data(0),
                     rank(0),
                     parent(this) { } // the constructor does MakeSet
        };

        Node*   find(Node*);
        Node*   merge(Node*, Node*); // Union
    };

    DisjointSet::Node*   DisjointSet::find(DisjointSet::Node* n)
    {
        if (n != n->parent) {
            n->parent = find(n->parent);
        }
        return n->parent;
    }

    DisjointSet::Node* DisjointSet::merge(DisjointSet::Node* x,
                                          DisjointSet::Node* y)
    {
        x = find(x);
        y = find(y);

        if (x->rank > y->rank) {
            y->parent = x;
        } else {
            x->parent = y;
            if (x->rank == y->rank) {
                ++(y->rank);
            }
        }
    }

I am pretty sure this is incomplete though and that I am missing something.

Introduction to Algorithms mentions that there should be a forest of trees, but it does not give any explanation for a practical implementation of this forest. I watched CS 61B Lecture 31: Disjoint Sets ( http://www.youtube.com/watch?v=wSPAjGfDl7Q ) and here the lecturer uses only an array to store both the forest and all its trees and values. There is no explicit 'Node' type of class as I have, mentioned. I have also found many other sources (I cannot post more than one link), which also use this technique. I would be happy to do this, except that this relies on the indices of the array for lookup and since I want to store values of type other than int, I need to use something else (std::map comes to mind).

Another issue that I am unsure about is memory allocation because I am using C++. I am storing trees of pointers and my MakeSet operation will be: new DisjointSet::Node; . Now, these Nodes only have pointers to their parents, so I'm not sure how to find the bottom of a tree. How will I be able to traverse my trees to deallocate them all?

I understand the basic concept of this data structure, but I'm just a bit confused about the implementation. Any advice and suggestions would be most welcome, thank you.

Body:
Not a perfect implementation by any means (I did write it after all!), but does this help?

/***
 * millipede: DisjointSetForest.h
 * Copyright Stuart Golodetz, 2009. All rights reserved.
 ***/

#ifndef H_MILLIPEDE_DISJOINTSETFOREST
#define H_MILLIPEDE_DISJOINTSETFOREST

#include <map>

#include <common/exceptions/Exception.h>
#include <common/io/util/OSSWrapper.h>
#include <common/util/NullType.h>

namespace mp {

/**
@brief  A disjoint set forest is a fairly standard data structure used to represent the partition of
        a set of elements into disjoint sets in such a way that common operations such as merging two
        sets together are computationally efficient.

This implementation uses the well-known union-by-rank and path compression optimizations, which together
yield an amortised complexity for key operations of O(a(n)), where a is the (extremely slow-growing)
inverse of the Ackermann function.

The implementation also allows clients to attach arbitrary data to each element, which can be useful for
some algorithms.

@tparam T   The type of data to attach to each element (arbitrary)
*/
template <typename T = NullType>
class DisjointSetForest
{
    //#################### NESTED CLASSES ####################
private:
    struct Element
    {
        T m_value;
        int m_parent;
        int m_rank;

        Element(const T& value, int parent)
        :   m_value(value), m_parent(parent), m_rank(0)
        {}
    };

    //#################### PRIVATE VARIABLES ####################
private:
    mutable std::map<int,Element> m_elements;
    int m_setCount;

    //#################### CONSTRUCTORS ####################
public:
    /**
    @brief  Constructs an empty disjoint set forest.
    */
    DisjointSetForest()
    :   m_setCount(0)
    {}

    /**
    @brief  Constructs a disjoint set forest from an initial set of elements and their associated values.

    @param[in]  initialElements     A map from the initial elements to their associated values
    */
    explicit DisjointSetForest(const std::map<int,T>& initialElements)
    :   m_setCount(0)
    {
        add_elements(initialElements);
    }

    //#################### PUBLIC METHODS ####################
public:
    /**
    @brief  Adds a single element x (and its associated value) to the disjoint set forest.

    @param[in]  x       The index of the element
    @param[in]  value   The value to initially associate with the element
    @pre
        -   x must not already be in the disjoint set forest
    */
    void add_element(int x, const T& value = T())
    {
        m_elements.insert(std::make_pair(x, Element(value, x)));
        ++m_setCount;
    }

    /**
    @brief  Adds multiple elements (and their associated values) to the disjoint set forest.

    @param[in]  elements    A map from the elements to add to their associated values
    @pre
        -   None of the elements to be added must already be in the disjoint set forest
    */
    void add_elements(const std::map<int,T>& elements)
    {
        for(typename std::map<int,T>::const_iterator it=elements.begin(), iend=elements.end(); it!=iend; ++it)
        {
            m_elements.insert(std::make_pair(it->first, Element(it->second, it->first)));
        }
        m_setCount += elements.size();
    }

    /**
    @brief  Returns the number of elements in the disjoint set forest.

    @return As described
    */
    int element_count() const
    {
        return static_cast<int>(m_elements.size());
    }

    /**
    @brief  Finds the index of the root element of the tree containing x in the disjoint set forest.

    @param[in]  x   The element whose set to determine
    @pre
        -   x must be an element in the disjoint set forest
    @throw Exception
        -   If the precondition is violated
    @return As described
    */
    int find_set(int x) const
    {
        Element& element = get_element(x);
        int& parent = element.m_parent;
        if(parent != x)
        {
            parent = find_set(parent);
        }
        return parent;
    }

    /**
    @brief  Returns the current number of disjoint sets in the forest (i.e. the current number of trees).

    @return As described
    */
    int set_count() const
    {
        return m_setCount;
    }

    /**
    @brief  Merges the disjoint sets containing elements x and y.

    If both elements are already in the same disjoint set, this is a no-op.

    @param[in]  x   The first element
    @param[in]  y   The second element
    @pre
        -   Both x and y must be elements in the disjoint set forest
    @throw Exception
        -   If the precondition is violated
    */
    void union_sets(int x, int y)
    {
        int setX = find_set(x);
        int setY = find_set(y);
        if(setX != setY) link(setX, setY);
    }

    /**
    @brief  Returns the value associated with element x.

    @param[in]  x   The element whose value to return
    @pre
        -   x must be an element in the disjoint set forest
    @throw Exception
        -   If the precondition is violated
    @return As described
    */
    T& value_of(int x)
    {
        return get_element(x).m_value;
    }

    /**
    @brief  Returns the value associated with element x.

    @param[in]  x   The element whose value to return
    @pre
        -   x must be an element in the disjoint set forest
    @throw Exception
        -   If the precondition is violated
    @return As described
    */
    const T& value_of(int x) const
    {
        return get_element(x).m_value;
    }

    //#################### PRIVATE METHODS ####################
private:
    Element& get_element(int x) const
    {
        typename std::map<int,Element>::iterator it = m_elements.find(x);
        if(it != m_elements.end()) return it->second;
        else throw Exception(OSSWrapper() << "No such element: " << x);
    }

    void link(int x, int y)
    {
        Element& elementX = get_element(x);
        Element& elementY = get_element(y);
        int& rankX = elementX.m_rank;
        int& rankY = elementY.m_rank;
        if(rankX > rankY)
        {
            elementY.m_parent = x;
        }
        else
        {
            elementX.m_parent = y;
            if(rankX == rankY) ++rankY;
        }
        --m_setCount;
    }
};

}

#endif


问:
How to debug in HTML
I am trying to implement a little code in HTML; calling a PHP onclick in HTML using the solution here and it just runs to a blank page. Upon inspection, I noticed a typo in my code but after i corrected it the output is still the same i.e. it opens a blank page with no echo or anything.

My question: Is there a way to debug my code so my browser (i suspect) can notify me as to what part or line of my code the error is coming from, like in Java IDEs?

```<code><?php
function working(){
    echo 'WORKED ';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dice Game</title>
</head>
<body>
<div>
<div>
    <h1 id="player1" onclick="document.write('<?php working(); ?>')">
        ENTER PLAYER 1 NAME
    </h1>
</div>
</div>
</body>
</html>
</code>```

Note: I use Chrome

答: On Chrome or Firefox use F12 to Debug (Window) or simply right click any in page select Inspect Elements then choose Console tabs

Title: How to debug in HTML

Body:
I am trying to implement a little code in HTML; calling a PHP onclick in HTML using the solution here and it just runs to a blank page. Upon inspection, I noticed a typo in my code but after i corrected it the output is still the same i.e. it opens a blank page with no echo or anything.

My question: Is there a way to debug my code so my browser (i suspect) can notify me as to what part or line of my code the error is coming from, like in Java IDEs?

<?php
function working(){
    echo 'WORKED ';
}
?>
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Dice Game</title>

    <h1 id="player1" onclick="document.write('<?php working(); ?>')">
        ENTER PLAYER 1 NAME

Note: I use Chrome


问:
What does declaring { get } with a property imply?
I came across a piece of code that had a property declared like this:

```<code>var category: String { get }
</code>```

What does it signify? can we also declare such a property in a class and not in a protocol?

答:
That line expresses the requirement of conforming types to have a variable called category, of type String, with at least a getter.

Such a requirement could be satisfied in a conforming type with a let constant, a var variable, or a computed var.

Body:
I came across a piece of code that had a property declared like this:

var category: String { get }

What does it signify? can we also declare such a property in a class and not in a protocol?


问:
What's the LINQ expression of this SQL code?
This is my SQL statement:

```<code>SELECT p.*
FROM p
LEFT JOIN q ON p.id = q.id AND p.name = q.name
WHERE q.id IS null
</code>```

I'm trying to convert this code to a LINQ expression.

答:
```<code>var query = from t1 in p
            join q1 in q on t1.name equals q1.name
            where q1.id == null
            select t1;
</code>```

Body:
This is my SQL statement:

SELECT p.*
FROM p
LEFT JOIN q ON p.id = q.id AND p.name = q.name
WHERE q.id IS null

I'm trying to convert this code to a LINQ expression.


问:
InputBox Cancel different from vbNullString (null)
I want to use an InputBox for checking password.

If the user presses "OK" without data entry, the InputBox should run again, and if the user pressed "Cancel" or "ESC", corporate subroutine have exit.

How can I recognize "ESC" or "Cancel" input, different from just "null" or empty?

And how specially do that for my customize created Input box with API, so for changing key-pressed shown as "*" in password input, named as InputBoxDk:

```<code>'API functions to be used
Private Declare Function CallNextHookEx _
Lib "user32" ( _
ByVal hHook As Long, _
ByVal ncode As Long, _
ByVal wParam As Long, _
lParam As Any) _
As Long

Private Declare Function GetModuleHandle _
Lib "kernel32" _
Alias "GetModuleHandleA" ( _
ByVal lpModuleName As String) _
As Long

Private Declare Function SetWindowsHookEx _
Lib "user32" _
Alias "SetWindowsHookExA" ( _
ByVal idHook As Long, _
ByVal lpfn As Long, _
ByVal hmod As Long, _
ByVal dwThreadId As Long) _
As Long

Private Declare Function UnhookWindowsHookEx _
Lib "user32" ( _
ByVal hHook As Long) _
As Long

Private Declare Function SendDlgItemMessage _
Lib "user32" Alias "SendDlgItemMessageA" ( _
ByVal hDlg As Long, _
ByVal nIDDlgItem As Long, _
ByVal wMsg As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) _
As Long

Private Declare Function GetClassName _
Lib "user32" _
Alias "GetClassNameA" ( _
ByVal hWnd As Long, _
ByVal lpClassName As String, _
ByVal nMaxCount As Long) _
As Long

Private Declare Function GetCurrentThreadId _
Lib "kernel32" () _
As Long

Private Declare Sub sapiSleep Lib "kernel32" _
    Alias "Sleep" _
    (ByVal dwMilliseconds As Long)
'Constants to be used in our API functions
Private Const EM_SETPASSWORDCHAR = &HCC
Private Const WH_CBT = 5
Private Const HCBT_ACTIVATE = 5
Private Const HC_ACTION = 0

Private hHook As Long

Public Function NewProc(ByVal lngCode As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) As Long

Dim RetVal
Dim strClassName As String, lngBuffer As Long

If lngCode < HC_ACTION Then
    NewProc = CallNextHookEx(hHook, lngCode, wParam, lParam)
    Exit Function
End If

strClassName = String$(256, " ")
lngBuffer = 255

If lngCode = HCBT_ACTIVATE Then 'A window has been activated
    RetVal = GetClassName(wParam, strClassName, lngBuffer)
    If Left$(strClassName, RetVal) = "#32770" Then 'Class name of the Inputbox
         'This changes the edit control so that it display the password character *.
         'You can change the Asc("*") as you please.
        SendDlgItemMessage wParam, &H1324, EM_SETPASSWORDCHAR, Asc("*"), &H0
    End If
End If

 'This line will ensure that any other hooks that may be in place are
 'called correctly.
CallNextHookEx hHook, lngCode, wParam, lParam

End Function

'// Make it public = avail to ALL Modules
 '// Lets simulate the VBA Input Function
Public Function InputBoxDK(Prompt As String, Optional Title As String, _
Optional Default As String, _
Optional Xpos As Long, _
Optional Ypos As Long, _
Optional Helpfile As String, _
Optional Context As Long) As String

Dim lngModHwnd As Long, lngThreadID As Long

 '// Lets handle any Errors JIC! due to HookProc> App hang!
On Error GoTo ExitProperly
lngThreadID = GetCurrentThreadId
lngModHwnd = GetModuleHandle(vbNullString)

hHook = SetWindowsHookEx(WH_CBT, AddressOf NewProc, lngModHwnd, lngThreadID)
If Xpos Then
    InputBoxDK = InputBox(Prompt, Title, Default, Xpos, Ypos, Helpfile, Context)
Else
    InputBoxDK = InputBox(Prompt, Title, Default, , , Helpfile, Context)
End If

ExitProperly:
UnhookWindowsHookEx hHook

End Function

Sub TestDKInputBox()
Dim x

x = InputBoxDK("Type your password here.", "Password Required")
If x = "" Then End
If x <> "yourpassword" Then
    MsgBox "You didn't enter a correct password."
    End
End If

MsgBox "Welcome Creator!", vbExclamation

End Sub
</code>```

Code reference: http://www.ozgrid.com

答:
```<code>InputBox("prompt", "title", "default")
</code>```

I can't test it, but If the user clicks OK the result should be "default". If something else is clicked the result should be "". If the user clears the input and clicks OK, the result is "" too. There is no way to make sure that OK was clicked in a InputBox, so you might need a custom UserForm for that.

Body:
I want to use an InputBox for checking password.

If the user presses "OK" without data entry, the InputBox should run again, and if the user pressed "Cancel" or "ESC", corporate subroutine have exit.

How can I recognize "ESC" or "Cancel" input, different from just "null" or empty?

And how specially do that for my customize created Input box with API, so for changing key-pressed shown as "*" in password input, named as InputBoxDk:

'API functions to be used
Private Declare Function CallNextHookEx _
Lib "user32" ( _
ByVal hHook As Long, _
ByVal ncode As Long, _
ByVal wParam As Long, _
lParam As Any) _
As Long

Private Declare Function GetModuleHandle _
Lib "kernel32" _
Alias "GetModuleHandleA" ( _
ByVal lpModuleName As String) _
As Long

Private Declare Function SetWindowsHookEx _
Lib "user32" _
Alias "SetWindowsHookExA" ( _
ByVal idHook As Long, _
ByVal lpfn As Long, _
ByVal hmod As Long, _
ByVal dwThreadId As Long) _
As Long

Private Declare Function UnhookWindowsHookEx _
Lib "user32" ( _
ByVal hHook As Long) _
As Long

Private Declare Function SendDlgItemMessage _
Lib "user32" Alias "SendDlgItemMessageA" ( _
ByVal hDlg As Long, _
ByVal nIDDlgItem As Long, _
ByVal wMsg As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) _
As Long

Private Declare Function GetClassName _
Lib "user32" _
Alias "GetClassNameA" ( _
ByVal hWnd As Long, _
ByVal lpClassName As String, _
ByVal nMaxCount As Long) _
As Long

Private Declare Function GetCurrentThreadId _
Lib "kernel32" () _
As Long

Private Declare Sub sapiSleep Lib "kernel32" _
    Alias "Sleep" _
    (ByVal dwMilliseconds As Long)
'Constants to be used in our API functions
Private Const EM_SETPASSWORDCHAR = &HCC
Private Const WH_CBT = 5
Private Const HCBT_ACTIVATE = 5
Private Const HC_ACTION = 0

Private hHook As Long

Public Function NewProc(ByVal lngCode As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) As Long

Dim RetVal
Dim strClassName As String, lngBuffer As Long

If lngCode < HC_ACTION Then
    NewProc = CallNextHookEx(hHook, lngCode, wParam, lParam)
    Exit Function
End If

strClassName = String$(256, " ")
lngBuffer = 255

If lngCode = HCBT_ACTIVATE Then 'A window has been activated
    RetVal = GetClassName(wParam, strClassName, lngBuffer)
    If Left$(strClassName, RetVal) = "#32770" Then 'Class name of the Inputbox
         'This changes the edit control so that it display the password character *.
         'You can change the Asc("*") as you please.
        SendDlgItemMessage wParam, &H1324, EM_SETPASSWORDCHAR, Asc("*"), &H0
    End If
End If

 'This line will ensure that any other hooks that may be in place are
 'called correctly.
CallNextHookEx hHook, lngCode, wParam, lParam

End Function

'// Make it public = avail to ALL Modules
 '// Lets simulate the VBA Input Function
Public Function InputBoxDK(Prompt As String, Optional Title As String, _
Optional Default As String, _
Optional Xpos As Long, _
Optional Ypos As Long, _
Optional Helpfile As String, _
Optional Context As Long) As String

Dim lngModHwnd As Long, lngThreadID As Long

 '// Lets handle any Errors JIC! due to HookProc> App hang!
On Error GoTo ExitProperly
lngThreadID = GetCurrentThreadId
lngModHwnd = GetModuleHandle(vbNullString)

hHook = SetWindowsHookEx(WH_CBT, AddressOf NewProc, lngModHwnd, lngThreadID)
If Xpos Then
    InputBoxDK = InputBox(Prompt, Title, Default, Xpos, Ypos, Helpfile, Context)
Else
    InputBoxDK = InputBox(Prompt, Title, Default, , , Helpfile, Context)
End If

ExitProperly:
UnhookWindowsHookEx hHook

End Function

Sub TestDKInputBox()
Dim x

x = InputBoxDK("Type your password here.", "Password Required")
If x = "" Then End
If x <> "yourpassword" Then
    MsgBox "You didn't enter a correct password."
    End
End If

MsgBox "Welcome Creator!", vbExclamation

End Sub

Code reference: http://www.ozgrid.com

Body:
InputBox("prompt", "title", "default")

I can't test it, but If the user clicks OK the result should be "default". If something else is clicked the result should be "". If the user clears the input and clicks OK, the result is "" too. There is no way to make sure that OK was clicked in a InputBox, so you might need a custom UserForm for that.


问:
Extract entities from Simple passive voice sentence by Python Spacy
Using Python Spacy, how to extract entity from simple passive voice sentence? In the follow sentence, my intention is to extract both "John”  from the sentence as nsubjpass and .ent_.

sentence =  "John was accused of crimes by David"

答: Go through the spacy 2.0 nightly build. It should have the solution you're looking for.</p>


问:
Selenium Java - ElementNotInteractableException upon trying to click a link
Within the program I'm trying to make I need to click on links from a variety of websites by searching for links including the word "team". I'm getting an error on a few websites I try it on though, and not on others, any idea why and any fixes available?
My code segment is as follows:

```<code>if (driver.getPageSource().contains("Team"))
{
     driver.findElement(By.partialLinkText("Team")).click();
     return;
}
</code>```

This works on some websites, however on others I'm getting

```<code>Exception in thread "AWT-EventQueue-0" org.openqa.selenium.ElementNotInteractableException:
</code>```

I don't know the source of this problem however, as I need it to work on multiple pages, for example I get that response on https://www.calipercorp.com/about-us/

Any workarounds or help given would be greatly appreciated.

答:
As you want to find a Link with Partial Text. Your approach will be time consuming.

I would suggest to go with xpath as it is easy and less code.

```<code>//a[contains(text(),'Team')]
</code>```

Sometimes the element's are not visible/clickable. Also sometimes href's are relative. To overcome that go with Javascript click

To check the presence of element use findElements don't go with pageSource.

```<code>List<WebElement> teamEls=driver.findElement(By.xpath("//a[contains(text(),'Team')]"));
if(!teamEls.isEmpty())
{
   WebElement team = teamEls.get(0);
   if(team.isDisplayed())
   {
      team.click();
   }
   else
   {
       JavascriptExecutor js = (JavascriptExecutor) driver;
       js.executeScript("arguments[0].click();", team);
   }

}
</code>```

Body:
Within the program I'm trying to make I need to click on links from a variety of websites by searching for links including the word "team". I'm getting an error on a few websites I try it on though, and not on others, any idea why and any fixes available?
My code segment is as follows:

if (driver.getPageSource().contains("Team"))
{
     driver.findElement(By.partialLinkText("Team")).click();
     return;
}

This works on some websites, however on others I'm getting

Exception in thread "AWT-EventQueue-0" org.openqa.selenium.ElementNotInteractableException:

I don't know the source of this problem however, as I need it to work on multiple pages, for example I get that response on https://www.calipercorp.com/about-us/

Any workarounds or help given would be greatly appreciated.

Body:
As you want to find a Link with Partial Text. Your approach will be time consuming.

I would suggest to go with xpath as it is easy and less code.

//a[contains(text(),'Team')]

Sometimes the element's are not visible/clickable. Also sometimes href's are relative. To overcome that go with Javascript click

To check the presence of element use findElements don't go with pageSource.

List<WebElement> teamEls=driver.findElement(By.xpath("//a[contains(text(),'Team')]"));
if(!teamEls.isEmpty())
{
   WebElement team = teamEls.get(0);
   if(team.isDisplayed())
   {
      team.click();
   }
   else
   {
       JavascriptExecutor js = (JavascriptExecutor) driver;
       js.executeScript("arguments[0].click();", team);
   }

}