问:
Converting an image_tag into a link that goes to the destroy route
I would like to convert this line of code into a link that goes to the destroy route in my routes table.  When this picture is pressed it will delete the current photo.

```<code><%= image_tag @user.avatar.avatarpic %>
</code>```

The route is as follows:

```<code>user_avatar DELETE /users/:user_id/avatars/:id(.:format) avatars#destroy
</code>```

The Avatar controller is as follow:

```<code>class AvatarsController < ApplicationController

  def create
    @user = User.find(params[:user_id])
    @avatar = Avatar.new(avatar_params)
    @avatar.user = @user
    @avatar.save
    # Three lines above can be replaced with
    # @user.create_avatar(params)
    redirect_to user_path(@user)
  end

private

def avatar_params
  params.require(:avatar).permit(:avatarpic)
end

end
</code>```

Currently I have an if/else statement that will display a default image if an avatar photo isn't available:

```<code><% if @user.avatar.present? %>
  <%= image_tag @user.avatar.avatarpic %>
<% else %>
  <%= image_tag 'user.png' %>
  <a href="#" class="add-image" data-toggle="modal" data-
  target="#avatarpic">
    Add a Picture
  </a>
<% end %>
</code>```

I would also like for a message to display once the mouse is hovering over the current avatar photo.  It will say something to the effect of "Upload a different image".  Once pressed, there should be a warning that asks the user "Are you sure you would like to delete this image?".  Thank you for your help.

答:
I'm not in front of my PC but this should work:

```<code><%= link_to destroy_path, method: :delete, data: { confirm: 'Are you sure?' } do %>
   <%= image_tag @user.avatar.avatarpic %>
<% end %>
</code>```

Please try and let me know if it does.

Body:
I would like to convert this line of code into a link that goes to the destroy route in my routes table.  When this picture is pressed it will delete the current photo.

<%= image_tag @user.avatar.avatarpic %>

The route is as follows:

user_avatar DELETE /users/:user_id/avatars/:id(.:format) avatars#destroy

The Avatar controller is as follow:

class AvatarsController < ApplicationController

  def create
    @user = User.find(params[:user_id])
    @avatar = Avatar.new(avatar_params)
    @avatar.user = @user
    @avatar.save
    # Three lines above can be replaced with
    # @user.create_avatar(params)
    redirect_to user_path(@user)
  end

private

def avatar_params
  params.require(:avatar).permit(:avatarpic)
end

end

Currently I have an if/else statement that will display a default image if an avatar photo isn't available:

<% if @user.avatar.present? %>
  <%= image_tag @user.avatar.avatarpic %>
<% else %>
  <%= image_tag 'user.png' %>

    Add a Picture

<% end %>

I would also like for a message to display once the mouse is hovering over the current avatar photo.  It will say something to the effect of "Upload a different image".  Once pressed, there should be a warning that asks the user "Are you sure you would like to delete this image?".  Thank you for your help.

Body:
I'm not in front of my PC but this should work:

<%= link_to destroy_path, method: :delete, data: { confirm: 'Are you sure?' } do %>
   <%= image_tag @user.avatar.avatarpic %>
<% end %>

Please try and let me know if it does.


来源: stackexchange

问:
Game controller layout detection - swift
How do I detect the game controllers layout from apple tv? I want to change the controls if the layout is different for the controller which will make the game easier to play. .For example, the apple recommended Nimbus Controller is shaped like a play station controller with two joysticks at the bottom, but I have seem other types of controllers which have a xbox like design with a d-pad and a joystick at the bottom instead, if I can detect which is which, to change to controls for different controllers, it will make the game easier to play

Any help would be appreciated

答:
You should use controller profiles to map physical controls to game inputs.

Controllers are automatically discovered, a physical controller is represented by a GCController object, which ‘profiles’ the controllers controls such as GCGamepad, extendedGamepad etc. You should check which controls are registered to each controller.  From the documentation on Discovering And Connecting Controllers:

“After your app has finished launching, the operating system
  automatically creates a list of connected controllers. Call
  the controllers class method to retrieve an array
  of GCController objects for all connected controllers.”

In apples sample code they register for .GCControllerDidConnect Notifications and cast the notification object as a GCController instance to a function that set’s up the controls if they exist, parse the controller and assign the corresponding handler method:

```<code>NotificationCenter.default.addObserver(self, selector: #selector(GameViewController.handleControllerDidConnectNotification(_:)), name: .GCControllerDidConnect, object: nil)

@objc func handleControllerDidConnectNotification(_ notification: NSNotification) {
    let gameController = notification.object as! GCController
    registerCharacterMovementEvents(gameController)
}

  private func registerCharacterMovementEvents(_ gameController: GCController) {
      //…

    // Gamepad D-pad
    if let gamepad = gameController.gamepad {
        gamepad.dpad.valueChangedHandler = movementHandler
    }

    // Extended gamepad left thumbstick
    if let extendedGamepad = gameController.extendedGamepad {
        extendedGamepad.leftThumbstick.valueChangedHandler = movementHandler
    }

      //…
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You should use controller profiles to map physical controls to game inputs.

Controllers are automatically discovered, a physical controller is represented by a GCController object, which ‘profiles’ the controllers controls such as GCGamepad, extendedGamepad etc. You should check which controls are registered to each controller.  From the documentation on Discovering And Connecting Controllers:

“After your app has finished launching, the operating system
  automatically creates a list of connected controllers. Call
  the controllers class method to retrieve an array
  of GCController objects for all connected controllers.”

In apples sample code they register for .GCControllerDidConnect Notifications and cast the notification object as a GCController instance to a function that set’s up the controls if they exist, parse the controller and assign the corresponding handler method:

NotificationCenter.default.addObserver(self, selector: #selector(GameViewController.handleControllerDidConnectNotification(_:)), name: .GCControllerDidConnect, object: nil)

@objc func handleControllerDidConnectNotification(_ notification: NSNotification) {
    let gameController = notification.object as! GCController
    registerCharacterMovementEvents(gameController)
}

  private func registerCharacterMovementEvents(_ gameController: GCController) {
      //…

    // Gamepad D-pad
    if let gamepad = gameController.gamepad {
        gamepad.dpad.valueChangedHandler = movementHandler
    }

    // Extended gamepad left thumbstick
    if let extendedGamepad = gameController.extendedGamepad {
        extendedGamepad.leftThumbstick.valueChangedHandler = movementHandler
    }

      //…
  }


问:
jQuery how to replace text node for children of elements
I want to replace all text of children of elements.

such as this, I replace all text children of II.Maybe has other tag.
not only
 and
.

I

II

A

B

1

2

3

C

III

I want get like this:

I

II

test: A

test: B

test: 1

test: 2

test: 3

test: C

III

I try code it, but I fail.

Why the .find('*') is failure?

<!DOCTYPE html>

I

II

A

B

1

2

3

C

III

```
</div>
</div>
</p>

<p>I can not modify this HTML because it is not the code I wrote.
so I use js to modify it.</p>

<p>Thank!</p>

<h1>update</h1>

<p>I solve it, Thank anyone!</p>

<p>Text Node is not a <code>Elements</code>, so <code>find('*')</code> can not <strong>capture</strong> it. I find <code>contents()</code> can <strong>capture</strong> it.
This is My code</p>

```    $('ul.level-2').find('*').contents().filter(function () {
        return this.nodeType === 3 && !!this.textContent.trim();
    }).each(function () {
        this.textContent = 'test'+this.textContent
    });
```

答:
```<code>$('.level-2').find('li').toArray().forEach(function(e){
    e.innerHTML = 'test ' + e.innerHTML;
});

$('.level-3').find('li').toArray().forEach(function(e){
    e.innerHTML = 'test ' + e.innerHTML;
});
</code>```

Body:
I want to replace all text of children of elements.

such as this, I replace all text children of II.Maybe has other tag.
not only
 and
.

I

II

A

B

1

2

3

C

III

I want get like this:

I

II

test: A

test: B

test: 1

test: 2

test: 3

test: C

III

I try code it, but I fail.

Why the .find('*') is failure?

<!DOCTYPE html>

I

II

A

B

1

2

3

C

III

I can not modify this HTML because it is not the code I wrote.
so I use js to modify it.

Thank!

update

I solve it, Thank anyone!

Text Node is not a Elements, so find('*') can not capture it. I find contents() can capture it.
This is My code

    $('ul.level-2').find('*').contents().filter(function () {
        return this.nodeType === 3 && !!this.textContent.trim();
    }).each(function () {
        this.textContent = 'test'+this.textContent
    });


问:
long term session storage (php shopping cart)
this is more of a 'can you point me in the right direction' type of question.

Basically I would like to offer customers a way to 'save' their shopping cart, perhaps to view later with a relative (it's a 'photo basket' for a photographers clients).

When my 'photo basket' is used, it creates a single basket array that is then filled with item arrays.

My idea was --- create a table for each user and then implode each array in the $_SESSION['basket'] to a string and then add this string to a row in the DB. When the user logs back in, their saved basket can then be exploded from the database to form a new basket...

That's my chain of thought (not started this section yet). Just wondered if anyone could spot any obvious flaws and errors I might encounter.

Thanks for any input.

Shane

答:
as mention before, don't create table, create a row. There are few php carts that do that (cs-cart).
However, delete old baskets from the table after a while...</p>

ContentLicense: CC BY-SA 2.5


问:
How do I delete a node from a binary search tree
How do I implement a function to delete a node from a binary search tree? Below is my current function:

```<code>    void makeDeletion(TreeNode *&tree) {
    TreeNode *NodeToDelete;
    NodeToDelete = tree;
    TreeNode *InOrder;

    if (tree->right == NULL && tree->left == NULL) {
        delete NodeToDelete;
    }
    if (tree->right == NULL) {
        tree = tree->left;
        delete NodeToDelete;
    }
    else if (tree->left == NULL) {
        tree = tree->right;
        delete NodeToDelete;
    }
    else {
        InOrder = tree->right;
        while (InOrder->left != NULL) {
            InOrder = InOrder->left;
        }

        NodeToDelete->value = InOrder->value;
        remove(InOrder, InOrder->value);
    }
}
</code>```

And here is the remove function I have that locates the value to be deleted:

```<code>    void remove(TreeNode *&tree, ANY num) {//Removed Need for ">"
    if (tree == NULL){
        return;
    }

    if (tree->value == num) {
        makeDeletion(tree);
    } else if (num < tree->value) {
        remove(tree->left, num);
    } else {
        remove(tree->right, num);
    }
};//Remove
</code>```

As it stands I feel like I'm very close, but when I go to output the contents of the binary tree the program crashes. I am trying to use an approach where, if the node has two children, I locate the in order successor, swap the values of the nodes of the in order successor and the node to be "deleted," and then delete the in order successor. Without adjusting the remove function, what bit of information am I missing to make the makeDeletion function work as described?

EDIT: in the makeDeletion function I mistakenly wrote two if statements in succession. The second if statement should be an else if statement.

答: In makeDeletion, if tree is a leaf (both left and right are NULL), you delete the leaf node, and don't set tree = nullptr.  This leaves a dangling reference in your tree to memory that has been freed.  Also, you then dereference the (now deleted) node in the next if.  Either one of these can result in your crash.

Body:
How do I implement a function to delete a node from a binary search tree? Below is my current function:

    void makeDeletion(TreeNode *&tree) {
    TreeNode *NodeToDelete;
    NodeToDelete = tree;
    TreeNode *InOrder;

    if (tree->right == NULL && tree->left == NULL) {
        delete NodeToDelete;
    }
    if (tree->right == NULL) {
        tree = tree->left;
        delete NodeToDelete;
    }
    else if (tree->left == NULL) {
        tree = tree->right;
        delete NodeToDelete;
    }
    else {
        InOrder = tree->right;
        while (InOrder->left != NULL) {
            InOrder = InOrder->left;
        }

        NodeToDelete->value = InOrder->value;
        remove(InOrder, InOrder->value);
    }
}

And here is the remove function I have that locates the value to be deleted:

    void remove(TreeNode *&tree, ANY num) {//Removed Need for ">"
    if (tree == NULL){
        return;
    }

    if (tree->value == num) {
        makeDeletion(tree);
    } else if (num < tree->value) {
        remove(tree->left, num);
    } else {
        remove(tree->right, num);
    }
};//Remove

As it stands I feel like I'm very close, but when I go to output the contents of the binary tree the program crashes. I am trying to use an approach where, if the node has two children, I locate the in order successor, swap the values of the nodes of the in order successor and the node to be "deleted," and then delete the in order successor. Without adjusting the remove function, what bit of information am I missing to make the makeDeletion function work as described?

EDIT: in the makeDeletion function I mistakenly wrote two if statements in succession. The second if statement should be an else if statement.


问:
Unable to return value after implode
This is my array

```<code>Array
(
[0] => Array
    (
        [0] => SC1MTTCS6J1WK
    )

[1] => Array
    (
        [0] => SC1MTTCSHJ1WK
    )
)
</code>```

But when I try to implode them using

```<code>$in_text = implode(",", $myArray3);
</code>```

I can't get the value instead I got this:

```<code>Array,Array
</code>```

Please assist thank you.

答:
You call implode on an array of array, which result the Array, Array. You can call like this,

```<code>implode(",", array_column($myArray3, 0));
</code>```

Title: Unable to return value after implode

Body:
This is my array

Array
(
[0] => Array
    (
        [0] => SC1MTTCS6J1WK
    )

[1] => Array
    (
        [0] => SC1MTTCSHJ1WK
    )
)

But when I try to implode them using

$in_text = implode(",", $myArray3);

I can't get the value instead I got this:

Array,Array

Please assist thank you.

Body:
You call implode on an array of array, which result the Array, Array. You can call like this,

implode(",", array_column($myArray3, 0));


问:
Rails 3: Including an SQL function in a query
MyModel.select('a, b, c').all

This returns the following from a database:

```<code>+---+---+---+
| a | b | c |
+---+---+---+
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
+---+---+---+
</code>```

Question: How would I include a fourth column with the result of an SQL function?

i.e.

```<code>+---+---+---+---------------------+
| a | b | c | MYFUNCTION(a, b, c) |
+---+---+---+---------------------+
| 1 | 2 | 3 | 123                 |
| 4 | 5 | 6 | 456                 |
| 7 | 8 | 9 | 789                 |
+---+---+---+---------------------+
</code>```

The following didn't work:

MyModel.select('a, b, c, MYFUNCTION(a, b, c)').all

although, if I use AS to give the column the name of a valid model attribute, it works:

MyModel.select('a, b, MYFUNCTION(a, b, b) AS c').all

```<code>+---+---+-----+
| a | b |  c  |
+---+---+-----+
| 1 | 2 | 122 |
| 4 | 5 | 455 |
| 7 | 8 | 788 |
+---+---+-----+
</code>```

I would prefer to solve this within the context of the model rather than reverting to raw SQL as I also need to utilise scopes.

Any suggestions much appreciated.

答:
You can give any arbitrary name to the AS column, instead of giving an existing attribute.</p>

```<code>irb(main):009:0> u = User.select('id, id+1 as blah').first
=> #<User id: 1>
irb(main):010:0> u.id
=> 1
irb(main):011:0> u.blah
=> 2
irb(main):012:0>
</code>```

Body:
MyModel.select('a, b, c').all

This returns the following from a database:

+---+---+---+
| a | b | c |
+---+---+---+
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
+---+---+---+

Question: How would I include a fourth column with the result of an SQL function?

i.e.

+---+---+---+---------------------+
| a | b | c | MYFUNCTION(a, b, c) |
+---+---+---+---------------------+
| 1 | 2 | 3 | 123                 |
| 4 | 5 | 6 | 456                 |
| 7 | 8 | 9 | 789                 |
+---+---+---+---------------------+

The following didn't work:

MyModel.select('a, b, c, MYFUNCTION(a, b, c)').all

although, if I use AS to give the column the name of a valid model attribute, it works:

MyModel.select('a, b, MYFUNCTION(a, b, b) AS c').all

+---+---+-----+
| a | b |  c  |
+---+---+-----+
| 1 | 2 | 122 |
| 4 | 5 | 455 |
| 7 | 8 | 788 |
+---+---+-----+

I would prefer to solve this within the context of the model rather than reverting to raw SQL as I also need to utilise scopes.

Any suggestions much appreciated.

Body:
You can give any arbitrary name to the AS column, instead of giving an existing attribute.

irb(main):009:0> u = User.select('id, id+1 as blah').first
=> #<User id: 1>
irb(main):010:0> u.id
=> 1
irb(main):011:0> u.blah
=> 2
irb(main):012:0>


问:
Print character multiple times
How can I print a character multiple times in a single line? This means I cannot use a loop.

I'm trying to print " _" multiple times.

I tried this method but it's not working:

```<code>System.out.println (" _" , s);
</code>```

s is the variable.

答:
With one call to print/println, and using your variable "s":

```<code>System.out.println(Stream.generate(() -> " _").limit(s).collect(Collectors.joining()))
</code>```

ContentLicense: CC BY-SA 4.0

Title: Print character multiple times

Body:
How can I print a character multiple times in a single line? This means I cannot use a loop.

I'm trying to print " _" multiple times.

I tried this method but it's not working:

System.out.println (" _" , s);

s is the variable.

Body:
With one call to print/println, and using your variable "s":

System.out.println(Stream.generate(() -> " _").limit(s).collect(Collectors.joining()))


问:
ERROR: A JNI error has occurred, please check your installation and try again.NoClassDefFound error: DRPCExecutionException
When I am trying to connect to storm-topology(v1.0.2) throuch DRPC client request I am getting the following error:

ERROR: A JNI error has occurred, please check your installation and try again.
      exception in thread "main" java.lang.NoClassDefFoundError:org/apache/storm/generated/DRPCExecutionException

答: This (JNI error) is very common error, it occurs when you change your jdk version. To solve this error you have to change the compiler setting only. Just right click on project and go to properties then go to java compiler and then select compiler compliance level to your JDK version....that's it, done!</p>


问:
For the latest version of Lucene(4.8.0) ,how to custom scoring rules
In Lucene (v3.0) we can use CustomScoreProvider and CustomScoreQuer to customize scoring.

However, in the latest version of Lucene, I can not find those classes. What can I do?

答:
both the classes move to the Lucene.Net.Queries

And any other change , we can look at Apache Lucene Migration Guide


问:
Merge sorting an array with a size that is not 2^n
In every example of merge sort I have found, the algorithm is demonstrated on an array of size 8 or some other power of 2. This makes it easier to demonstrate, but doesn’t explain how to employ it on arrays of different sizes. How should you split up the sub arrays?</p>

答:
I think you're overthinking this problem. In the classical version of mergesort you continue breaking the input down until you have single-element sub-collections, which are by definition sorted - then you start merging the sub-collections back together. Breaking the collection down into single-element collections is mostly an exercise in allocating memory/creating collection objects and sticking one element in each.

The basic merge-sort function doesn't actually do very much at all. My Clojure (Lisp variant) implementation of mergesort looks like:

```<code>(defn merge-sort [compare-func col]
  (merge-runs compare-func (find-runs-of-3 compare-func col)))
</code>```

In other words, the input collection col is broken down into sub-collections of three elements and sorted, and then these three element subcollections are merged to get the final output. If the input collection isn't an exact multiple of three elements, that's OK - it just means there's going to be a "leftover" sub-collection of 1 or 2 elements to be sorted/merged in with all the rest.

(As to "why collections-of-three" - efficiency. First, breaking the collection to be sorted down into collections-of-1 requires three times more effort than breaking it down into collections-of-3. Then, too, you can sort a three-element collection using, on average, 2.66 comparisons instead of three, which saves 1/3 of a comparison for each sub-collection. Not much of a savings, perhaps, until you're sorting collections of 50K elements :-).

Best of luck.

Body:
I think you're overthinking this problem. In the classical version of mergesort you continue breaking the input down until you have single-element sub-collections, which are by definition sorted - then you start merging the sub-collections back together. Breaking the collection down into single-element collections is mostly an exercise in allocating memory/creating collection objects and sticking one element in each.

The basic merge-sort function doesn't actually do very much at all. My Clojure (Lisp variant) implementation of mergesort looks like:

(defn merge-sort [compare-func col]
  (merge-runs compare-func (find-runs-of-3 compare-func col)))

In other words, the input collection col is broken down into sub-collections of three elements and sorted, and then these three element subcollections are merged to get the final output. If the input collection isn't an exact multiple of three elements, that's OK - it just means there's going to be a "leftover" sub-collection of 1 or 2 elements to be sorted/merged in with all the rest.

(As to "why collections-of-three" - efficiency. First, breaking the collection to be sorted down into collections-of-1 requires three times more effort than breaking it down into collections-of-3. Then, too, you can sort a three-element collection using, on average, 2.66 comparisons instead of three, which saves 1/3 of a comparison for each sub-collection. Not much of a savings, perhaps, until you're sorting collections of 50K elements :-).

Best of luck.


问:
Does Intel SGX provide software memory protection in simulation mode?
I have some 4th generation Intel CPU and I want to run some Intel SGX application. I use release simulation mode.

Here you can see that SGX simulation doesn't provide HARDWARE protection! However, I would like to know if Intel SGX provides some kind of SOFTWARE protection in release simulation mode?

答:
No, the goal of simulation mode is to develop enclave on non-supporting platforms and to enable debug of enclaves.

In simulation mode, the enclave is running as a standard process in regular memory and can be debugged and accessed like any other process in the system.


问:
Verifying HMAC from Microsoft Teams custom Bot in PHP
I am trying to authenticate a Microsoft Teams custom Bot with PHP, following the Microsoft instructions and read de C# example code.

Microsoft Intructions steps:

  1. Generate the hmac from the request body of the message. There are standard libraries on most platforms. Microsoft Teams uses standard
  SHA256 HMAC cryptography. You will need to convert the body to a byte
  array in UTF8.

  2. To compute the hash, provide the byte array of the shared secret.

  3. Convert the hash to a string using UTF8 encoding.

  4. Compare the string value of the generated hash with the value provided in the HTTP request.

I had write a small php script to test this in local:

```<code>        <?php
        //Function to generate C# byte[] equivalent
        function unpak_str($val){
            $b = unpack('C*', $val);
            foreach ($b as $key => $value)
                $byte_a .= $value;

           return $byte_a;
          }

        //multi test outputs
        function hasher($values=[], &$output){
            //my secret share
            $secret="ejWiKHgsKY1ZfpJwJ+wIiN4+bgsFad/lkpu9/MWNXgM=";
            //diferent test
            $secret_64=base64_decode($secret);
            $secret_b=unpak_str($secret);
            $secret_b_64=unpak_str(base64_decode($secret));

            foreach($values as $msg){
                $hs = hash_hmac("sha256",$msg,$secret, true);
                $hs_64 = hash_hmac("sha256",$msg,$secret_64, true);
                $hs_b = hash_hmac("sha256",$msg,$secret_b, true);
                $hs_b_64 = hash_hmac("sha256",$msg,$secret_b_64, true);

                $output.=base64_encode($hs)." <BR>";
                $output.=base64_encode($hs_64)." <BR>";
                $output.=base64_encode($hs_b)." <BR>";
                $output.=base64_encode($hs_b_64)." <BR>";
             }
          }

    //Get data
    $data=file_get_contents('php://input');

    //real data request content for test
    $data ='{type":"message","id":"1512376018086","timestamp":"2017-12-04T08:26:58.237Z","localTimestamp":"2017-12-04T09:26:58.237+01:00","serviceUrl":"https://smba.trafficmanager.net/emea-client-ss.msg/","channelId":"msteams","from":{"id":"29:1aq6GCrC6lM9dv3YkAYi1gxTPiLnojGFgVr0_Th-2x6DhqmHAOhFwQHFzSyDy5RruXY4_FZjJebKHU7bpxfHpXA","name":"ROBERTO ALONSO FERNANDEZ","aadObjectId":"1e0dc7a0-9d5e-488b-bcf2-7e39c84076b8"},"conversation":{"isGroup":true,"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype;messageid=1512376018086","name":null},"recipient":null,"textFormat":"plain","attachmentLayout":null,"membersAdded":[],"membersRemoved":[],"topicName":null,"historyDisclosed":null,"locale":null,"text":"<at>PandoBot</at> fff","speak":null,"inputHint":null,"summary":null,"suggestedActions":null,"attachments":[{"contentType":"text/html","contentUrl":null,"content":"<div><span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">PandoBot</span> fff</div>","name":null,"thumbnailUrl":null}],"entities":[{"type":"clientInfo","locale":"es-ES","country":"ES","platform":"iOS"}],"channelData":{"teamsChannelId":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype","teamsTeamId":"19:1e04f564ce5e4596bf2f266dbcff439e@thread.skype","channel":{"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype"},"team":{"id":"19:1e04f564ce5e4596bf2f266dbcff439e@thread.skype"},"tenant":{"id":"9744600e-3e04-492e-baa1-25ec245c6f10"}},"action":null,"replyToId":null,"value":null,"name":null,"relatesTo":null,"code":null}';

    //generate HMAC hash with diferent $data formats
    $test = [$data, unpak_str($data), base64_encode($data), unpak_str(base64_encode($data))];
    hasher($test, $output);

    //microsoft provided HMAC
    $output.="<HR>EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE=";

    echo $output;
    /*
    Calculates:
    0HsKoHza/QBvdz+nZw9tOti/eSWjyMMt/U77bfDqiE8=
    3jSq3I0HNQkjB9QfnnsxC1c3pF5PjqweHlSVcicrShY=
    bTQcGVTHX8/Gh4xovnN0WiJUiNaOQwvUZnwyFfiCaJE=
    qHBT2Y2ITyoxz2gmBbG8P1CrClvETus6dTffET3bAR8=
    8BcrXEQDDi77qgxCZLYyb/6ez8p9Qg2ZhTyZPWkdn/g=
    +8RSU5SSJKxqRLKkI+NkTE01xwu6PwPkKKMuvyyUvlo=
    PdL5ZpEwcN6Fe5kfX7zeAZLJvt0uLNTzu7lhuoOcr2o=
    s6M5pYruEgWeNMEOFfQRjVKQqtPBVaW3TJb2MzObF2c=
    xOTLhddbAwczQVneuTDQhPzmoIXGQljpf27c+hlhQII=
    aUMm5b2sKfmwGZOglfiu228fWqoLlwjc7z1QRdIbakE=
    5a7bAj9tzqhP9l85OvfVasURW0GSV5rykRutFFPO2fk=
    kwg6P2LoDL9rc3SSwJxQeoYJzZYlh+FHFefe38UokBM=
    eHeAzI7TV6vYDzxTxwyKWxMeVKFiFlIffWRiIMAk6fk=
    ZCyj2UppacQOTXogLPMFLDeMArQg03rhhlIwhynDvng=
    uQYK+7u9fppb62zXqtVYfkNK9wVawB3g+BlTyu4dc74=
    vjOFA3fqpwUx/VO9dQv3XviNhpjTNQsUwaJIwH4JjdY=
    ------------ MS PROVIDED HMAC ---------------
    EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE=
     */
</code>```

I've zero hash matching...

答:
I'm not a PHP expert, and your logic to cover all the cases is a bit convoluted, but I'm pretty sure your problem is that you aren't converting the message ($data) from UTF8 before computing the HMAC.

Here's a simple custom echo bot in Node that shows how to compute and validate the HMAC:

const util = require('util');
const crypto = require('crypto');
const sharedSecret = "+ZaRRMC8+mpnfGaGsBOmkIFt98bttL5YQRq3p2tXgcE=";
const bufSecret = Buffer(sharedSecret, "base64");

var http = require('http');
var PORT = process.env.port || process.env.PORT || 8080;

http.createServer(function(request, response) {
    var payload = '';
    request.on('data', function (data) {
        // console.log("Chunk size: %s bytes", data.length)
        payload += data;
    });

    request.on('end', function() {
        try {
            // Retrieve authorization HMAC information
            var auth = this.headers['authorization'];
            // Calculate HMAC on the message we've received using the shared secret
            var msgBuf = Buffer.from(payload, 'utf8');
            var msgHash = "HMAC " + crypto.createHmac('sha256', bufSecret).update(msgBuf).digest("base64");
            console.log("Computed HMAC: " + msgHash);
            console.log("Received HMAC: " + auth);

            response.writeHead(200);
            if (msgHash === auth) {
                var receivedMsg = JSON.parse(payload);
                var responseMsg = '{ "type": "message", "text": "You typed: ' + receivedMsg.text + '" }';
            } else {
                var responseMsg = '{ "type": "message", "text": "Error: message sender cannot be authenticated." }';
            }
            response.write(responseMsg);
            response.end();
        }
        catch (err) {
            response.writeHead(400);
            return response.end("Error: " + err + "\n" + err.stack);
        }
    });

}).listen(PORT);

console.log('Listening on port %s', PORT);
```

Body:
I am trying to authenticate a Microsoft Teams custom Bot with PHP, following the Microsoft instructions and read de C# example code.

Microsoft Intructions steps:

  1. Generate the hmac from the request body of the message. There are standard libraries on most platforms. Microsoft Teams uses standard
  SHA256 HMAC cryptography. You will need to convert the body to a byte
  array in UTF8.

  2. To compute the hash, provide the byte array of the shared secret.

  3. Convert the hash to a string using UTF8 encoding.

  4. Compare the string value of the generated hash with the value provided in the HTTP request.

I had write a small php script to test this in local:

        <?php
        //Function to generate C# byte[] equivalent
        function unpak_str($val){
            $b = unpack('C*', $val);
            foreach ($b as $key => $value)
                $byte_a .= $value;

           return $byte_a;
          }

        //multi test outputs
        function hasher($values=[], &$output){
            //my secret share
            $secret="ejWiKHgsKY1ZfpJwJ+wIiN4+bgsFad/lkpu9/MWNXgM=";
            //diferent test
            $secret_64=base64_decode($secret);
            $secret_b=unpak_str($secret);
            $secret_b_64=unpak_str(base64_decode($secret));

            foreach($values as $msg){
                $hs = hash_hmac("sha256",$msg,$secret, true);
                $hs_64 = hash_hmac("sha256",$msg,$secret_64, true);
                $hs_b = hash_hmac("sha256",$msg,$secret_b, true);
                $hs_b_64 = hash_hmac("sha256",$msg,$secret_b_64, true);

                $output.=base64_encode($hs)."
";
                $output.=base64_encode($hs_64)."
";
                $output.=base64_encode($hs_b)."
";
                $output.=base64_encode($hs_b_64)."
";
             }
          }

    //Get data
    $data=file_get_contents('php://input');

    //real data request content for test
    $data ='{type":"message","id":"1512376018086","timestamp":"2017-12-04T08:26:58.237Z","localTimestamp":"2017-12-04T09:26:58.237+01:00","serviceUrl":"https://smba.trafficmanager.net/emea-client-ss.msg/","channelId":"msteams","from":{"id":"29:1aq6GCrC6lM9dv3YkAYi1gxTPiLnojGFgVr0_Th-2x6DhqmHAOhFwQHFzSyDy5RruXY4_FZjJebKHU7bpxfHpXA","name":"ROBERTO ALONSO FERNANDEZ","aadObjectId":"1e0dc7a0-9d5e-488b-bcf2-7e39c84076b8"},"conversation":{"isGroup":true,"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype;messageid=1512376018086","name":null},"recipient":null,"textFormat":"plain","attachmentLayout":null,"membersAdded":[],"membersRemoved":[],"topicName":null,"historyDisclosed":null,"locale":null,"text":"<at>PandoBot</at> fff","speak":null,"inputHint":null,"summary":null,"suggestedActions":null,"attachments":[{"contentType":"text/html","contentUrl":null,"content":"
PandoBot fff
","name":null,"thumbnailUrl":null}],"entities":[{"type":"clientInfo","locale":"es-ES","country":"ES","platform":"iOS"}],"channelData":{"teamsChannelId":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype","teamsTeamId":"19:1e04f564ce5e4596bf2f266dbcff439e@thread.skype","channel":{"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype"},"team":{"id":"19:1e04f564ce5e4596bf2f266dbcff439e@thread.skype"},"tenant":{"id":"9744600e-3e04-492e-baa1-25ec245c6f10"}},"action":null,"replyToId":null,"value":null,"name":null,"relatesTo":null,"code":null}';

    //generate HMAC hash with diferent $data formats
    $test = [$data, unpak_str($data), base64_encode($data), unpak_str(base64_encode($data))];
    hasher($test, $output);

    //microsoft provided HMAC
    $output.="
EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE=";

    echo $output;
    /*
    Calculates:
    0HsKoHza/QBvdz+nZw9tOti/eSWjyMMt/U77bfDqiE8=
    3jSq3I0HNQkjB9QfnnsxC1c3pF5PjqweHlSVcicrShY=
    bTQcGVTHX8/Gh4xovnN0WiJUiNaOQwvUZnwyFfiCaJE=
    qHBT2Y2ITyoxz2gmBbG8P1CrClvETus6dTffET3bAR8=
    8BcrXEQDDi77qgxCZLYyb/6ez8p9Qg2ZhTyZPWkdn/g=
    +8RSU5SSJKxqRLKkI+NkTE01xwu6PwPkKKMuvyyUvlo=
    PdL5ZpEwcN6Fe5kfX7zeAZLJvt0uLNTzu7lhuoOcr2o=
    s6M5pYruEgWeNMEOFfQRjVKQqtPBVaW3TJb2MzObF2c=
    xOTLhddbAwczQVneuTDQhPzmoIXGQljpf27c+hlhQII=
    aUMm5b2sKfmwGZOglfiu228fWqoLlwjc7z1QRdIbakE=
    5a7bAj9tzqhP9l85OvfVasURW0GSV5rykRutFFPO2fk=
    kwg6P2LoDL9rc3SSwJxQeoYJzZYlh+FHFefe38UokBM=
    eHeAzI7TV6vYDzxTxwyKWxMeVKFiFlIffWRiIMAk6fk=
    ZCyj2UppacQOTXogLPMFLDeMArQg03rhhlIwhynDvng=
    uQYK+7u9fppb62zXqtVYfkNK9wVawB3g+BlTyu4dc74=
    vjOFA3fqpwUx/VO9dQv3XviNhpjTNQsUwaJIwH4JjdY=
    ------------ MS PROVIDED HMAC ---------------
    EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE=
     */

I've zero hash matching...


问:
ember-cp-validations conditional validator
I'm using ember-cp-validations on models and forms.  I want a validation to be active only when certain conditions are met.  Like, when a route is active or when a component is used in a particular context.

To illustrate, I have a basic email model that has typical validations on the model itself.  When that model is being used in the context of a user account, I want an additional validator to be active (a username-exists validator, used to tell if they are trying to update their email address to one that exists on another account).

My email model:

```<code>import DS from 'ember-data';
import { validator, buildValidations } from 'ember-cp-validations';

const { attr } = DS;

const Validations = buildValidations({
    email: {
        validators: [
            validator('presence', { presence: true, description: 'E-Mail'}),
            validator('format', {
                type: 'email'
            }),
            validator('length', {
                max: 200,
            })
        ]
    },
});

export default DS.Model.extend(Validations, {
    email: attr('string'),
    optin: attr('boolean', { defaultValue: false })
});
</code>```

I already have a username-exists custom validator.  I just can't figure out how to add that validation conditionally.

The simplest solution would be adding the validated with a disabled option that keeps it disabled unless a condition is met.

```<code>validator('username-available', {
    debounce: 300,
    disabled: computed.bool(what is the dependent key??)
})
</code>```

But I have no idea what the dependent key would be.  I don't think the route name is available in the model definition.

Or should I add the conditional validator to the component itself? Is there a way to append a validator to the validators array from the component js?

I think I am probably missing something obvious ;)

答:
It took me a while to dig that up too when I was looking for it. Here's what I have (setup slightly differently, but should get you going):</p>

```<code>  email: {
    disabled: Ember.computed.not('model.attributeInQuestion'),
    validators: [
    ],
  }
</code>```

Body:
I'm using ember-cp-validations on models and forms.  I want a validation to be active only when certain conditions are met.  Like, when a route is active or when a component is used in a particular context.

To illustrate, I have a basic email model that has typical validations on the model itself.  When that model is being used in the context of a user account, I want an additional validator to be active (a username-exists validator, used to tell if they are trying to update their email address to one that exists on another account).

My email model:

import DS from 'ember-data';
import { validator, buildValidations } from 'ember-cp-validations';

const { attr } = DS;

const Validations = buildValidations({
    email: {
        validators: [
            validator('presence', { presence: true, description: 'E-Mail'}),
            validator('format', {
                type: 'email'
            }),
            validator('length', {
                max: 200,
            })
        ]
    },
});

export default DS.Model.extend(Validations, {
    email: attr('string'),
    optin: attr('boolean', { defaultValue: false })
});

I already have a username-exists custom validator.  I just can't figure out how to add that validation conditionally.

The simplest solution would be adding the validated with a disabled option that keeps it disabled unless a condition is met.

validator('username-available', {
    debounce: 300,
    disabled: computed.bool(what is the dependent key??)
})

But I have no idea what the dependent key would be.  I don't think the route name is available in the model definition.

Or should I add the conditional validator to the component itself? Is there a way to append a validator to the validators array from the component js?

I think I am probably missing something obvious ;)

Body:
It took me a while to dig that up too when I was looking for it. Here's what I have (setup slightly differently, but should get you going):

  email: {
    disabled: Ember.computed.not('model.attributeInQuestion'),
    validators: [
    ],
  }


问:
iOS: Programmatically drawing lines in UIView
I am trying to create a UIView as modeled in the picture. Though, I seem to be having some issue with my code. Any idea why?

Solved with the help of comments! Correct code is updated!

UPDATE: I created a custom UIView class
Here is my new code, based off of the comments.

drawLine taken from this: Draw a line with UIBezierPath

答:
Code to achieve the above image:

```<code>//Post this function in your TableViewController
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = HeaderTableView()
    view.title.text = "THIS WEEK"

    return view
}

//Custom UIView Class
class CustomView: UIView {

var shouldSetupConstraints = true
var title: UILabel!
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
    let textStartX = Int((title.frame.minX))
    let textEndX = Int((title.frame.maxX))
    let midY = Int(self.frame.midY)
    self.drawLine(startX: 8, toEndingX: textStartX - 8, startingY: midY, toEndingY: midY, ofColor: UIColor.white, widthOfLine: 1, inView: self)
    self.drawLine(startX: textEndX + 8, toEndingX: Int(self.frame.maxX) - 8, startingY: midY, toEndingY: midY, ofColor: UIColor.white, widthOfLine: 1, inView: self)

}

override init(frame: CGRect) {
    super.init(frame: frame)
    title = UILabel()
    self.addSubview(title)

    title.textAlignment = .center
    title.textColor = UIColor.white
    title.translatesAutoresizingMaskIntoConstraints = false

}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func updateConstraints() {
    if(shouldSetupConstraints) {
        // AutoLayout constraints
        let xConstraint = NSLayoutConstraint(item: title, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)
        let yConstraint = NSLayoutConstraint(item: title, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)
        self.addConstraints([xConstraint, yConstraint])
        shouldSetupConstraints = false
    }
    super.updateConstraints()
}

func drawLine(startX: Int, toEndingX endX: Int, startingY startY: Int, toEndingY endY: Int, ofColor lineColor: UIColor, widthOfLine lineWidth: CGFloat, inView view: UIView) {

    let path = UIBezierPath()
    path.move(to: CGPoint(x: startX, y: startY))
    path.addLine(to: CGPoint(x: endX, y: endY))

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = lineColor.cgColor
    shapeLayer.lineWidth = lineWidth

    view.layer.addSublayer(shapeLayer)

}
}
</code>```

Credits:

Draw a line with UIBezierPath

https://medium.com/written-code/creating-uiviews-programmatically-in-swift-55f5d14502ae

Body:
Code to achieve the above image:

//Post this function in your TableViewController
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = HeaderTableView()
    view.title.text = "THIS WEEK"

    return view
}

//Custom UIView Class
class CustomView: UIView {

var shouldSetupConstraints = true
var title: UILabel!
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
    let textStartX = Int((title.frame.minX))
    let textEndX = Int((title.frame.maxX))
    let midY = Int(self.frame.midY)
    self.drawLine(startX: 8, toEndingX: textStartX - 8, startingY: midY, toEndingY: midY, ofColor: UIColor.white, widthOfLine: 1, inView: self)
    self.drawLine(startX: textEndX + 8, toEndingX: Int(self.frame.maxX) - 8, startingY: midY, toEndingY: midY, ofColor: UIColor.white, widthOfLine: 1, inView: self)

}

override init(frame: CGRect) {
    super.init(frame: frame)
    title = UILabel()
    self.addSubview(title)

    title.textAlignment = .center
    title.textColor = UIColor.white
    title.translatesAutoresizingMaskIntoConstraints = false

}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func updateConstraints() {
    if(shouldSetupConstraints) {
        // AutoLayout constraints
        let xConstraint = NSLayoutConstraint(item: title, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)
        let yConstraint = NSLayoutConstraint(item: title, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)
        self.addConstraints([xConstraint, yConstraint])
        shouldSetupConstraints = false
    }
    super.updateConstraints()
}

func drawLine(startX: Int, toEndingX endX: Int, startingY startY: Int, toEndingY endY: Int, ofColor lineColor: UIColor, widthOfLine lineWidth: CGFloat, inView view: UIView) {

    let path = UIBezierPath()
    path.move(to: CGPoint(x: startX, y: startY))
    path.addLine(to: CGPoint(x: endX, y: endY))

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = lineColor.cgColor
    shapeLayer.lineWidth = lineWidth

    view.layer.addSublayer(shapeLayer)

}
}

Credits:

Draw a line with UIBezierPath

https://medium.com/written-code/creating-uiviews-programmatically-in-swift-55f5d14502ae


问:
Inner Join in laravel missing P
I needed to combine the two table product_price and trade_channels, when I use inner join,

the ID of product_price is remove.

Here is my code

```<code>DB::table('product_price')->where('product_id',$id)->where('action','customer_price')
         ->join('customers','product_price.action_id','=','customers.id')
         ->get();
</code>```

答:
try

```<code>DB::table('product_price')
->select('*','product_price.id AS product_price_id')
->where('product_id',$id)
->where('action','customer_price')
->join('customers','product_price.action_id','=','customers.id')
->get();
</code>```

the product_price id would be replace with customers id, so just print out the product_price id with other name.
hope it is help

Title: Inner Join in laravel missing P

Body:
I needed to combine the two table product_price and trade_channels, when I use inner join,

the ID of product_price is remove.

Here is my code

DB::table('product_price')->where('product_id',$id)->where('action','customer_price')
         ->join('customers','product_price.action_id','=','customers.id')
         ->get();

Body:
try

DB::table('product_price')
->select('*','product_price.id AS product_price_id')
->where('product_id',$id)
->where('action','customer_price')
->join('customers','product_price.action_id','=','customers.id')
->get();

the product_price id would be replace with customers id, so just print out the product_price id with other name.
hope it is help


问:
Breaking a promise chain (with multiple happy flows and single chain)
This question has been asked before but I wasn't satisfied with solutions like rejecting and handling in catch for breaking for a happy flow. I want to know if we can end up with multiple happy flows in a linear promise chain without rejecting (except in case of errors).

Here's my code sample:

```<code>const goStraight = (steps) => {
  return new Promise ((resolve, reject) => {
    resolve(steps+2);
  });
};

const turnLeft = (steps) => {
  return new Promise ((resolve, reject) => {
    resolve(++steps);
  });
};

const turnRight = (steps) => {
  return new Promise ((resolve, reject) => {
    resolve(++steps);
  });
};

goStraight(0)
.then((total_steps_taken) => {
  if (total_steps_taken % 2 === 0)
    return turnLeft(total_steps_taken);
  else
    return null; // This is where I want to break the chain
})
.then((total_steps_taken) => {
  return turnRight(total_steps_taken);
}).then((total_steps_taken) => {
  console.log("Finished with Total Steps : "+total_steps_taken);
})
</code>```

In the case that I start with goStraight(1) the code would flow in the else condition and this is when I want to break the chain.

Just want to know if it can be done without creating branches or using promise rejection.

答:
Other than using promise rejection, a possible approach to clean the code up could be to organize the happy paths into their own chains which get combined into a single chain.

In other words, every sequence of steps that should happen, well, sequentially, should be organized together.

In the particular snippet you provided, you always go right after you went left, so just make that an explicit chain that happens if the number of steps taken is even:

```<code>const happyPath = total_steps_taken => turnLeft(total_steps_taken)
  .then(turnRight)
  .then(logSteps);

goStraight(0).then(total_steps_taken => {
  if (total_steps_taken % 2 === 0) {
    return happyPath(total_steps_taken);
  }
});
</code>```

Full example:

const stepPromise = direction => x => {
  console.log(`going ${x} steps ${direction}`);
  return new Promise(resolve => {
    setTimeout(() => resolve(x), 500);
  });
}

const turnLeft = stepPromise('left')
const turnRight = stepPromise('right');
const goStraight = stepPromise('straight');
const logSteps = steps => console.log(`steps taken: ${steps}`);

const happyPath = steps => turnLeft(steps)
  .then(turnRight)
  .then(steps => console.log(`Took ${steps} steps`));

const branchOrQuit = steps => {
  if (steps % 2 === 0) {
    console.log('going down the happy path');
    return happyPath(steps);
  }
  console.log('quitting');
}

const happyExample = () => {
  console.log('\n --- EVEN ---');
  return goStraight(2).then(branchOrQuit);
}

const sadExample = () => {
  console.log('\n --- ODD ---');
  return goStraight(1).then(branchOrQuit);
}

happyExample().then(sadExample);```

Body:
This question has been asked before but I wasn't satisfied with solutions like rejecting and handling in catch for breaking for a happy flow. I want to know if we can end up with multiple happy flows in a linear promise chain without rejecting (except in case of errors).

Here's my code sample:

const goStraight = (steps) => {
  return new Promise ((resolve, reject) => {
    resolve(steps+2);
  });
};

const turnLeft = (steps) => {
  return new Promise ((resolve, reject) => {
    resolve(++steps);
  });
};

const turnRight = (steps) => {
  return new Promise ((resolve, reject) => {
    resolve(++steps);
  });
};

goStraight(0)
.then((total_steps_taken) => {
  if (total_steps_taken % 2 === 0)
    return turnLeft(total_steps_taken);
  else
    return null; // This is where I want to break the chain
})
.then((total_steps_taken) => {
  return turnRight(total_steps_taken);
}).then((total_steps_taken) => {
  console.log("Finished with Total Steps : "+total_steps_taken);
})

In the case that I start with goStraight(1) the code would flow in the else condition and this is when I want to break the chain.

Just want to know if it can be done without creating branches or using promise rejection.

Body:
Other than using promise rejection, a possible approach to clean the code up could be to organize the happy paths into their own chains which get combined into a single chain.

In other words, every sequence of steps that should happen, well, sequentially, should be organized together.

In the particular snippet you provided, you always go right after you went left, so just make that an explicit chain that happens if the number of steps taken is even:

const happyPath = total_steps_taken => turnLeft(total_steps_taken)
  .then(turnRight)
  .then(logSteps);

goStraight(0).then(total_steps_taken => {
  if (total_steps_taken % 2 === 0) {
    return happyPath(total_steps_taken);
  }
});

Full example:

const stepPromise = direction => x => {
  console.log(`going ${x} steps ${direction}`);
  return new Promise(resolve => {
    setTimeout(() => resolve(x), 500);
  });
}

const turnLeft = stepPromise('left')
const turnRight = stepPromise('right');
const goStraight = stepPromise('straight');
const logSteps = steps => console.log(`steps taken: ${steps}`);

const happyPath = steps => turnLeft(steps)
  .then(turnRight)
  .then(steps => console.log(`Took ${steps} steps`));

const branchOrQuit = steps => {
  if (steps % 2 === 0) {
    console.log('going down the happy path');
    return happyPath(steps);
  }
  console.log('quitting');
}

const happyExample = () => {
  console.log('\n --- EVEN ---');
  return goStraight(2).then(branchOrQuit);
}

const sadExample = () => {
  console.log('\n --- ODD ---');
  return goStraight(1).then(branchOrQuit);
}

happyExample().then(sadExample);


问:
How to find part of a string in a python array
I have an array with a column of numbers and a column of strings. I need to find the indices that contain a certain part of the string. Example:

```<code>array([['4', 'red crayon'],
       ['2', 'purple people eater'],
       ['6', 'red hammer'],
       ['12', 'green screwdriver']])
</code>```

I am in Intro Programming so my instructors told me to use if 'stringpart' in array[index] to get a boolean array to use in our problem solving. What I think should happen:

```<code>input:
'red' in array[:,1]
output:
(true,false,true,false)
</code>```

What actually happens is I get all false. I tested the code outside of functions, and applied it to an array with only the strings and it still gives me false. But I tried it with an one of the full strings 'red crayon' and it said true. This partial string code works for the instructors and other students. Why isn't it working for me?

答:
You can do without for loop:

```<code>import numpy as np
wow=np.array([['4', 'red crayon'],
       ['2', 'purple people eater'],
       ['6', 'red hammer'],
       ['12', 'green screwdriver']])

your_word='red'
print(list(map(lambda x:True if your_word in x[1].split() else False ,wow)))
</code>```

output:

```<code>[True, False, True, False]
</code>```

Body:
I have an array with a column of numbers and a column of strings. I need to find the indices that contain a certain part of the string. Example:

array([['4', 'red crayon'],
       ['2', 'purple people eater'],
       ['6', 'red hammer'],
       ['12', 'green screwdriver']])

I am in Intro Programming so my instructors told me to use if 'stringpart' in array[index] to get a boolean array to use in our problem solving. What I think should happen:

input:
'red' in array[:,1]
output:
(true,false,true,false)

What actually happens is I get all false. I tested the code outside of functions, and applied it to an array with only the strings and it still gives me false. But I tried it with an one of the full strings 'red crayon' and it said true. This partial string code works for the instructors and other students. Why isn't it working for me?

Body:
You can do without for loop:

import numpy as np
wow=np.array([['4', 'red crayon'],
       ['2', 'purple people eater'],
       ['6', 'red hammer'],
       ['12', 'green screwdriver']])

your_word='red'
print(list(map(lambda x:True if your_word in x[1].split() else False ,wow)))

output:

[True, False, True, False]


问:
How to fix the mistake in my collage with python3?
I want to create a collage of 3 x 3 pictures. I want to reuse the code with which I did a 2 x 2 collage, but it's not working. Primarily I want to understand my mistake, not get running code (I am aware that there is a solution online here but with a different approach).

Help would be much appreciated, as I am totally new to coding.

```<code>from PIL import Image
new_im = Image.new('RGB', (640,480))

width = 213
height = 160

x = 0
y = 0

for im in image_list:
    if (x == 640):
        y = y + height
        x = 0
    im.thumbnail((width, height))
    new_im.paste(im, (x,y))
    x = x + width

new_im.save('collage.png')
</code>```

答:
Always be sure to print your values as a first step for debugging. A simple

```<code>print(x, y)
</code>```

at the bottom of your loop would have saved you the trouble. The variable x only gets updated by 213 each time in this case, which isn't a multiple of 640.

If you want your collage to be NxM in general then simply take the width and height to be width/N and height/M and round to integers. Then check whenever x >= width*N to advance y.

Body:
I want to create a collage of 3 x 3 pictures. I want to reuse the code with which I did a 2 x 2 collage, but it's not working. Primarily I want to understand my mistake, not get running code (I am aware that there is a solution online here but with a different approach).

Help would be much appreciated, as I am totally new to coding.

from PIL import Image
new_im = Image.new('RGB', (640,480))

width = 213
height = 160

x = 0
y = 0

for im in image_list:
    if (x == 640):
        y = y + height
        x = 0
    im.thumbnail((width, height))
    new_im.paste(im, (x,y))
    x = x + width

new_im.save('collage.png')

Body:
Always be sure to print your values as a first step for debugging. A simple

print(x, y)

at the bottom of your loop would have saved you the trouble. The variable x only gets updated by 213 each time in this case, which isn't a multiple of 640.

If you want your collage to be NxM in general then simply take the width and height to be width/N and height/M and round to integers. Then check whenever x >= width*N to advance y.


问:
matplotlib.basemap - Earth Science - ValueError: operands could not be broadcast together with shapes (12529,15661) (12529,15662)
Can't seem to figure out why my graph will not come out correctly. I am attempting to plot depth on a map projection using netCDF4, and mpl_toolkits.Basemap. I have attempted several projections yet none have worked. Below is the code I am using:

```<code>from netCDF4 import Dataset
from mpl_toolkits.basemap import Basemap
import mpl_toolkits as mplt
import matplotlib.pyplot as plt
import numpy as np

f = Dataset("/geosci/path2data/depth_data.nc")

# extract and label column
lats = f.variables['lat'][:]  # extract/copy the latitude data
lons = f.variables['lon'][:]  # extract/copy the longitude data
depth = f.variables['Band1'][:]
lon_0 = lons.mean()
lat_0 = lats.mean()

#create map projection
m = Basemap(projection = 'stere', width = 5*10**6, height = 35*10**5, resolution = 'l', lat_ts = 40, lat_0 = lat_0, lon_0 = lon_0)

# Plot of global temperature on our random day
fig = plt.figure()
fig.subplots_adjust(left=0., right=1., bottom=0., top=0.9)

# Make the plot continuous
depth_cyclic, lons_cyclic = mplt.basemap.addcyclic(depth, lons)

# compute map projection coordinates for lat/lon grid
# Create 2D lat/lon arrays for Basemap
lon2d, lat2d = np.meshgrid(lons_cyclic, lats)
# Transforms lat/lon into plotting coordinates for projection
x, y = m(lon2d, lat2d)

# Plot of air temperature with 11 contour intervals
cs = m.contourf(lon2d, lat2d, depth, 11, cmap=plt.cm.Spectral_r)
cbar = plt.colorbar(cs, orientation='horizontal', shrink=0.5)
m.plot(x,y)
plt.show()
</code>```

This is the error I get in return. Still teaching myself to code and need a little bit of help on this one.

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-7-7b81b2da3866> in <module>()
     18
     19 # Plot of air temperature with 11 contour intervals
---> 20 cs = m.contourf(lon2d, lat2d, depth, 11, cmap=plt.cm.Spectral_r)
     21 cbar = plt.colorbar(cs, orientation='horizontal', shrink=0.5)
     22 m.plot(x,y)

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mpl_toolkits/basemap/__init__.pyc
in with_transform(self, x, y, data, *args, **kwargs)
    519             # convert lat/lon coords to map projection coords.
    520             x, y = self(x,y)
--> 521         return plotfunc(self,x,y,data,*args,**kwargs)
    522     return with_transform
    523

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mpl_toolkits/basemap/__init__.pyc
in contourf(self, x, y, data, *args, **kwargs)
   3669                 data = ma.asarray(data)
   3670                 # combine with data mask.
-> 3671                 mask = np.logical_or(ma.getmaskarray(data),xymask)
   3672                 data = ma.masked_array(data,mask=mask)
   3673                 CS = ax.contourf(x,y,data,*args,**kwargs)

ValueError: operands could not be broadcast together with shapes (12529,15661) (12529,15662)
</code>```

答:
I forgot to the continuous depth which was assigned to the other information.

cs = m.contourf(x, y, depth_cyclic, 11, cmap=plt.cm.Spectral_r)

Body:
Can't seem to figure out why my graph will not come out correctly. I am attempting to plot depth on a map projection using netCDF4, and mpl_toolkits.Basemap. I have attempted several projections yet none have worked. Below is the code I am using:

from netCDF4 import Dataset
from mpl_toolkits.basemap import Basemap
import mpl_toolkits as mplt
import matplotlib.pyplot as plt
import numpy as np

f = Dataset("/geosci/path2data/depth_data.nc")

# extract and label column
lats = f.variables['lat'][:]  # extract/copy the latitude data
lons = f.variables['lon'][:]  # extract/copy the longitude data
depth = f.variables['Band1'][:]
lon_0 = lons.mean()
lat_0 = lats.mean()

#create map projection
m = Basemap(projection = 'stere', width = 5*10**6, height = 35*10**5, resolution = 'l', lat_ts = 40, lat_0 = lat_0, lon_0 = lon_0)

# Plot of global temperature on our random day
fig = plt.figure()
fig.subplots_adjust(left=0., right=1., bottom=0., top=0.9)

# Make the plot continuous
depth_cyclic, lons_cyclic = mplt.basemap.addcyclic(depth, lons)

# compute map projection coordinates for lat/lon grid
# Create 2D lat/lon arrays for Basemap
lon2d, lat2d = np.meshgrid(lons_cyclic, lats)
# Transforms lat/lon into plotting coordinates for projection
x, y = m(lon2d, lat2d)

# Plot of air temperature with 11 contour intervals
cs = m.contourf(lon2d, lat2d, depth, 11, cmap=plt.cm.Spectral_r)
cbar = plt.colorbar(cs, orientation='horizontal', shrink=0.5)
m.plot(x,y)
plt.show()

This is the error I get in return. Still teaching myself to code and need a little bit of help on this one.

ValueError                                Traceback (most recent call last)
<ipython-input-7-7b81b2da3866> in <module>()
     18
     19 # Plot of air temperature with 11 contour intervals
---> 20 cs = m.contourf(lon2d, lat2d, depth, 11, cmap=plt.cm.Spectral_r)
     21 cbar = plt.colorbar(cs, orientation='horizontal', shrink=0.5)
     22 m.plot(x,y)

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mpl_toolkits/basemap/__init__.pyc
in with_transform(self, x, y, data, *args, **kwargs)
    519             # convert lat/lon coords to map projection coords.
    520             x, y = self(x,y)
--> 521         return plotfunc(self,x,y,data,*args,**kwargs)
    522     return with_transform
    523

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mpl_toolkits/basemap/__init__.pyc
in contourf(self, x, y, data, *args, **kwargs)
   3669                 data = ma.asarray(data)
   3670                 # combine with data mask.
-> 3671                 mask = np.logical_or(ma.getmaskarray(data),xymask)
   3672                 data = ma.masked_array(data,mask=mask)
   3673                 CS = ax.contourf(x,y,data,*args,**kwargs)

ValueError: operands could not be broadcast together with shapes (12529,15661) (12529,15662)


问:
Set max-execution-time on a function
I am generating PDF files using pdfmake on client side (a cordova app).

The more complex the document definition is the longer pdfmake takes to produce the document.

Thus, my intention is to put a hard limit on how long it takes for pdfmake to produce the document, something like what timeout command do in bash, and indicate to user if it failed to complete.

Here's a snippet of what I'm trying to do:

```<code>runFor(10, function(){  // run this function for a maximum of 10s
  pdfMake.createPdf(documentDefinition).getBase64(function(b64buff){
     //do something with the result
  });
}, ontimeout);
</code>```

答:
Ideally you need to change the function. Maybe it could take a condition as a parameter.

Depending on what it was doing that takes 'forever' you could spawn a child process that runs the function then kill the process after a certain time.

Title: Set max-execution-time on a function

Body:
I am generating PDF files using pdfmake on client side (a cordova app).

The more complex the document definition is the longer pdfmake takes to produce the document.

Thus, my intention is to put a hard limit on how long it takes for pdfmake to produce the document, something like what timeout command do in bash, and indicate to user if it failed to complete.

Here's a snippet of what I'm trying to do:

runFor(10, function(){  // run this function for a maximum of 10s
  pdfMake.createPdf(documentDefinition).getBase64(function(b64buff){
     //do something with the result
  });
}, ontimeout);


问:
Adding support:preference-v7 or -v14 library causes Gradle build to fail
My project builds fine, until I attempt to include the Support Preference library.

When I do, build fails with this error:

```<code>C:\Users\user\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.0.0.aar\e8afe3ff4b4dc10495266439a3695e57\res\values\values.xml:252:5-69: AAPT: error: duplicate value for resource 'attr/min' with config ''.

C:\Users\user\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.0.0.aar\e8afe3ff4b4dc10495266439a3695e57\res\values\values.xml:252:5-69: AAPT: error: resource previously defined here.

C:\Users\user\StudioProjects\project\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:627: error: duplicate value for resource 'attr/min' with config ''.

C:\Users\user\StudioProjects\project\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:483: error: resource previously defined here.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
</code>```

I really don't know why this error is occuring...

EDIT: Full build.gradle:

```<code>apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 27

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.myapp"
        minSdkVersion 16
        targetSdkVersion 27
        multiDexEnabled true
        versionCode 1
        versionName "myVersion"
        resConfigs "en"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            ext.enableCrashlytics = false
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')

    def firebaseVersion = '11.4.2'
    def supportVersion = '27.0.0'

    //Firebase Crashlytics
    compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
        transitive = true
    }

    //Firebase
    implementation 'com.google.firebase:firebase-auth:' + firebaseVersion
    implementation 'com.google.firebase:firebase-core:' + firebaseVersion
    implementation 'com.google.firebase:firebase-firestore:' + firebaseVersion

    //FirebaseUI
    implementation 'com.firebaseui:firebase-ui-auth:3.1.0'

    //Android Support
    implementation 'com.android.support:support-v4:' + supportVersion

    implementation 'com.android.support:appcompat-v7:' + supportVersion
    implementation 'com.android.support:cardview-v7:' + supportVersion
    implementation 'com.android.support:gridlayout-v7:' + supportVersion
    implementation 'com.android.support:recyclerview-v7:' + supportVersion
    implementation 'com.android.support:preference-v7:' + supportVersion

    implementation 'com.android.support:preference-v14:' + supportVersion

    implementation 'com.android.support:support-vector-drawable:' + supportVersion

    implementation 'com.android.support:design:' + supportVersion

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    implementation 'com.android.support:multidex:1.0.2'

    //Material About
    implementation 'com.github.daniel-stoneuk:material-about-library:2.2.3-support26.1.0' //Weird version system

    //OpenCSV
    implementation('com.opencsv:opencsv:4.0') {
        //Transitively requires Apache Commons, which necessitates multidex...
        exclude group: 'commons-beanutils'
    }

    //Gson
    implementation 'com.google.code.gson:gson:2.8.2'
}

apply plugin: 'com.google.gms.google-services'
</code>```

It wants some more details, so I'll elaborate on the problem.
I want to use the AppCompat Preference library, but the error at the beginning pops up whenever I try to add it to my build.gradle.

答:
You can try to excluding support library from Material About library with this:

```<code>  implementation ('com.github.daniel-stoneuk:material-about-library:2.2.3-support26.1.0') {
    exclude group: 'com.android.support'
    exclude module: 'appcompat-v7'
    exclude module: 'cardview-v7'
    exclude module: 'design'
  }
</code>```

Please look at its build.gradle: https://github.com/daniel-stoneuk/material-about-library/blob/master/build.gradle

Body:
My project builds fine, until I attempt to include the Support Preference library.

When I do, build fails with this error:

C:\Users\user\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.0.0.aar\e8afe3ff4b4dc10495266439a3695e57\res\values\values.xml:252:5-69: AAPT: error: duplicate value for resource 'attr/min' with config ''.

C:\Users\user\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.0.0.aar\e8afe3ff4b4dc10495266439a3695e57\res\values\values.xml:252:5-69: AAPT: error: resource previously defined here.

C:\Users\user\StudioProjects\project\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:627: error: duplicate value for resource 'attr/min' with config ''.

C:\Users\user\StudioProjects\project\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:483: error: resource previously defined here.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

I really don't know why this error is occuring...

EDIT: Full build.gradle:

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 27

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.myapp"
        minSdkVersion 16
        targetSdkVersion 27
        multiDexEnabled true
        versionCode 1
        versionName "myVersion"
        resConfigs "en"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            ext.enableCrashlytics = false
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')

    def firebaseVersion = '11.4.2'
    def supportVersion = '27.0.0'

    //Firebase Crashlytics
    compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
        transitive = true
    }

    //Firebase
    implementation 'com.google.firebase:firebase-auth:' + firebaseVersion
    implementation 'com.google.firebase:firebase-core:' + firebaseVersion
    implementation 'com.google.firebase:firebase-firestore:' + firebaseVersion

    //FirebaseUI
    implementation 'com.firebaseui:firebase-ui-auth:3.1.0'

    //Android Support
    implementation 'com.android.support:support-v4:' + supportVersion

    implementation 'com.android.support:appcompat-v7:' + supportVersion
    implementation 'com.android.support:cardview-v7:' + supportVersion
    implementation 'com.android.support:gridlayout-v7:' + supportVersion
    implementation 'com.android.support:recyclerview-v7:' + supportVersion
    implementation 'com.android.support:preference-v7:' + supportVersion

    implementation 'com.android.support:preference-v14:' + supportVersion

    implementation 'com.android.support:support-vector-drawable:' + supportVersion

    implementation 'com.android.support:design:' + supportVersion

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    implementation 'com.android.support:multidex:1.0.2'

    //Material About
    implementation 'com.github.daniel-stoneuk:material-about-library:2.2.3-support26.1.0' //Weird version system

    //OpenCSV
    implementation('com.opencsv:opencsv:4.0') {
        //Transitively requires Apache Commons, which necessitates multidex...
        exclude group: 'commons-beanutils'
    }

    //Gson
    implementation 'com.google.code.gson:gson:2.8.2'
}

apply plugin: 'com.google.gms.google-services'

It wants some more details, so I'll elaborate on the problem.
I want to use the AppCompat Preference library, but the error at the beginning pops up whenever I try to add it to my build.gradle.

Body:
You can try to excluding support library from Material About library with this:

  implementation ('com.github.daniel-stoneuk:material-about-library:2.2.3-support26.1.0') {
    exclude group: 'com.android.support'
    exclude module: 'appcompat-v7'
    exclude module: 'cardview-v7'
    exclude module: 'design'
  }

Please look at its build.gradle: https://github.com/daniel-stoneuk/material-about-library/blob/master/build.gradle


问:
OpenCV: memory leak with Python interface but not in the C version
I am asking here because I haven't gotten any help from the OpenCV developers so far. I reduced the problem to a very simple test case so probably anyone with some background with CPython could help here.

This C code does not leak:

```<code>int main() {
    while(true) {
        int hist_size[] = {40};
        float range[] = {0.0f,255.0f};
        float* ranges[] = {range};
        CvHistogram* hist = cvCreateHist(1, hist_size, CV_HIST_ARRAY, ranges, 1);
        cvReleaseHist(&hist);
    }
}
</code>```

This Python code does leak:

```<code>while True: cv.CreateHist([40], cv.CV_HIST_ARRAY, [[0,255]], 1)
</code>```

I searched through the CPython code (of OpenCVs current SVN trunk code) and found this:

```<code>struct cvhistogram_t {
  PyObject_HEAD
  CvHistogram h;
  PyObject *bins;
};
</code>```

...

```<code>/* cvhistogram */

static void cvhistogram_dealloc(PyObject *self)
{
  cvhistogram_t *cvh = (cvhistogram_t*)self;
  Py_DECREF(cvh->bins);
  PyObject_Del(self);
}

static PyTypeObject cvhistogram_Type = {
  PyObject_HEAD_INIT(&PyType_Type)
  0,                                      /*size*/
  MODULESTR".cvhistogram",                /*name*/
  sizeof(cvhistogram_t),                  /*basicsize*/
};

static PyObject *cvhistogram_getbins(cvhistogram_t *cvh)
{
  Py_INCREF(cvh->bins);
  return cvh->bins;
}

static PyGetSetDef cvhistogram_getseters[] = {
  {(char*)"bins", (getter)cvhistogram_getbins, (setter)NULL, (char*)"bins", NULL},
  {NULL}  /* Sentinel */
};

static void cvhistogram_specials(void)
{
  cvhistogram_Type.tp_dealloc = cvhistogram_dealloc;
  cvhistogram_Type.tp_getset = cvhistogram_getseters;
}
</code>```

...

```<code>static PyObject *pycvCreateHist(PyObject *self, PyObject *args, PyObject *kw)
{
  const char *keywords[] = { "dims", "type", "ranges", "uniform", NULL };
  PyObject *dims;
  int type;
  float **ranges = NULL;
  int uniform = 1;

  if (!PyArg_ParseTupleAndKeywords(args, kw, "Oi|O&i", (char**)keywords, &dims, &type, convert_to_floatPTRPTR, (void*)&ranges, &uniform)) {
    return NULL;
  }
  cvhistogram_t *h = PyObject_NEW(cvhistogram_t, &cvhistogram_Type);
  args = Py_BuildValue("Oi", dims, CV_32FC1);
  h->bins = pycvCreateMatND(self, args);
  Py_DECREF(args);
  if (h->bins == NULL) {
    return NULL;
  }
  h->h.type = CV_HIST_MAGIC_VAL;
  if (!convert_to_CvArr(h->bins, &(h->h.bins), "bins"))
    return NULL;

  ERRWRAP(cvSetHistBinRanges(&(h->h), ranges, uniform));

  return (PyObject*)h;
}
</code>```

And from the OpenCV C headers:

```<code>typedef struct CvHistogram
{
    int     type;
    CvArr*  bins;
    float   thresh[CV_MAX_DIM][2];  /* For uniform histograms.                      */
    float** thresh2;                /* For non-uniform histograms.                  */
    CvMatND mat;                    /* Embedded matrix header for array histograms. */
}
CvHistogram;
</code>```

I don't exactly understand everything because I never worked with the C-interface to Python before. But probably the bug I am searching for is somewhere in this code.

Am I right? Or where should I search for the bug? How would I fix it?

(Note for people who have seen an earlier version of this question: I looked at the wrong code. Their SWIG interface was deprecated and not used anymore (but the code was still there in SVN, this is why I confused it. So don't look into interfaces/swig, this code is old and not used. The current code lives in modules/python.)

Upstream bug report: memleak in OpenCV Python CreateHist

答:
I think you have  garbage collection issue, in that you never leave the loop.

Does this work more as expected?

```<code>while True:
    cv.CreateHist([40], cv.CV_HIST_ARRAY, [[0,255]], 1)
    cv = None
</code>```

Body:
I am asking here because I haven't gotten any help from the OpenCV developers so far. I reduced the problem to a very simple test case so probably anyone with some background with CPython could help here.

This C code does not leak:

int main() {
    while(true) {
        int hist_size[] = {40};
        float range[] = {0.0f,255.0f};
        float* ranges[] = {range};
        CvHistogram* hist = cvCreateHist(1, hist_size, CV_HIST_ARRAY, ranges, 1);
        cvReleaseHist(&hist);
    }
}

This Python code does leak:

while True: cv.CreateHist([40], cv.CV_HIST_ARRAY, [[0,255]], 1)

I searched through the CPython code (of OpenCVs current SVN trunk code) and found this:

struct cvhistogram_t {
  PyObject_HEAD
  CvHistogram h;
  PyObject *bins;
};

...

/* cvhistogram */

static void cvhistogram_dealloc(PyObject *self)
{
  cvhistogram_t *cvh = (cvhistogram_t*)self;
  Py_DECREF(cvh->bins);
  PyObject_Del(self);
}

static PyTypeObject cvhistogram_Type = {
  PyObject_HEAD_INIT(&PyType_Type)
  0,                                      /*size*/
  MODULESTR".cvhistogram",                /*name*/
  sizeof(cvhistogram_t),                  /*basicsize*/
};

static PyObject *cvhistogram_getbins(cvhistogram_t *cvh)
{
  Py_INCREF(cvh->bins);
  return cvh->bins;
}

static PyGetSetDef cvhistogram_getseters[] = {
  {(char*)"bins", (getter)cvhistogram_getbins, (setter)NULL, (char*)"bins", NULL},
  {NULL}  /* Sentinel */
};

static void cvhistogram_specials(void)
{
  cvhistogram_Type.tp_dealloc = cvhistogram_dealloc;
  cvhistogram_Type.tp_getset = cvhistogram_getseters;
}

...

static PyObject *pycvCreateHist(PyObject *self, PyObject *args, PyObject *kw)
{
  const char *keywords[] = { "dims", "type", "ranges", "uniform", NULL };
  PyObject *dims;
  int type;
  float **ranges = NULL;
  int uniform = 1;

  if (!PyArg_ParseTupleAndKeywords(args, kw, "Oi|O&i", (char**)keywords, &dims, &type, convert_to_floatPTRPTR, (void*)&ranges, &uniform)) {
    return NULL;
  }
  cvhistogram_t *h = PyObject_NEW(cvhistogram_t, &cvhistogram_Type);
  args = Py_BuildValue("Oi", dims, CV_32FC1);
  h->bins = pycvCreateMatND(self, args);
  Py_DECREF(args);
  if (h->bins == NULL) {
    return NULL;
  }
  h->h.type = CV_HIST_MAGIC_VAL;
  if (!convert_to_CvArr(h->bins, &(h->h.bins), "bins"))
    return NULL;

  ERRWRAP(cvSetHistBinRanges(&(h->h), ranges, uniform));

  return (PyObject*)h;
}

And from the OpenCV C headers:

typedef struct CvHistogram
{
    int     type;
    CvArr*  bins;
    float   thresh[CV_MAX_DIM][2];  /* For uniform histograms.                      */
    float** thresh2;                /* For non-uniform histograms.                  */
    CvMatND mat;                    /* Embedded matrix header for array histograms. */
}
CvHistogram;

I don't exactly understand everything because I never worked with the C-interface to Python before. But probably the bug I am searching for is somewhere in this code.

Am I right? Or where should I search for the bug? How would I fix it?

(Note for people who have seen an earlier version of this question: I looked at the wrong code. Their SWIG interface was deprecated and not used anymore (but the code was still there in SVN, this is why I confused it. So don't look into interfaces/swig, this code is old and not used. The current code lives in modules/python.)

Upstream bug report: memleak in OpenCV Python CreateHist

Body:
I think you have  garbage collection issue, in that you never leave the loop.

Does this work more as expected?

while True:
    cv.CreateHist([40], cv.CV_HIST_ARRAY, [[0,255]], 1)
    cv = None


问:
Is it possible to customise column width of bar chart created using AmChart
I am having issue with the AmChart column width that column names is overlapping to each other. See below image.

Please advise if possible to change column width or to bring extra content in next line

答:
You can change the columns width in your graph, but that doesn't define the space available for your labels.

Ideally you would be changing the labelRotation in your CategoryAxis:

```<code>"categoryAxis": {
    "labelRotation": 45
}
</code>```

Please check the example here: https://codepen.io/team/amcharts/pen/574ba080c90e5030bae9352a31465086

Body:
You can change the columns width in your graph, but that doesn't define the space available for your labels.

Ideally you would be changing the labelRotation in your CategoryAxis:

"categoryAxis": {
    "labelRotation": 45
}

Please check the example here: https://codepen.io/team/amcharts/pen/574ba080c90e5030bae9352a31465086


问:
Tab key navigation in JavaFX TextArea
How do I make hitting the Tab Key in TextArea navigates to the next control ?

I could add a listener to cath de key pressed event, but how do I make te TextArea control to lose it focus (without knowing the next field in the chain to be focused) ?

```<code>@FXML protected void handleTabKeyTextArea(KeyEvent event) {
    if (event.getCode() == KeyCode.TAB) {
        ...
    }
}
</code>```

答:
As of Java 9 (2017), most answers in this page don't work, since you can't do skin.getBehavior() anymore.

This works:

```<code>@Override
public void handle(KeyEvent event) {
    KeyCode code = event.getCode();

    if (code == KeyCode.TAB && !event.isShiftDown() && !event.isControlDown()) {
        event.consume();
        Node node = (Node) event.getSource();
        try {
            Robot robot = new Robot();
            robot.keyPress(KeyCode.CONTROL.getCode());
            robot.keyPress(KeyCode.TAB.getCode());
            robot.delay(10);
            robot.keyRelease(KeyCode.TAB.getCode());
            robot.keyRelease(KeyCode.CONTROL.getCode());
            }
        catch (AWTException e) { }
        }
    }
</code>```

This also works:

```<code>@Override
public void handle(KeyEvent event) {
    KeyCode code = event.getCode();

    if (code == KeyCode.TAB && !event.isShiftDown() && !event.isControlDown()) {
        event.consume();
        Node node = (Node) event.getSource();
        KeyEvent newEvent
          = new KeyEvent(event.getSource(),
                     event.getTarget(), event.getEventType(),
                     event.getCharacter(), event.getText(),
                     event.getCode(), event.isShiftDown(),
                     true, event.isAltDown(),
                     event.isMetaDown());

        node.fireEvent(newEvent);
        }
    }
</code>```

Both simulate pressing CTRL+TAB when the user presses TAB. The default behaviour of the TextArea for CTRL+TAB is moving the focus to the next control. Please note the second code is based on Johan De Schutter's answer.

Title: Tab key navigation in JavaFX TextArea

Body:
How do I make hitting the Tab Key in TextArea navigates to the next control ?

I could add a listener to cath de key pressed event, but how do I make te TextArea control to lose it focus (without knowing the next field in the chain to be focused) ?

@FXML protected void handleTabKeyTextArea(KeyEvent event) {
    if (event.getCode() == KeyCode.TAB) {
        ...
    }
}

Body:
As of Java 9 (2017), most answers in this page don't work, since you can't do skin.getBehavior() anymore.

This works:

@Override
public void handle(KeyEvent event) {
    KeyCode code = event.getCode();

    if (code == KeyCode.TAB && !event.isShiftDown() && !event.isControlDown()) {
        event.consume();
        Node node = (Node) event.getSource();
        try {
            Robot robot = new Robot();
            robot.keyPress(KeyCode.CONTROL.getCode());
            robot.keyPress(KeyCode.TAB.getCode());
            robot.delay(10);
            robot.keyRelease(KeyCode.TAB.getCode());
            robot.keyRelease(KeyCode.CONTROL.getCode());
            }
        catch (AWTException e) { }
        }
    }

This also works:

@Override
public void handle(KeyEvent event) {
    KeyCode code = event.getCode();

    if (code == KeyCode.TAB && !event.isShiftDown() && !event.isControlDown()) {
        event.consume();
        Node node = (Node) event.getSource();
        KeyEvent newEvent
          = new KeyEvent(event.getSource(),
                     event.getTarget(), event.getEventType(),
                     event.getCharacter(), event.getText(),
                     event.getCode(), event.isShiftDown(),
                     true, event.isAltDown(),
                     event.isMetaDown());

        node.fireEvent(newEvent);
        }
    }

Both simulate pressing CTRL+TAB when the user presses TAB. The default behaviour of the TextArea for CTRL+TAB is moving the focus to the next control. Please note the second code is based on Johan De Schutter's answer.


问:
window.print on a long React DOM captures only one page
I have a react component which renders markdown, and can be multi page.
When component is rendered in the browser, the scrolling in the component works fine.

But when I call window.print or ctrl + P on the page, the preview captrues only one page. Its not scrolling and not splitting the content into multiple pages.

Can somebody please suggest how to resolve this?

答:
Answering this hoping it will be useful to somebody else.

The react renders a virtual dom, rendering only the content of view port. Not full component. And print preview was getting only the content of view port.

I solved the issue by rendering everything to and IFrame and then printing the the IFrame.


问:
JDK 9 unsafe import sun.misc.Launcher
I've recently upgraded to JDK 9 and Eclipse complains that sun.misc.Launcher cannot be imported. It seems that sun.misc.Launcher is unsafe.
I'm looking for an alternative to replace this line of code in my project.

```<code>final URL url = Launcher.class.getResource("/");
</code>```

Any help would be appreciated.

Update: the more complete version of the above block of code is:

```<code>final URL url = Launcher.class.getResource("/");
final File fs = new File(url.toURI());
for (File f : fs.listFiles()) {
     System.out.println(f.getAbsolutePath());
}
</code>```

This is to print all the files in the src folder when program is launched in IDE.

答:
Class.getResource method can be invoked on any Class

```<code>final URL url = ClassInTheCurrentModule.class.getResource("/");
</code>```

UPDATE

Edited based on Feedback from members

Title: JDK 9 unsafe import sun.misc.Launcher

Body:
I've recently upgraded to JDK 9 and Eclipse complains that sun.misc.Launcher cannot be imported. It seems that sun.misc.Launcher is unsafe.
I'm looking for an alternative to replace this line of code in my project.

final URL url = Launcher.class.getResource("/");

Any help would be appreciated.

Update: the more complete version of the above block of code is:

final URL url = Launcher.class.getResource("/");
final File fs = new File(url.toURI());
for (File f : fs.listFiles()) {
     System.out.println(f.getAbsolutePath());
}

This is to print all the files in the src folder when program is launched in IDE.

Body:
Class.getResource method can be invoked on any Class

final URL url = ClassInTheCurrentModule.class.getResource("/");

UPDATE

Edited based on Feedback from members


问:
POST 400 (bad Request) Error
my environment is below

ASP.NET CORE 2.0

Here is Test Function

```<code>    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Test()
    {
        return RedirectToAction("Home");
    }
</code>```

and I use PostMan to send Post Data
http://localhost:00000/test/test

and always have 400 bad request... why?

[error message]

```<code>headers:Headers
ok:false
status:400
statusText:"Bad Request"
type:2
url:"http://localhost:57230/account/register"
_body:""
</code>```

[Updated]
I found solution.. but have new error XD

```<code> headers:Headers
 ok:false
 status:500
 statusText:"Internal Server Error"
 type:2
 url:"http://localhost:57227/account/register"
 _body:
</code>```

[Update]
Solved...

https://learn.microsoft.com/en-us/aspnet/core/publishing/iis

答:
I was facing a similar situation where the Form POST was routed to the correct controller, but then the controller returned an empty page (400 Error). The controller didn't even execute any code within it.

The issue appears to be the following:

If you do not place @Html.AntiForgeryToken() just after the <form> tag in your CSHTML, if you use [AutoValidateAntiforgeryToken] or [ValidateAntiForgeryToken] the Controller will return an empty page without output or console warning.

So it appears preventing cross-site or cross-session(?) attacks through HTML forms is working as intended.

Title: POST 400 (bad Request) Error

Body:
my environment is below

ASP.NET CORE 2.0

Here is Test Function

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Test()
    {
        return RedirectToAction("Home");
    }

and I use PostMan to send Post Data
http://localhost:00000/test/test

and always have 400 bad request... why?

[error message]

headers:Headers
ok:false
status:400
statusText:"Bad Request"
type:2
url:"http://localhost:57230/account/register"
_body:""

[Updated]
I found solution.. but have new error XD

 headers:Headers
 ok:false
 status:500
 statusText:"Internal Server Error"
 type:2
 url:"http://localhost:57227/account/register"
 _body:

[Update]
Solved...

https://learn.microsoft.com/en-us/aspnet/core/publishing/iis


问:
Async/Await Class Constructor
At the moment, I'm attempting to use async/await within a class constructor function.  This is so that I can get a custom e-mail tag for an Electron project I'm working on.

```<code>customElements.define('e-mail', class extends HTMLElement {
  async constructor() {
    super()

    let uid = this.getAttribute('data-uid')
    let message = await grabUID(uid)

    const shadowRoot = this.attachShadow({mode: 'open'})
    shadowRoot.innerHTML = `
      <div id="email">A random email message has appeared. ${message}</div>
    `
  }
})
</code>```

At the moment however, the project does not work, with the following error:

```<code>Class constructor may not be an async method
</code>```

Is there a way to circumvent this so that I can use async/await within this?  Instead of requiring callbacks or .then()?

答:
The other answers are missing the obvious. Simply call an async function from your constructor:</p>

```<code>constructor() {
    setContentAsync();
}

async setContentAsync() {
    let uid = this.getAttribute('data-uid')
    let message = await grabUID(uid)

    const shadowRoot = this.attachShadow({mode: 'open'})
    shadowRoot.innerHTML = `
      <div id="email">A random email message has appeared. ${message}</div>
    `
}
</code>```

Title: Async/Await Class Constructor

Body:
At the moment, I'm attempting to use async/await within a class constructor function.  This is so that I can get a custom e-mail tag for an Electron project I'm working on.

customElements.define('e-mail', class extends HTMLElement {
  async constructor() {
    super()

    let uid = this.getAttribute('data-uid')
    let message = await grabUID(uid)

    const shadowRoot = this.attachShadow({mode: 'open'})
    shadowRoot.innerHTML = `

A random email message has appeared. ${message}

    `
  }
})

At the moment however, the project does not work, with the following error:

Class constructor may not be an async method

Is there a way to circumvent this so that I can use async/await within this?  Instead of requiring callbacks or .then()?

Body:
The other answers are missing the obvious. Simply call an async function from your constructor:

constructor() {
    setContentAsync();
}

async setContentAsync() {
    let uid = this.getAttribute('data-uid')
    let message = await grabUID(uid)

    const shadowRoot = this.attachShadow({mode: 'open'})
    shadowRoot.innerHTML = `
      <div id="email">A random email message has appeared. ${message}</div>
    `
}


问:
How to store decimal in MySQL?
I've tried using DECIMAL with (2,2) but it won't let me use this.

I simply want to store a number, for example 7.50 or 10.50.  I need to keep both numbers after the decimal though but when I refresh the database it resets the values to 0.99.  Any suggestions?

答:
```<code>CREATE TABLE `salary` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`salary` DECIMAL(10,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
</code>```

DECIMAL(10,2) indicates that salary will hold a total of 10 digits out of which 2 will be after the decimal.

i.e.

8 digits before decimal and 2 digits after decimal.

Title: How to store decimal in MySQL?

Body:
CREATE TABLE `salary` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`salary` DECIMAL(10,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

DECIMAL(10,2) indicates that salary will hold a total of 10 digits out of which 2 will be after the decimal.

i.e.

8 digits before decimal and 2 digits after decimal.


问:
Invalid 'await' of a non-Promise value (Bluebird promise)
When I tslint my whole project using tslint --project tsconfig.json src/**/*.ts I get lots of tslint errors like these:

Invalid 'await' of a non-Promise value.

These errors pops up in every line where I am awaiting a Bluebird promise. I wonder what I should do to avoid these warnings? At runtime I don't face any issues, however I assume that there is a good reason to fix these issues?

For instance I am using the amqplib library which uses Bluebird for all promises. And every time I await one of the promise based methods I will get a tslint error:

```<code>const queueInfo: Replies.AssertQueue = await this.channel.assertQueue(this.jobQueueName);
</code>```

Question:

What is the best way for awaiting non-Promise values like Bluebird promises?

答:
It looks like TSLint contains a setting for indicating which types to treat as promises in await expressions:

https://palantir.github.io/tslint/rules/await-promise/

I haven't tried this myself, but it looks like you should be able to use this to allow awaiting Bluebird promises:

```<code>"await-promise": [true, "Bluebird"]
</code>```

Body:
When I tslint my whole project using tslint --project tsconfig.json src/**/*.ts I get lots of tslint errors like these:

Invalid 'await' of a non-Promise value.

These errors pops up in every line where I am awaiting a Bluebird promise. I wonder what I should do to avoid these warnings? At runtime I don't face any issues, however I assume that there is a good reason to fix these issues?

For instance I am using the amqplib library which uses Bluebird for all promises. And every time I await one of the promise based methods I will get a tslint error:

const queueInfo: Replies.AssertQueue = await this.channel.assertQueue(this.jobQueueName);

Question:

What is the best way for awaiting non-Promise values like Bluebird promises?

Body:
It looks like TSLint contains a setting for indicating which types to treat as promises in await expressions:

https://palantir.github.io/tslint/rules/await-promise/

I haven't tried this myself, but it looks like you should be able to use this to allow awaiting Bluebird promises:

"await-promise": [true, "Bluebird"]


问:
If an object is passed as an argument in a function, does it create a new instance?
In this code:

```<code>function myFunction(obj) {
  console.log(obj);
}

var obj = {
  key : 'value',
  funct :  function(){},
  elem  :  document.getElementById('navigation').getElementsByTagName('a')
}

myFunction(obj);
</code>```

Is the object "obj" printed in the console inside myFunction the same object i defined or is a new instance?

Also, what if i pass it from myFunction to another function?

答:
It's the same object, not a new instance. What gets passed into the function is a reference to the object, not a copy of the object. JavaScript is a purely pass-by-value language. The values passed into functions (and held in variables, etc.) for objects are references to the object, not the object itself.

You can readily prove that the object is not copied by modifying it in the function and seeing if you see those mods:

```<code>function foo(obj) {
    alert(obj.prop1);
    obj.prop2 = "foo";
}
var thingy = {
    prop1: 'bar'
}
foo(thingy);
alert(thingy.prop2);
</code>```

Live example

With the above, first you see the alert from foo showing the prop1 property of thingy, then you see the alert from the outer code showing the prop2 that foo assigned to it.

Body:
In this code:

function myFunction(obj) {
  console.log(obj);
}

var obj = {
  key : 'value',
  funct :  function(){},
  elem  :  document.getElementById('navigation').getElementsByTagName('a')
}

myFunction(obj);

Is the object "obj" printed in the console inside myFunction the same object i defined or is a new instance?

Also, what if i pass it from myFunction to another function?

Body:
It's the same object, not a new instance. What gets passed into the function is a reference to the object, not a copy of the object. JavaScript is a purely pass-by-value language. The values passed into functions (and held in variables, etc.) for objects are references to the object, not the object itself.

You can readily prove that the object is not copied by modifying it in the function and seeing if you see those mods:

function foo(obj) {
    alert(obj.prop1);
    obj.prop2 = "foo";
}
var thingy = {
    prop1: 'bar'
}
foo(thingy);
alert(thingy.prop2);

Live example

With the above, first you see the alert from foo showing the prop1 property of thingy, then you see the alert from the outer code showing the prop2 that foo assigned to it.


问:
GoogleAPI- Get signature setting via API
Is there anyway to get Gmail signature setting [on/off]?

I'm retrieving signature via https://developers.google.com/gmail/api/v1/reference/users/settings/sendAs

Unfortunately, the API does not contain any information about setting [No signature].

答:
Similar question: Gmail API returning email signature even if set as "No Signature" but no answer yet.
Related issue on Google's issuetracker: https://issuetracker.google.com/issues/68380736, https://issuetracker.google.com/issues/36760480, https://issuetracker.google.com/issues/69721532</p>