问:
Making my first angular directive. 'vm' is undefined
```<code>(function () {
  'use strict';

  angular
    .module('contacts.directives')
    .directive('hotkeys', HotkeysDirective);

  HotkeysDirective.$inject = ['$resource', '$document'];

  function HotkeysDirective($resource, $document) {
    var directive = {
      templateUrl: '/my-app/contacts/client/views/ui/hotkeys.ui.html',
      link: link,
      controller: 'AddManagerController',
      controllerAs: 'vm',
      scope: {},
      bindToController: {
        },
    };

    return directive;

    function link(scope, element, attrs, modelCtrl) {

      $document.bind('keypress', function (e) {
        var key = String.fromCharCode(e.which);
        if (key == 1 || key == 2 || key == 3 || key == 4 || key == 5 || key == 6) {
          scope.$broadcast('keypress', e, e.which);
        }
      });

      scope.$on('keypress', function (event, key) {
        // do stuff
        scope.$apply();
      });
    }
  }
}());
</code>```

This is the code that I think is not working...

```<code>HotkeysDirective.$inject = ['$resource', '$document'];

function HotkeysDirective($resource, $document) {
  var directive = {
    templateUrl: '/request-off-work/contacts/client/views/ui/hotkeys.ui.html',
    link: link,
    controller: 'AddManagerController',
    controllerAs: 'vm',
    scope: {},
    bindToController: {
      },
  };

  return directive;

  function link(scope, element, attrs, modelCtrl) {
</code>```

It's saying vm is undefined when I'm using controllerAs: 'vm', In the AddManagerController, it says 'var vm = this;'. Also not sure why scope: {} needs to be there, and I'll figure out bindToController eventually... I think I need to bind vm.credentials.groups to it.

Update: here's the controller

```<code>function AddManagerController($scope, $document, $rootScope, $state, $window, Authentication, ContactsService, Notification) {
  var vm = this;
  vm.authentication = Authentication;
  vm.credentials = {};
  vm.showGroups = [null, false, false, false, false, false, false];
</code>```

答: I changed vm.credentials.groups in the link function of the directive to scope.vm.credentials.groups and now it works. Hope this answer helps somebody.</p>

Body:
(function () {
  'use strict';

  angular
    .module('contacts.directives')
    .directive('hotkeys', HotkeysDirective);

  HotkeysDirective.$inject = ['$resource', '$document'];

  function HotkeysDirective($resource, $document) {
    var directive = {
      templateUrl: '/my-app/contacts/client/views/ui/hotkeys.ui.html',
      link: link,
      controller: 'AddManagerController',
      controllerAs: 'vm',
      scope: {},
      bindToController: {
        },
    };

    return directive;

    function link(scope, element, attrs, modelCtrl) {

      $document.bind('keypress', function (e) {
        var key = String.fromCharCode(e.which);
        if (key == 1 || key == 2 || key == 3 || key == 4 || key == 5 || key == 6) {
          scope.$broadcast('keypress', e, e.which);
        }
      });

      scope.$on('keypress', function (event, key) {
        // do stuff
        scope.$apply();
      });
    }
  }
}());

This is the code that I think is not working...

HotkeysDirective.$inject = ['$resource', '$document'];

function HotkeysDirective($resource, $document) {
  var directive = {
    templateUrl: '/request-off-work/contacts/client/views/ui/hotkeys.ui.html',
    link: link,
    controller: 'AddManagerController',
    controllerAs: 'vm',
    scope: {},
    bindToController: {
      },
  };

  return directive;

  function link(scope, element, attrs, modelCtrl) {

It's saying vm is undefined when I'm using controllerAs: 'vm', In the AddManagerController, it says 'var vm = this;'. Also not sure why scope: {} needs to be there, and I'll figure out bindToController eventually... I think I need to bind vm.credentials.groups to it.

Update: here's the controller

function AddManagerController($scope, $document, $rootScope, $state, $window, Authentication, ContactsService, Notification) {
  var vm = this;
  vm.authentication = Authentication;
  vm.credentials = {};
  vm.showGroups = [null, false, false, false, false, false, false];


来源: stackexchange

问:
Host multiple Symfony projects on the same domain
I have one domain and i need to host many symfony 3 projects in differents folder. For example :

www.domain.com/project1
www.domain.com/project2
...

My current nginx conf is :

```<code>server {
    server_name domain.fr www.domain.fr;
    root /var/proximiteclient/www/web;

    location / {
        # try to serve file directly, fallback to app.php
        try_files $uri /app.php$is_args$args;
    }

    # PROD
    location ~ ^/app\.php(/|$) {
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        # Prevents URIs that include the front controller. This will 404:
        # http://domain.tld/app.php/some-path
        # Remove the internal directive to allow URIs like this
        #internal;
    }

    # return 404 for all other php files not matching the front controller
    # this prevents access to other php files you don't want to be accessible.
    location ~ \.php$ {
      return 404;
    }

    error_log /var/log/nginx/domain_error.log;
    access_log /var/log/nginx/domain_access.log;

    listen 80; # managed by Certbot

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/domain.fr/fullchain.pem; # manag$
    ssl_certificate_key /etc/letsencrypt/live/domain.fr/privkey.pem; # man$
    ssl_session_cache shared:le_nginx_SSL:1m; # managed by Certbot
    ssl_session_timeout 1440m; # managed by Certbot
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # managed by Certbot
    ssl_prefer_server_ciphers on; # managed by Certbot

    ssl_ciphers "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE$

    #Redirect non-https traffic to https
    if ($scheme != "https") {
         return 301 https://$host$request_uri;
    } # managed by Certbot
}
</code>```

Sorry, i can't put in text mode it didn't work :(

Thansk very much !

答:
I'd recommend creating a pseudo-apache setup where you have "sites-available" that are auto-loaded into your nginx config.

For example:

```<code>//nginx.conf
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
</code>```

Then create /etc/nginx/sites-enabled and create a "site config" for each of the domains. This will keep them cleanly separated.

```<code>//etc/nginx/sites-enabled/dev.conf
server {
    listen 80;
    ssl off;
    server_name dev.example.com;
    root /path/to/example/web;
}

server {
    listen 443;
    server_name dev.example.com;
    return 301 http://$server_name$request_uri;
}
</code>```

And a second site for good measure..

```<code>//etc/nginx/sites-enabled/staging.conf
server {
    listen 80;
    ssl off;
    server_name staging.example.com;
    root /path/to/example2/web;
}

server {
    listen 443;
    server_name staging.example.com;
    return 301 http://$server_name$request_uri;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have one domain and i need to host many symfony 3 projects in differents folder. For example :

www.domain.com/project1
www.domain.com/project2
...

My current nginx conf is :

server {
    server_name domain.fr www.domain.fr;
    root /var/proximiteclient/www/web;

    location / {
        # try to serve file directly, fallback to app.php
        try_files $uri /app.php$is_args$args;
    }

    # PROD
    location ~ ^/app\.php(/|$) {
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        # Prevents URIs that include the front controller. This will 404:
        # http://domain.tld/app.php/some-path
        # Remove the internal directive to allow URIs like this
        #internal;
    }

    # return 404 for all other php files not matching the front controller
    # this prevents access to other php files you don't want to be accessible.
    location ~ \.php$ {
      return 404;
    }

    error_log /var/log/nginx/domain_error.log;
    access_log /var/log/nginx/domain_access.log;

    listen 80; # managed by Certbot

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/domain.fr/fullchain.pem; # manag$
    ssl_certificate_key /etc/letsencrypt/live/domain.fr/privkey.pem; # man$
    ssl_session_cache shared:le_nginx_SSL:1m; # managed by Certbot
    ssl_session_timeout 1440m; # managed by Certbot
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # managed by Certbot
    ssl_prefer_server_ciphers on; # managed by Certbot

    ssl_ciphers "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE$

    #Redirect non-https traffic to https
    if ($scheme != "https") {
         return 301 https://$host$request_uri;
    } # managed by Certbot
}

Sorry, i can't put in text mode it didn't work :(

Thansk very much !

Body:
I'd recommend creating a pseudo-apache setup where you have "sites-available" that are auto-loaded into your nginx config.

For example:

//nginx.conf
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

Then create /etc/nginx/sites-enabled and create a "site config" for each of the domains. This will keep them cleanly separated.

//etc/nginx/sites-enabled/dev.conf
server {
    listen 80;
    ssl off;
    server_name dev.example.com;
    root /path/to/example/web;
}

server {
    listen 443;
    server_name dev.example.com;
    return 301 http://$server_name$request_uri;
}

And a second site for good measure..

//etc/nginx/sites-enabled/staging.conf
server {
    listen 80;
    ssl off;
    server_name staging.example.com;
    root /path/to/example2/web;
}

server {
    listen 443;
    server_name staging.example.com;
    return 301 http://$server_name$request_uri;
}


问:
Loops, "have n items to process but only n-1 update steps"
Consider the following loop:

```<code>marker_stream = 0
for character in input_file:
            if character != ',':
               marker_stream |= 1
            marker_stream <<= 1
</code>```

For each character in input_file_contents, this loop does a processing step, stores the result of the processing step (either a 0 or 1 bit) in marker_stream, and then shifts marker_stream over by one position to prepare for the next iteration.

Here's the problem: I want to process each character in the input file, but I only want to shift marker_stream number of characters in the input file - 1 times. The loop above shifts marker_stream one too many times.

Now, I know I could add marker_stream >>= 1 after the for loop, or I could maintain some flag that says whether or not the character we're currently processing is the last character in the file, but neither of these solutions seem that great. The flag solution involves flags (yuck), and the extra line solution could be confusing if the processing loop was longer.

I'm looking for a more elegant solution to this problem, and, more generally the "I have n items to process but have an update step I want to run only n-1 times" problem.

答:
Process the first element in the file separately; treat the file as a one-entry head with a tail holding the rest of the entries:

```<code>// Process head
entry <- readNext(inFile)
write(entry, outFile)

// Process tail
while (NOT inFile.endOfFile)
  write(separator, outFile)
  entry <- readNext(inFile)
  write(entry, outFile)
endwhile
</code>```

The head entry does not follow a separator; the tail entries all follow a separator.  You get your 'n-1' effect by treating the single head entry differently from the n-1 tail entries in the file.

Body:
Consider the following loop:

marker_stream = 0
for character in input_file:
            if character != ',':
               marker_stream |= 1
            marker_stream <<= 1

For each character in input_file_contents, this loop does a processing step, stores the result of the processing step (either a 0 or 1 bit) in marker_stream, and then shifts marker_stream over by one position to prepare for the next iteration.

Here's the problem: I want to process each character in the input file, but I only want to shift marker_stream number of characters in the input file - 1 times. The loop above shifts marker_stream one too many times.

Now, I know I could add marker_stream >>= 1 after the for loop, or I could maintain some flag that says whether or not the character we're currently processing is the last character in the file, but neither of these solutions seem that great. The flag solution involves flags (yuck), and the extra line solution could be confusing if the processing loop was longer.

I'm looking for a more elegant solution to this problem, and, more generally the "I have n items to process but have an update step I want to run only n-1 times" problem.

Body:
Process the first element in the file separately; treat the file as a one-entry head with a tail holding the rest of the entries:

// Process head
entry <- readNext(inFile)
write(entry, outFile)

// Process tail
while (NOT inFile.endOfFile)
  write(separator, outFile)
  entry <- readNext(inFile)
  write(entry, outFile)
endwhile

The head entry does not follow a separator; the tail entries all follow a separator.  You get your 'n-1' effect by treating the single head entry differently from the n-1 tail entries in the file.


问:
Can I use array.prototype.reduce() to process two arrays at once?
I have two arrays of same length and I would like to somehow process them both at once with the reduce method. Something like:

```<code>var arr1 = [2, 3, 4, 5, 6];
var arr2 = [5, 10, 4, 9, 5];
var productSum = arr1.reduce(function(sumOfProducts, item, secondArrayItem) {
    /* here I would like to multiply item from arr1 by the item from arr2 at the same index */
    return sumOfProducts + item * secondArrayItem;
}, 0, arr2)
console.log(productSum);  // 131
</code>```

An option would of course be to access the correct item from arr2 using currentIndex, but that solution is ugly as I am accessing a variable outside of the scope of the function.

My specific use case is that I have an array with resources like var resources = [2, 5, 4, 6, 2] and I want to check if each item is higher than corresponding resource cost in another array like var cost = [3, 1, 0, 0, 1].

Is there some nice solution to this using the reduce() function?

答:
The standard way that I know to do this is to combine the 2 lists into a list of corresponding pairs ("zipping"), then reduce the combined lists:

```<code>var zipped = zip(arr1, arr2)

reduce((acc, [x, y]) => (Use x and y),
              zipped)
</code>```

For implementations of zip, see this question.

(Will verify syntax when I got off of transit)

Body:
I have two arrays of same length and I would like to somehow process them both at once with the reduce method. Something like:

var arr1 = [2, 3, 4, 5, 6];
var arr2 = [5, 10, 4, 9, 5];
var productSum = arr1.reduce(function(sumOfProducts, item, secondArrayItem) {
    /* here I would like to multiply item from arr1 by the item from arr2 at the same index */
    return sumOfProducts + item * secondArrayItem;
}, 0, arr2)
console.log(productSum);  // 131

An option would of course be to access the correct item from arr2 using currentIndex, but that solution is ugly as I am accessing a variable outside of the scope of the function.

My specific use case is that I have an array with resources like var resources = [2, 5, 4, 6, 2] and I want to check if each item is higher than corresponding resource cost in another array like var cost = [3, 1, 0, 0, 1].

Is there some nice solution to this using the reduce() function?

Body:
The standard way that I know to do this is to combine the 2 lists into a list of corresponding pairs ("zipping"), then reduce the combined lists:

var zipped = zip(arr1, arr2)

reduce((acc, [x, y]) => (Use x and y),
              zipped)

For implementations of zip, see this question.

(Will verify syntax when I got off of transit)


问:
Automatically generate MD5 and display
On a page that automatically lists several small files (~100-500kb) that are contained in a specific folder, is there a way using VBScript to automatically generate MD5 hashes of each file and display it on the page?

Cliff notes: Can I generate an MD5 hash of a file on the server machine?

答:
If the VBScript is client-side you have a problem.

If it runs server-side then it's easy (as long as the web server has read rights).

Simple solution - for each file get its MD5 hash by:

Read the file into memory

Calculate the MD5 hash with System.Security.Cryptography.MD5CryptoServiceProvider

Convert to hex with System.BitConverter.ToString(array).Replace("-","")

A (much) better solution would be to read the file in blocks and feed it to MD5CryptoServiceProvider, because loading an entire big file into memory is not the best thing in the world.

ContentLicense: CC BY-SA 2.5

Title: Automatically generate MD5 and display

OwnerDisplayName: orip


问:
How to left align footer element in GridView
I am getting problem in alignment of element that is in FooterTemplate of GridView.
Anyone suggest me how to do it.The Code is:

```<code><asp:GridView ID="gvComment" runat="server" AutoGenerateColumns="false"
OnRowDataBound="gvComment_RowDataBound" OnRowCreated="gvComment_RowCreated" Width="100%" ShowHeader="false" BorderWidth="0px" ShowFooter="true">
<Columns>
    <asp:TemplateField>
        <ItemTemplate>
            <table border="0" cellpadding="0" cellspacing="0" width="100%" >
                <tr>
                    <td valign="middle" align="left" style="width:10%"><img id="imgUser" src="" alt="" title="" runat="server" /></td>
                    <td align="left" valign="top">
                        comment comment
                        <asp:Label ID="lblNameComments" runat="server" Visible="false" ></asp:Label>
                    </td>
                </tr>
                <tr><td colspan="2" style="height:7px;"></td></tr>
                <tr>
                    <td colspan="2" style="padding-top:10px;background-image:url(../Images/dotted_line.jpg);background-repeat:repeat-x;background-position:center;"></td>
                </tr>
                <tr><td colspan="2" style="height:7px;"></td></tr>
            </table>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
        <FooterTemplate >
        <table border="0" cellpadding="0" cellspacing="0" width="100%" >
            <tr>
                <td align="left">
                    Footer Text
                   Footer Text
                   Footer Text
                </td>
            </tr>
        </table>
        </FooterTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>
</code>```

I have set align property of td left but it doesn't work.Page output shown in image.

答:
Have you tried to add align="left" on the table from  <FooterTemplate > ?

```<code><table border="0" cellpadding="0" cellspacing="0" width="100%" align="left">
<tr>
    <td align="left">
       Footer Text
       Footer Text
       Footer Text
    </td>
</tr>
</table>
</code>```

Body:
I am getting problem in alignment of element that is in FooterTemplate of GridView.
Anyone suggest me how to do it.The Code is:

<asp:GridView ID="gvComment" runat="server" AutoGenerateColumns="false"
OnRowDataBound="gvComment_RowDataBound" OnRowCreated="gvComment_RowCreated" Width="100%" ShowHeader="false" BorderWidth="0px" ShowFooter="true">
<Columns>
    <asp:TemplateField>
        <ItemTemplate>

                        comment comment
                        <asp:Label ID="lblNameComments" runat="server" Visible="false" ></asp:Label>

        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
        <FooterTemplate >

                    Footer Text
                   Footer Text
                   Footer Text

        </FooterTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>

I have set align property of td left but it doesn't work.Page output shown in image.

Body:
Have you tried to add align="left" on the table from  <FooterTemplate > ?

<table border="0" cellpadding="0" cellspacing="0" width="100%" align="left">
<tr>
    <td align="left">
       Footer Text
       Footer Text
       Footer Text
    </td>
</tr>
</table>


问:
Public/Private key authentication for Ruby Net::SFTP
I am having trouble finding documentation for specifying a key for SFTP authentication.

Would like to have something like:

```<code>export SOME_PRIVATE_KEY="$(cat tmp/some-certs/privatekey.pem)"

# then somewhere in the code
private_key = OpenSSL::PKey::RSA.new(ENV['SOME_PRIVATE_KEY'])

Net::SFTP.start(ftp_host, user, key: private_key) do |sftp|
  sftp.dir.entries('/path/to/folder').each do |remote_file|
     # ...
  end
end
</code>```

答:
Net::SFTP.start passes its options hash directly to Net::SSH.start, so we should look to its documentation. It lists three options that look relevant:

:keys => an array of file names of private keys to use for publickey and hostbased authentication

:key_data => an array of strings, with each element of the array being a raw private key in PEM format.

:keys_only => set to true to use only private keys from keys and key_data parameters, even if ssh-agent offers more identities. This option is intended for situations where ssh-agent offers many different identites.

The answer to a related question suggests that you may need to use all three:

```<code>Net::SFTP.start(ftp_host, user,
  key_data: [],
  keys: "tmp/some-certs/privatekey.pem",
  keys_only: true)
</code>```

If you want to use the raw key data from the SOME_PRIVATE_KEY environment variable instead, it ought to look like this:

```<code>Net::SFTP.start(ftp_host, user,
  key_data: [ ENV["SOME_PRIVATE_KEY"] ],
  keys: [],
  keys_only: true)
</code>```

Body:
I am having trouble finding documentation for specifying a key for SFTP authentication.

Would like to have something like:

export SOME_PRIVATE_KEY="$(cat tmp/some-certs/privatekey.pem)"

# then somewhere in the code
private_key = OpenSSL::PKey::RSA.new(ENV['SOME_PRIVATE_KEY'])

Net::SFTP.start(ftp_host, user, key: private_key) do |sftp|
  sftp.dir.entries('/path/to/folder').each do |remote_file|
     # ...
  end
end

Body:
Net::SFTP.start passes its options hash directly to Net::SSH.start, so we should look to its documentation. It lists three options that look relevant:

:keys => an array of file names of private keys to use for publickey and hostbased authentication

:key_data => an array of strings, with each element of the array being a raw private key in PEM format.

:keys_only => set to true to use only private keys from keys and key_data parameters, even if ssh-agent offers more identities. This option is intended for situations where ssh-agent offers many different identites.

The answer to a related question suggests that you may need to use all three:

Net::SFTP.start(ftp_host, user,
  key_data: [],
  keys: "tmp/some-certs/privatekey.pem",
  keys_only: true)

If you want to use the raw key data from the SOME_PRIVATE_KEY environment variable instead, it ought to look like this:

Net::SFTP.start(ftp_host, user,
  key_data: [ ENV["SOME_PRIVATE_KEY"] ],
  keys: [],
  keys_only: true)


问:
UIScrollView how to restore to original size after UIImageView pinch zoom
I have a collection view containing several images. I can zoom an image in the cell but I want it and the scroll view to return to its original size on a tap gesture. My tap gesture restores the image to it's original size but it's off the screen and the scroll view remains it's zoomed size. Here is my code:</p>

```<code>import UIKit

class ZoomingCollectionViewCell: UICollectionViewCell, UIScrollViewDelegate {

let zoomScrollView: UIScrollView = {
    let scrollView = UIScrollView()
    scrollView.backgroundColor = .white
    scrollView.isUserInteractionEnabled = true
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    scrollView.minimumZoomScale = 1.0
    scrollView.maximumZoomScale = 6.0
    scrollView.clipsToBounds = true
    return scrollView
}()

var itemImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.contentMode = .scaleAspectFit
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.backgroundColor = .white
    imageView.isUserInteractionEnabled = true
    return imageView
}()

var originalSize: CGRect!

override init(frame: CGRect) {
    super.init(frame: frame)

    contentView.backgroundColor = .white

    zoomScrollView.delegate = self

    itemImageView.frame = CGRect(x: 0, y: 0, width: contentView.frame.size.width, height: contentView.frame.size.height)

    zoomScrollView.frame = itemImageView.frame

    originalSize = itemImageView.frame

    let tap = UITapGestureRecognizer(target: self, action: #selector(tapZoomingGesture(_:)))

    tap.numberOfTapsRequired = 2

    zoomScrollView.addGestureRecognizer(tap)

    zoomScrollView.addSubview(itemImageView)

    contentView.addSubview(zoomScrollView)
}

func viewForZooming(in zoomScrollView: UIScrollView) -> UIView? {

    return itemImageView
}

func tapZoomingGesture(_ sender: UIPinchGestureRecognizer) {

    itemImageView.center = itemImageView.superview!.center

    itemImageView.transform = .identity

    zoomScrollView.frame = originalSize
}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    return true
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}
</code>```

答:
This works for me. I just noticed that I used UIPinchGestureRecognizer as the sender but for some reason it works anyway.

```<code>func tapZoomingGesture(_ sender: UIPinchGestureRecognizer) {

    let newZoomScale: CGFloat = 1.0000001

    let scrollViewSize = zoomScrollView.bounds.size

    let w = (scrollViewSize.width / newZoomScale)
    let h = (scrollViewSize.height / newZoomScale)
    let x = w / 6.0
    let y = h / 6.0

    let rectToZoomTo = CGRect(x, y, w, h)

    zoomScrollView.zoom(to: rectToZoomTo, animated: true)

    zoomScrollView.frame = itemImageView.frame

    itemImageView.center = zoomScrollView.center

}
</code>```

Body:
I have a collection view containing several images. I can zoom an image in the cell but I want it and the scroll view to return to its original size on a tap gesture. My tap gesture restores the image to it's original size but it's off the screen and the scroll view remains it's zoomed size. Here is my code:

import UIKit

class ZoomingCollectionViewCell: UICollectionViewCell, UIScrollViewDelegate {

let zoomScrollView: UIScrollView = {
    let scrollView = UIScrollView()
    scrollView.backgroundColor = .white
    scrollView.isUserInteractionEnabled = true
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    scrollView.minimumZoomScale = 1.0
    scrollView.maximumZoomScale = 6.0
    scrollView.clipsToBounds = true
    return scrollView
}()

var itemImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.contentMode = .scaleAspectFit
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.backgroundColor = .white
    imageView.isUserInteractionEnabled = true
    return imageView
}()

var originalSize: CGRect!

override init(frame: CGRect) {
    super.init(frame: frame)

    contentView.backgroundColor = .white

    zoomScrollView.delegate = self

    itemImageView.frame = CGRect(x: 0, y: 0, width: contentView.frame.size.width, height: contentView.frame.size.height)

    zoomScrollView.frame = itemImageView.frame

    originalSize = itemImageView.frame

    let tap = UITapGestureRecognizer(target: self, action: #selector(tapZoomingGesture(_:)))

    tap.numberOfTapsRequired = 2

    zoomScrollView.addGestureRecognizer(tap)

    zoomScrollView.addSubview(itemImageView)

    contentView.addSubview(zoomScrollView)
}

func viewForZooming(in zoomScrollView: UIScrollView) -> UIView? {

    return itemImageView
}

func tapZoomingGesture(_ sender: UIPinchGestureRecognizer) {

    itemImageView.center = itemImageView.superview!.center

    itemImageView.transform = .identity

    zoomScrollView.frame = originalSize
}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    return true
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

Body:
This works for me. I just noticed that I used UIPinchGestureRecognizer as the sender but for some reason it works anyway.

func tapZoomingGesture(_ sender: UIPinchGestureRecognizer) {

    let newZoomScale: CGFloat = 1.0000001

    let scrollViewSize = zoomScrollView.bounds.size

    let w = (scrollViewSize.width / newZoomScale)
    let h = (scrollViewSize.height / newZoomScale)
    let x = w / 6.0
    let y = h / 6.0

    let rectToZoomTo = CGRect(x, y, w, h)

    zoomScrollView.zoom(to: rectToZoomTo, animated: true)

    zoomScrollView.frame = itemImageView.frame

    itemImageView.center = zoomScrollView.center

}


问:
Angularjs formData.append is not working
Hi I am developing angularjs application. I have file upload module. I am appending file data to FormData as below.

```<code> var filesformdata = new FormData();
    angular.forEach(this.pendingFiles, function (value, key) {
                filesformdata.append(key, value);
            });
            for (var pair of filesformdata.entries()) {
                console.log(pair[0] + ', ' + pair[1]);
            }
</code>```

This is My angular code.

```<code>angular.module('RoslpApp').factory('fileUpload', ['$http', function ($http) {
    debugger;
    var fileuploadurl = "http://localhost:19144/" + 'api/Customer/UploadLeaseFiles/' + 2;
    var service = {
        uploadUrl: fileuploadurl,
        pendingFiles: [],
        doUpload: doUpload
    };
    return service;

    function doUpload() {
        debugger;
        var filesformdata = new FormData();
        angular.forEach(this.pendingFiles, function (value, key) {
            filesformdata.append(key, value);
        });
        for (var pair of filesformdata.entries()) {
            console.log(pair[0] + ', ' + pair[1]);
        }

        return $http.post(this.uploadUrl, filesformdata, {
            transformRequest: angular.identity,
            headers: {
                'Content-Type': undefined
            }
        })
    }
}]);
</code>```

This is directive code.

```<code>myapp.directive('fileModel', ['fileUpload', function (fileUpload) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.bind("change", function (evt) {
                fileUpload.pendingFiles[attrs.fileModel] = evt.target.files[0];
            });
        }
    };
}]);
</code>```

This is upload function

```<code>  $scope.upload = function (filename) {
                debugger;
                fileUpload.doUpload().success(function (success) {
                   console.log(success);
                });
            };
</code>```

This is html code.

```<code><div class="upload-button" ng-repeat="file in files">
                <div class="upload-button-icon">
                    <img src="images/folder-small.png">
                    <div class="upload-text">{{file}}</div>
                    <input type="file" id="file1" name="file1" file-data="{{file}}" file-model="{{file}}"/>
                </div>
            </div>
   <input type="submit" value="{{ 'NEXT' | translate }}" class="blue-button" ng-click="upload()">
</code>```

Eventough i have files in this.pendingFiles when i display using console.log or in api using below code i dont get files.

```<code>  System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
                // CHECK THE FILE COUNT.
                UploadedLeaseFiles totalDocumentInserted = null;
                for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
</code>```

I have files inside this.pendingFiles. Please see the screen shot.

My filesformdata FormData is empty always. May i get some help here to fix this? Thanks.

答:
Here is a filesInput directive that integrates with the ngModelController API:

```<code>app.directive("filesInput", function() {
  return {
    require: "ngModel",
    link: postLink
  };
  function postLink(scope, elem, attrs, ngModel) {
    elem.on("change", function() {
      ngModel.$setViewValue(elem[0].files);
    })
  }
});
</code>```

Usage:

```<code><input type=file ng-model="files" files-input multiple />
</code>```

Test it with:

```<code>  vm.compute = function () {
        var filesformdata = new FormData();
        angular.forEach(vm.files, function (value, key) {
            filesformdata.append(key, value);
        });
        for (var pair of filesformdata.entries()) {
            console.log(pair[0] + ', ' + pair[1]);
            console.log(pair[1]);
        }

  }
</code>```

You will find that formData.append works.

The DEMO on PLNKR

Body:
Hi I am developing angularjs application. I have file upload module. I am appending file data to FormData as below.

 var filesformdata = new FormData();
    angular.forEach(this.pendingFiles, function (value, key) {
                filesformdata.append(key, value);
            });
            for (var pair of filesformdata.entries()) {
                console.log(pair[0] + ', ' + pair[1]);
            }

This is My angular code.

angular.module('RoslpApp').factory('fileUpload', ['$http', function ($http) {
    debugger;
    var fileuploadurl = "http://localhost:19144/" + 'api/Customer/UploadLeaseFiles/' + 2;
    var service = {
        uploadUrl: fileuploadurl,
        pendingFiles: [],
        doUpload: doUpload
    };
    return service;

    function doUpload() {
        debugger;
        var filesformdata = new FormData();
        angular.forEach(this.pendingFiles, function (value, key) {
            filesformdata.append(key, value);
        });
        for (var pair of filesformdata.entries()) {
            console.log(pair[0] + ', ' + pair[1]);
        }

        return $http.post(this.uploadUrl, filesformdata, {
            transformRequest: angular.identity,
            headers: {
                'Content-Type': undefined
            }
        })
    }
}]);

This is directive code.

myapp.directive('fileModel', ['fileUpload', function (fileUpload) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.bind("change", function (evt) {
                fileUpload.pendingFiles[attrs.fileModel] = evt.target.files[0];
            });
        }
    };
}]);

This is upload function

  $scope.upload = function (filename) {
                debugger;
                fileUpload.doUpload().success(function (success) {
                   console.log(success);
                });
            };

This is html code.

{{file}}

                    <input type="file" id="file1" name="file1" file-data="{{file}}" file-model="{{file}}"/>

   <input type="submit" value="{{ 'NEXT' | translate }}" class="blue-button" ng-click="upload()">

Eventough i have files in this.pendingFiles when i display using console.log or in api using below code i dont get files.

  System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
                // CHECK THE FILE COUNT.
                UploadedLeaseFiles totalDocumentInserted = null;
                for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)

I have files inside this.pendingFiles. Please see the screen shot.

My filesformdata FormData is empty always. May i get some help here to fix this? Thanks.

Body:
Here is a filesInput directive that integrates with the ngModelController API:

app.directive("filesInput", function() {
  return {
    require: "ngModel",
    link: postLink
  };
  function postLink(scope, elem, attrs, ngModel) {
    elem.on("change", function() {
      ngModel.$setViewValue(elem[0].files);
    })
  }
});

Usage:

<input type=file ng-model="files" files-input multiple />

Test it with:

  vm.compute = function () {
        var filesformdata = new FormData();
        angular.forEach(vm.files, function (value, key) {
            filesformdata.append(key, value);
        });
        for (var pair of filesformdata.entries()) {
            console.log(pair[0] + ', ' + pair[1]);
            console.log(pair[1]);
        }

  }

You will find that formData.append works.

The DEMO on PLNKR


问:
Very simple array, loop, and logical comparison issue
Very simple question: I'm trying to compare values in an array and I'm completely stumped as to why my comparison logic is failing. Somehow, during the course of my loop, 6 is being evaluated as > 524. Any ideas as to what I'm doing wrong? I'm totally stumped. Here's the code, and thanks!

```<code>function highAndLow(numbers){

    var compArr = numbers.split(" ");

    var highNum = compArr[0]
    var lowNum = compArr[0];

      for (i = 1; i < compArr.length; i++) {
        if (compArr[i] > highNum) {
          highNum = compArr[i]
          console.log(highNum)
        }
      }

      for (i = 1; i < compArr.length; i++) {
        if (compArr[i] < lowNum) {
          lowNum = compArr[i]
        }
      }

      return highNum + " " + lowNum
}

highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")
</code>```

Again, I'm not sure how, but the result I'm getting in the console is 6 for the highNum (incorrect) and -214 for the lowNum (which is correct). Am I missing something obvious?

答:
edited to include Barmar's answer. Thanks Barmar!

I figured it out. My comparison was running to the edge of the array and trying to compare to undefined. Also, because of the way I had set things up, this method wouldn't work on strings with only two values. Here's my new code:

```<code>function highAndLow(numbers){

    var compArr = numbers.split(" ").map(Number);

    var highNum = compArr[0]
    var lowNum = compArr[0];

    if (compArr.length === 2) {
      if (compArr[1] > highNum) {
          highNum = compArr[1]
      }
      if (compArr[1] < lowNum) {
          lowNum = compArr[1]
      }

    } else {
        for (i = 1; i < compArr.length - 2; i++) {
          if (compArr[i] > highNum) {
            highNum = compArr[i]
          }
        }

        for (i = 1; i < compArr.length - 2; i++) {
          if (compArr[i] < lowNum) {
            lowNum = compArr[i]
          }
        }
      }

      return highNum + " " + lowNum

}
</code>```

There's probably a better/cleaner way to do this, however.

Body:
Very simple question: I'm trying to compare values in an array and I'm completely stumped as to why my comparison logic is failing. Somehow, during the course of my loop, 6 is being evaluated as > 524. Any ideas as to what I'm doing wrong? I'm totally stumped. Here's the code, and thanks!

function highAndLow(numbers){

    var compArr = numbers.split(" ");

    var highNum = compArr[0]
    var lowNum = compArr[0];

      for (i = 1; i < compArr.length; i++) {
        if (compArr[i] > highNum) {
          highNum = compArr[i]
          console.log(highNum)
        }
      }

      for (i = 1; i < compArr.length; i++) {
        if (compArr[i] < lowNum) {
          lowNum = compArr[i]
        }
      }

      return highNum + " " + lowNum
}

highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")

Again, I'm not sure how, but the result I'm getting in the console is 6 for the highNum (incorrect) and -214 for the lowNum (which is correct). Am I missing something obvious?

Body:
edited to include Barmar's answer. Thanks Barmar!

I figured it out. My comparison was running to the edge of the array and trying to compare to undefined. Also, because of the way I had set things up, this method wouldn't work on strings with only two values. Here's my new code:

function highAndLow(numbers){

    var compArr = numbers.split(" ").map(Number);

    var highNum = compArr[0]
    var lowNum = compArr[0];

    if (compArr.length === 2) {
      if (compArr[1] > highNum) {
          highNum = compArr[1]
      }
      if (compArr[1] < lowNum) {
          lowNum = compArr[1]
      }

    } else {
        for (i = 1; i < compArr.length - 2; i++) {
          if (compArr[i] > highNum) {
            highNum = compArr[i]
          }
        }

        for (i = 1; i < compArr.length - 2; i++) {
          if (compArr[i] < lowNum) {
            lowNum = compArr[i]
          }
        }
      }

      return highNum + " " + lowNum

}

There's probably a better/cleaner way to do this, however.


问:
How to count the length of a tuple in Haskell?
I tried searching in web and stackexchange, but surprisingly no one asked how to calculate length of a tuple in Haskell in the form below.

So suppose you have tuple like (1,2,3,4) or (1,3,5,6,7) in Haskell and wish to write the length function that calculates length of a tuple. How can I do this? For list I know how I will be able to do so using recursion without explicitly invoking built-in functions. But tuple is different, and I can't use "head"-"tail" distinction.

Will the method involve creating a new data type?

答:
The reason you don't find anything on this is that it doesn't make a lot of sense to count the length of a tuple:

It is pre-determined a compile time (i.e. you might just as well hard-code it)

There's not really much you could do with that information: unlike with e.g. a list, it's not possible to index specific entries in a generic tuple.

That said, it is possible to achieve your goal, however this shouldn't be a normal function but a type-level function, aka type family. Using singleton type nats:

```<code>{-# LANGUAGE TypeFamilies, DataKinds #-}
import Data.Singletons
import Data.Singletons.TypeLits

type family TupLength a :: Nat where
  TupLength () = 0
  TupLength (a,b) = 2
  TupLength (a,b,c) = 3
  TupLength (a,b,c,d) = 4
  -- ...
  TupLength x = 1
</code>```

Then

```<code>> mapM_ print [ natVal (sing :: SNat (TupLength ()))
              , natVal (sing :: SNat (TupLength (Int,String,Double)))
              , natVal (sing :: SNat (TupLength Bool)) ]
0
3
1
</code>```

Body:
The reason you don't find anything on this is that it doesn't make a lot of sense to count the length of a tuple:

It is pre-determined a compile time (i.e. you might just as well hard-code it)

There's not really much you could do with that information: unlike with e.g. a list, it's not possible to index specific entries in a generic tuple.

That said, it is possible to achieve your goal, however this shouldn't be a normal function but a type-level function, aka type family. Using singleton type nats:

{-# LANGUAGE TypeFamilies, DataKinds #-}
import Data.Singletons
import Data.Singletons.TypeLits

type family TupLength a :: Nat where
  TupLength () = 0
  TupLength (a,b) = 2
  TupLength (a,b,c) = 3
  TupLength (a,b,c,d) = 4
  -- ...
  TupLength x = 1

Then

> mapM_ print [ natVal (sing :: SNat (TupLength ()))
              , natVal (sing :: SNat (TupLength (Int,String,Double)))
              , natVal (sing :: SNat (TupLength Bool)) ]
0
3
1


问:
Django cannot use Sum with SQLite and time fields?
I have a model with a time field, and I need to sum the time fields in all instances.

This is what I've tried:

```<code>total_hours = Day.objects.filter(date__year=current_year, date__month=current_month).aggregate(Sum('total_work_hours'))
print(total_hours)
</code>```

and I get this error:

You cannot use Sum, Avg, StdDev, and Variance aggregations on date/time fields in sqlite3 since date/time is saved as text.

Is there a way around this? I'd like to stick with SQLite for now.

答:
Without changing databases, you will have to do this in Python. You can do it rather cheaply by using values_list to just pull the total_work_hours for each day, and sum them.

```<code>hours = Day.objects.filter(
    date__year=current_year,
    date__month=current_month
).values_list('total_work_hours', flat=True)

total_hours = sum(hours)
print(total_hours)
</code>```

Body:
I have a model with a time field, and I need to sum the time fields in all instances.

This is what I've tried:

total_hours = Day.objects.filter(date__year=current_year, date__month=current_month).aggregate(Sum('total_work_hours'))
print(total_hours)

and I get this error:

You cannot use Sum, Avg, StdDev, and Variance aggregations on date/time fields in sqlite3 since date/time is saved as text.

Is there a way around this? I'd like to stick with SQLite for now.

Body:
Without changing databases, you will have to do this in Python. You can do it rather cheaply by using values_list to just pull the total_work_hours for each day, and sum them.

hours = Day.objects.filter(
    date__year=current_year,
    date__month=current_month
).values_list('total_work_hours', flat=True)

total_hours = sum(hours)
print(total_hours)


问:
How do I insert a space between an alpha character and a numeric character?
This is a continuation of my original question:
Perl- How do I insert a space before each capital letter except for the first occurrence or existing?

I was able to achieve a desired result of inserting spaces between caps with only letters in the string:

```<code>my $camel ="SomeCamel IsEnteringText";
$camel =~ s/(?<=[a-z])(?=[A-Z])/ /g;
$camel =~ s/([^[:space:]]+)/\u$1/g;
</code>```

Prints:

Some Camel Is Entering Text

But, when numbers are present, I ran into issues:

```<code>my $camel ="Some 440Camel220 IsEntering100Text Nogo";
$camel =~ s/(?<=[a-z])(?=[A-Z])/ /g;
$camel =~ s/([^[:space:]]+)/\u$1/g;
</code>```

Prints:

Some 440Camel220 Is Entering100Text Nogo

Desired:

Some 440 Camel 220 Is Entering 100 Text Nogo

So, how do I now insert a space between the letters and the numbers?.

答:
Change the first substitution to be:

```<code>$camel =~ s/(?<=[a-z])(?=[A-Z0-9])|(?<=[0-9])(?=[A-Z])/ /g;
</code>```

See also perldoc perlre.

Body:
This is a continuation of my original question:
Perl- How do I insert a space before each capital letter except for the first occurrence or existing?

I was able to achieve a desired result of inserting spaces between caps with only letters in the string:

my $camel ="SomeCamel IsEnteringText";
$camel =~ s/(?<=[a-z])(?=[A-Z])/ /g;
$camel =~ s/([^[:space:]]+)/\u$1/g;

Prints:

Some Camel Is Entering Text

But, when numbers are present, I ran into issues:

my $camel ="Some 440Camel220 IsEntering100Text Nogo";
$camel =~ s/(?<=[a-z])(?=[A-Z])/ /g;
$camel =~ s/([^[:space:]]+)/\u$1/g;

Prints:

Some 440Camel220 Is Entering100Text Nogo

Desired:

Some 440 Camel 220 Is Entering 100 Text Nogo

So, how do I now insert a space between the letters and the numbers?.

Body:
Change the first substitution to be:

$camel =~ s/(?<=[a-z])(?=[A-Z0-9])|(?<=[0-9])(?=[A-Z])/ /g;

See also perldoc perlre.


问:
Vue.js pagination component
I am trying to make a general use Vue.JS component that performs pagination through AJAX calls. I want the data that the component uses (i.e. list of items) to be encapsulated by the component and that only the AJAX URL be passed to the component through Vue.JS Props. I am using SLOTs to populate the component template including the iteration part..
I think this means that parent (the caller) needs to have access to the binded variables during the iteration, because the caller is looping through the items.. I cant put the looping part in the component because the component becomes specific to one type of list, and it wont be a general one anymore.

How can I make the component iterate through the items even when SLOTs are being used.. or at least allow the parent to iterate through the items but pass the data to the component so that it can fetch the next pages and update the parent's data.

To illustrate better see the following code:

```<code>// my component
Vue.component('pagination', {
  template: '#pagination-component',
  props:  {
   // the URL for ajax calls is passed from parent to component
   source: {
      type: String,
      required: true
    }
 },
  data: function () {
    // access the data being paginated somehow
    return data;
  },

  created:
     function () {
    console.log("component loaded...");
    this.getNextPage();
    },
  methods:
  {
    getNextPage: function () {
          console.log("getNextPage called...");
          // call ajax method and populate the binded data
    },
    getPrevPage: function () {
          console.log("getPrevPage called...");
          // call ajax method and populate the binded data
    }
  }
})

console.log("javascript loaded...");

var app = new Vue({
     el: '#wrapper',
data: {
}
})
</code>```

my component layout is:

```<code><script type="text/x-template" id="pagination-component">

<div class="pagination-wrapper">

<slot name="header"></slot>

<slot name="table">default text: Please define the table in parent!</slot>

<div class="well">
    <a href="#" @click="getPrevPage">Previous Page</a> |
   <a href="#" @click="getNextPage">Next Page</a>
</div>

<slot name="footer"></slot>

</div>
</script>
</code>```

and my main page (parent) using the component is:

```<code><div class="table-wrapper" slot="table">

    <table class='table'>

         <tr>
             <th>Username</th>
             <th>First name</th>
             <th>Last name</th>
             <th>E-mail</th>
        </tr>

        <tr v-for="user in users">
          <td>
          <a :href="user.id">{{user.username}}</a>
          </td>
          <td>{{user.firstname}}</td>
          <td>{{user.lastname}}</td>
          <td>{{user.email}}</td>
        </tr>

    </table>

</div>
</code>```

答:
I realise it's tempting to have a paginator deal with fetching data, but I think the best approach is to have the paginator be completely decoupled from the data it is paginating.

So, the parent should pass through the maximum number of pages and the paginator component should emit the page number back to the parent which should then deal with obtaining the data based on that page number. This means that you can develop different pagination components that utilise the paginator without having to create one complex component.

I did actually write something a few months back that takes this approach which you are welcome to look at on my GitHub Page, although this particular component isn't stable, but it should give you an idea of what I mean.

Title: Vue.js pagination component

Body:
I am trying to make a general use Vue.JS component that performs pagination through AJAX calls. I want the data that the component uses (i.e. list of items) to be encapsulated by the component and that only the AJAX URL be passed to the component through Vue.JS Props. I am using SLOTs to populate the component template including the iteration part..
I think this means that parent (the caller) needs to have access to the binded variables during the iteration, because the caller is looping through the items.. I cant put the looping part in the component because the component becomes specific to one type of list, and it wont be a general one anymore.

How can I make the component iterate through the items even when SLOTs are being used.. or at least allow the parent to iterate through the items but pass the data to the component so that it can fetch the next pages and update the parent's data.

To illustrate better see the following code:

// my component
Vue.component('pagination', {
  template: '#pagination-component',
  props:  {
   // the URL for ajax calls is passed from parent to component
   source: {
      type: String,
      required: true
    }
 },
  data: function () {
    // access the data being paginated somehow
    return data;
  },

  created:
     function () {
    console.log("component loaded...");
    this.getNextPage();
    },
  methods:
  {
    getNextPage: function () {
          console.log("getNextPage called...");
          // call ajax method and populate the binded data
    },
    getPrevPage: function () {
          console.log("getPrevPage called...");
          // call ajax method and populate the binded data
    }
  }
})

console.log("javascript loaded...");

var app = new Vue({
     el: '#wrapper',
data: {
}
})

my component layout is:

and my main page (parent) using the component is:

             Username
             First name
             Last name
             E-mail

          {{user.username}}

          {{user.firstname}}
          {{user.lastname}}
          {{user.email}}


问:
SKPhysicsBody and [SKNode setScale:]
In my current project using SpriteKit, I have a bunch of sprites that need to be scaled up and down independently at various times. The problem is that when I scale the node, the physics body doesn't scale with it so it screws up the physics. Here's a small example I put together for the purpose of this question:

```<code>CGSize objectSize = CGSizeMake(100, 100);
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:CGRectMake(0, 0, self.size.width, self.size.height)];

SKSpriteNode *n1 = [SKSpriteNode spriteNodeWithColor:[UIColor blueColor] size:objectSize];
n1.position = CGPointMake(self.size.width/2, 2*self.size.height/3);
n1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:objectSize];
n1.physicsBody.affectedByGravity = YES;
[self addChild:n1];

SKSpriteNode *n2 = [SKSpriteNode spriteNodeWithColor:[UIColor redColor] size:objectSize];
n2.position = CGPointMake(self.size.width/2, self.size.height/3);
n2.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:objectSize];
n2.physicsBody.affectedByGravity = YES;
[self addChild:n2];

[n1 setScale:0.5];
</code>```

Notice how the blue sprite (scaled down) sits on top of the red one but you can tell its physics body still has the dimension I told it, and it didn't scale.

So obviously, scaling down the node doesn't scale down the physicsBody. So my question is if I have to manually do it, how do I go about it?

I tried swapping the body with one of the right size when scaling, but then things get really convoluted if the old body had joints, etc... It'd be a lot simpler if I could just scale the existing body somehow.

答:
I had this same problem, all I did was define my physics body in my update current time function and it would scale with it.

For you it would be something like this:

```<code>override func sceneDidLoad() {

SKSpriteNode *n1 = [SKSpriteNode spriteNodeWithColor:[UIColor blueColor] size:objectSize];
n1.position = CGPointMake(self.size.width/2, 2*self.size.height/3);

}
override func update(_ currentTime: TimeInterval) {

n1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:objectSize];
n1.physicsBody.affectedByGravity = YES;

}
</code>```

The only problem is that you have to redefine your physics properties every time in updateCurrentTime. You can make some of these properties like it's restitution equal a variable so you can change its properties by changing the variable elsewhere. Redefining it anywhere else only works until the next frame is called.

Title: SKPhysicsBody and [SKNode setScale:]

Body:
In my current project using SpriteKit, I have a bunch of sprites that need to be scaled up and down independently at various times. The problem is that when I scale the node, the physics body doesn't scale with it so it screws up the physics. Here's a small example I put together for the purpose of this question:

CGSize objectSize = CGSizeMake(100, 100);
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:CGRectMake(0, 0, self.size.width, self.size.height)];

SKSpriteNode *n1 = [SKSpriteNode spriteNodeWithColor:[UIColor blueColor] size:objectSize];
n1.position = CGPointMake(self.size.width/2, 2*self.size.height/3);
n1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:objectSize];
n1.physicsBody.affectedByGravity = YES;
[self addChild:n1];

SKSpriteNode *n2 = [SKSpriteNode spriteNodeWithColor:[UIColor redColor] size:objectSize];
n2.position = CGPointMake(self.size.width/2, self.size.height/3);
n2.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:objectSize];
n2.physicsBody.affectedByGravity = YES;
[self addChild:n2];

[n1 setScale:0.5];

Notice how the blue sprite (scaled down) sits on top of the red one but you can tell its physics body still has the dimension I told it, and it didn't scale.

So obviously, scaling down the node doesn't scale down the physicsBody. So my question is if I have to manually do it, how do I go about it?

I tried swapping the body with one of the right size when scaling, but then things get really convoluted if the old body had joints, etc... It'd be a lot simpler if I could just scale the existing body somehow.

Body:
I had this same problem, all I did was define my physics body in my update current time function and it would scale with it.

For you it would be something like this:

override func sceneDidLoad() {

SKSpriteNode *n1 = [SKSpriteNode spriteNodeWithColor:[UIColor blueColor] size:objectSize];
n1.position = CGPointMake(self.size.width/2, 2*self.size.height/3);

}
override func update(_ currentTime: TimeInterval) {

n1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:objectSize];
n1.physicsBody.affectedByGravity = YES;

}

The only problem is that you have to redefine your physics properties every time in updateCurrentTime. You can make some of these properties like it's restitution equal a variable so you can change its properties by changing the variable elsewhere. Redefining it anywhere else only works until the next frame is called.


答:
Using Ramda you can first zip the two lists, and then reduce it and use destructuring to extract the array elements and pass them as arguments to the callback:

const reduceTwo = (callback, initialValue, arr1, arr2) =>
  R.reduce((acc, [x, y]) => callback(acc, x, y), initialValue, R.zip(arr1, arr2));

const arr1 = [2, 3, 4, 5, 6];
const arr2 = [5, 10, 4, 9, 5];
console.log(reduceTwo((acc, x, y) => acc + x * y, 0, arr1, arr2));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script></code>```

Title: Can I use array.prototype.reduce() to process two arrays at once?

Body:
I have two arrays of same length and I would like to somehow process them both at once with the reduce method. Something like:

var arr1 = [2, 3, 4, 5, 6];
var arr2 = [5, 10, 4, 9, 5];
var productSum = arr1.reduce(function(sumOfProducts, item, secondArrayItem) {
    /* here I would like to multiply item from arr1 by the item from arr2 at the same index */
    return sumOfProducts + item * secondArrayItem;
}, 0, arr2)
console.log(productSum);  // 131

An option would of course be to access the correct item from arr2 using currentIndex, but that solution is ugly as I am accessing a variable outside of the scope of the function.

My specific use case is that I have an array with resources like var resources = [2, 5, 4, 6, 2] and I want to check if each item is higher than corresponding resource cost in another array like var cost = [3, 1, 0, 0, 1].

Is there some nice solution to this using the reduce() function?

Body:
Using Ramda you can first zip the two lists, and then reduce it and use destructuring to extract the array elements and pass them as arguments to the callback:

const reduceTwo = (callback, initialValue, arr1, arr2) =>
  R.reduce((acc, [x, y]) => callback(acc, x, y), initialValue, R.zip(arr1, arr2));

const arr1 = [2, 3, 4, 5, 6];
const arr2 = [5, 10, 4, 9, 5];
console.log(reduceTwo((acc, x, y) => acc + x * y, 0, arr1, arr2));

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>


问:
"Wrap with try...catch" in IntelliJ?
Can I select a block of code and have IntelliJ wrap it with a "try...catch" ?

Is there a keyboard shortcut?

答:
If you only need to wrap one line in a try-catch, you can use the Postfix Completion, available in IDEA 13.1 EAP and above.

The idea is that all you need to do is append .try to your line and the completion will be able to wrap it in a try-catch.

For example:

```<code>System.out.println("Hello World!");.try
</code>```

results in

```<code>try {
    System.out.println("Hello World!");
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

Title: "Wrap with try...catch" in IntelliJ?

Body:
If you only need to wrap one line in a try-catch, you can use the Postfix Completion, available in IDEA 13.1 EAP and above.

The idea is that all you need to do is append .try to your line and the completion will be able to wrap it in a try-catch.

For example:

System.out.println("Hello World!");.try

results in

try {
    System.out.println("Hello World!");
} catch (Exception e) {
    e.printStackTrace();
}


问:
Determining if a string is an Isogram
The Task:

Write a program that checks if a word supplied as the argument is an Isogram. An Isogram is a word in which no letter occurs more than once.

Create a method called is_isogram that takes one argument, a word to test if it's an isogram. This method should return a tuple of the word and a boolean indicating whether it is an isogram.

If the argument supplied is an empty string, return the argument and False: (argument, False). If the argument supplied is not a string, raise a TypeError with the message 'Argument should be a string'.

Example:

```<code>is_isogram("abolishment")
</code>```

Expected result:

```<code>("abolishment", True)
</code>```

The Visible test

```<code>from unittest import TestCase

class IsogramTestCases(TestCase):
  def test_checks_for_isograms(self):
    word = 'abolishment'
    self.assertEqual(
      is_isogram(word),
      (word, True),
      msg="Isogram word, '{}' not detected correctly".format(word)
    )

  def test_returns_false_for_nonisograms(self):
    word = 'alphabet'
    self.assertEqual(
      is_isogram(word),
      (word, False),
      msg="Non isogram word, '{}' falsely detected".format(word)
    )

  def test_it_only_accepts_strings(self):
    with self.assertRaises(TypeError) as context:
      is_isogram(2)
      self.assertEqual(
        'Argument should be a string',
        context.exception.message,
        'String inputs allowed only'
      )
</code>```

My Solution:

```<code>def is_isogram(word):
    if type(word) != str:
        raise TypeError('Argument should be a string')

    elif word == "":
      return (word, False)
    else:
        word = word.lower()
        for char in word:
            if word.count(char) > 1:
                return (word, False)
            else:
                return (word, True)
</code>```

But it the function refuses to pass some hidden test: What is wrong with my solution? Is there another elegant way of writing this function?

答:
i solved it here:

def is_isogram(word):

```<code>for letter in word:
    if word.count(letter) > 1:
        return False
else:
    return True
</code>```

print is_isogram("Hello")

Title: Determining if a string is an Isogram

Body:
The Task:

Write a program that checks if a word supplied as the argument is an Isogram. An Isogram is a word in which no letter occurs more than once.

Create a method called is_isogram that takes one argument, a word to test if it's an isogram. This method should return a tuple of the word and a boolean indicating whether it is an isogram.

If the argument supplied is an empty string, return the argument and False: (argument, False). If the argument supplied is not a string, raise a TypeError with the message 'Argument should be a string'.

Example:

is_isogram("abolishment")

Expected result:

("abolishment", True)

The Visible test

from unittest import TestCase

class IsogramTestCases(TestCase):
  def test_checks_for_isograms(self):
    word = 'abolishment'
    self.assertEqual(
      is_isogram(word),
      (word, True),
      msg="Isogram word, '{}' not detected correctly".format(word)
    )

  def test_returns_false_for_nonisograms(self):
    word = 'alphabet'
    self.assertEqual(
      is_isogram(word),
      (word, False),
      msg="Non isogram word, '{}' falsely detected".format(word)
    )

  def test_it_only_accepts_strings(self):
    with self.assertRaises(TypeError) as context:
      is_isogram(2)
      self.assertEqual(
        'Argument should be a string',
        context.exception.message,
        'String inputs allowed only'
      )

My Solution:

def is_isogram(word):
    if type(word) != str:
        raise TypeError('Argument should be a string')

    elif word == "":
      return (word, False)
    else:
        word = word.lower()
        for char in word:
            if word.count(char) > 1:
                return (word, False)
            else:
                return (word, True)

But it the function refuses to pass some hidden test: What is wrong with my solution? Is there another elegant way of writing this function?

Body:
i solved it here:

def is_isogram(word):

for letter in word:
    if word.count(letter) > 1:
        return False
else:
    return True

print is_isogram("Hello")


问:
Save CURL result in a variable PHP
I'm new to the whole CURL library in PHP and managed to sucesfully get post data from a website using the following code:

```<code> <?php
    $postcode="6942GJ";
    $huisnummer="8";
    $marktsegment="27";
    $aansluiting="-";
    $url="http://notimportantforstackoverflow.com";
    $postdata = "postcode=".$postcode."&huisnummer=".$huisnummer."&marktsegment=".$marktsegment."&aansluiting=".$aansluiting;
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $result = curl_exec ($ch);
    curl_close($ch);
    ?>
</code>```

Wich returns the following table:

    Ean code aansluiting

    Straatnaam

    Huisnr.

    Huisnr. toev.

    Woonplaats

    Postcode

    Bijzondere aansluiting

    Markt segment

    Naam Netbeheerder

    Ean Netbeheerder

    871687140007253845

    Pittelderstraat

    8

    DIDAM

    6942GJ

    NEE

         GAS

    Liander NB

    8716871000002

```

I want to work with the resulting data specifically the resulting string "Liander NB" I want to make a var out of this result like so $beheerder ="Liander NB"; But I don't know how to make a variable out of the resulting CURL data.

答:
Use the CURLOPT_RETURNTRANSFER option to make curl_exec() return the response.

```<code>curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$result = curl_exec ($ch);
</code>```

Then you can use DOMDocument to parse the HTML in the response, and its methods to find the information you want in the HTML.

Title: Save CURL result in a variable PHP

Body:
I'm new to the whole CURL library in PHP and managed to sucesfully get post data from a website using the following code:

 <?php
    $postcode="6942GJ";
    $huisnummer="8";
    $marktsegment="27";
    $aansluiting="-";
    $url="http://notimportantforstackoverflow.com";
    $postdata = "postcode=".$postcode."&huisnummer=".$huisnummer."&marktsegment=".$marktsegment."&aansluiting=".$aansluiting;
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $result = curl_exec ($ch);
    curl_close($ch);
    ?>

Wich returns the following table:

    Ean code aansluiting

    Straatnaam

    Huisnr.

    Huisnr. toev.

    Woonplaats

    Postcode

    Bijzondere aansluiting

    Markt segment

    Naam Netbeheerder

    Ean Netbeheerder

    871687140007253845

    Pittelderstraat

    8

    DIDAM

    6942GJ

    NEE

         GAS

    Liander NB

    8716871000002

I want to work with the resulting data specifically the resulting string "Liander NB" I want to make a var out of this result like so $beheerder ="Liander NB"; But I don't know how to make a variable out of the resulting CURL data.

Body:
Use the CURLOPT_RETURNTRANSFER option to make curl_exec() return the response.

curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$result = curl_exec ($ch);

Then you can use DOMDocument to parse the HTML in the response, and its methods to find the information you want in the HTML.


问:
FacebookCallback.onCancel is getting called when trying to login using facebook sdk
I have an Android app and I am trying to use Facebook's SDK (version 4.1.0) to get a token and log in. Here is my code:

```<code>public class LoginActivity extends Activity {
    private CallbackManager callbackManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        FacebookSdk.sdkInitialize(getApplicationContext());

        callbackManager = CallbackManager.Factory.create();
        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                AccessToken accessToken = loginResult.getAccessToken();
                Log.v(TAG, "Facebook login was successful");
                String authToken = accessToken.getToken();
                // User authToken here:
            }

            @Override
            public void onCancel() {
                Log.v(TAG, "Facebook login was canceled");
            }

            @Override
            public void onError(FacebookException e) {
                Log.e(TAG, "Facebook login failed: " + e.getMessage());
            }
        });

        Button facebook_button = (Button) findViewById(R.id.fbButton);

        facebook_button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile"));
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
}
</code>```

The code switched to the Facebook app and back and OnActivityResult() is called. However, every time the callback method that is called is onCancel(). Note that I am not using the LoginButton provided by Facebook, and I have my own button (although I tried that approach and the result was the same). I double and triple checked my app ID and the keyhash generated by the app and they look correct too. So, I don't know what else may be wrong. Any help at this point is greatly appreciated.

答:
If anyone comes across this in the future, this can also be caused by the Facebook native app installed on the device blocking login due to reason X.

In my case, this was being thrown every single time I attempted login. I finally switched over to the native Facebook app and as it opened, it required authentication and had me log in again due to some 'suspicious activity' (I think I changed my number recently).

If you are doing everything that is listed above and users are still complaining about it (and they have the app installed, you can use the code at the bottom to see if the Facebook app in installed:) you may wish to include a dialog that asks them to check the Facebook app and make sure they are still logged in, which would then prompt them to fix any errors before tabbing back into your application.

```<code>//Code to check if Facebook app is installed:
public static boolean doesUserHaveFacebookAppInstalled(Context context){
    try{
        context.getPackageManager().getApplicationInfo("com.facebook.katana", 0 );
        return true;
    } catch( PackageManager.NameNotFoundException e ){
        return false;
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an Android app and I am trying to use Facebook's SDK (version 4.1.0) to get a token and log in. Here is my code:

public class LoginActivity extends Activity {
    private CallbackManager callbackManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        FacebookSdk.sdkInitialize(getApplicationContext());

        callbackManager = CallbackManager.Factory.create();
        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                AccessToken accessToken = loginResult.getAccessToken();
                Log.v(TAG, "Facebook login was successful");
                String authToken = accessToken.getToken();
                // User authToken here:
            }

            @Override
            public void onCancel() {
                Log.v(TAG, "Facebook login was canceled");
            }

            @Override
            public void onError(FacebookException e) {
                Log.e(TAG, "Facebook login failed: " + e.getMessage());
            }
        });

        Button facebook_button = (Button) findViewById(R.id.fbButton);

        facebook_button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile"));
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
}

The code switched to the Facebook app and back and OnActivityResult() is called. However, every time the callback method that is called is onCancel(). Note that I am not using the LoginButton provided by Facebook, and I have my own button (although I tried that approach and the result was the same). I double and triple checked my app ID and the keyhash generated by the app and they look correct too. So, I don't know what else may be wrong. Any help at this point is greatly appreciated.

Body:
If anyone comes across this in the future, this can also be caused by the Facebook native app installed on the device blocking login due to reason X.

In my case, this was being thrown every single time I attempted login. I finally switched over to the native Facebook app and as it opened, it required authentication and had me log in again due to some 'suspicious activity' (I think I changed my number recently).

If you are doing everything that is listed above and users are still complaining about it (and they have the app installed, you can use the code at the bottom to see if the Facebook app in installed:) you may wish to include a dialog that asks them to check the Facebook app and make sure they are still logged in, which would then prompt them to fix any errors before tabbing back into your application.

//Code to check if Facebook app is installed:
public static boolean doesUserHaveFacebookAppInstalled(Context context){
    try{
        context.getPackageManager().getApplicationInfo("com.facebook.katana", 0 );
        return true;
    } catch( PackageManager.NameNotFoundException e ){
        return false;
    }
}


问:
invalid_client in google oauth2
I try to make a web page for youtube video upload, therefore I try to get the client id from google api console, and in the api console it shows something like this:

```<code>Client ID: 533832195920.apps.googleusercontent.com
Redirect URIs: http://bobyouku.ap01.aws.af.cm/testyoutube.php
https://developers.google.com/oauthplayground
</code>```

However when I try to test my account using the following URL:

https://accounts.google.com/o/oauth2/auth?client_id=533832195920.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Fbobyouku.ap01.aws.af.cm%2Ftestyoutube.php&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube&response_type=code&access_type=offline

It gives out the result of invalid_client. Even when I try it on oauth2 playground, same fail occurs

So anyone knows what's happen?

答: invalid_client can also simply means that your client ID and client secret are wrong when you create your Oauth2 object.</p>

Title: invalid_client in google oauth2

Body:
I try to make a web page for youtube video upload, therefore I try to get the client id from google api console, and in the api console it shows something like this:

Client ID: 533832195920.apps.googleusercontent.com
Redirect URIs: http://bobyouku.ap01.aws.af.cm/testyoutube.php
https://developers.google.com/oauthplayground

However when I try to test my account using the following URL:

https://accounts.google.com/o/oauth2/auth?client_id=533832195920.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Fbobyouku.ap01.aws.af.cm%2Ftestyoutube.php&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube&response_type=code&access_type=offline

It gives out the result of invalid_client. Even when I try it on oauth2 playground, same fail occurs

So anyone knows what's happen?


问:
Null pointer exception when accessing Google Calendar
I am writing a android app that need to insert event to Google Calendar. I run my app in my two android phone and thay are all success. However, some crash reports from others are received. They have null pointer exception in the last line of the following code.

(BTW, I have already handled two different URIs of google calendar by following Is there a way to access the calendar's entries without using gdata-java-client?)

Entire source code file: http://gonow.no-ip.org/hkpl/GoogleCalendar.java

I call function addEvent in another class by this

```<code>GoogleCalendar.addEvent(getContentResolver(),EVENT_TITLE,CONTENT);
</code>```

Extracted:

```<code>ContentValues event = new ContentValues();
event.put("title", title);
event.put("description", description);
event.put("calendar_id",calId);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, 1);
long start = cal.getTime().getTime();
event.put("dtstart", start);
cal.add(Calendar.DAY_OF_MONTH, 1);
long end = cal.getTime().getTime();
event.put("dtend", end);
event.put("hasAlarm",1);
event.put("allDay", 1);
Uri newEvent = cr.insert(Uri.parse(calanderEventURL), event); <-- exception here
</code>```

Crash report here

java.lang.RuntimeException: An error occured while executing
  doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:200) at
  java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
  at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
  at java.util.concurrent.FutureTask.run(FutureTask.java:138) at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
  at java.lang.Thread.run(Thread.java:1019) Caused by:
  java.lang.NullPointerException at
  android.os.Parcel.readException(Parcel.java:1328) at
  android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:160)
  at
  android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:114)
  at
  android.content.ContentProviderProxy.insert(ContentProviderNative.java:408)
  at android.content.ContentResolver.insert(ContentResolver.java:604) at
  ming.hkpl.GoogleCalendar.addEvent(GoogleCalendar.java:93)

答:
In general, use the following process:

Find the line number of the failure in the bottom of the stack trace with the company namespace (ming.hkpl.GoogleCalendar.addEvent)

Go to the line number of the file mentioned in the stack trace in an IDE or text editor

Add a breakpoint

Compile the code

Run jdb
OR

Add a print statement to the previous line, printing the variable referenced in the line that throws an error. For example:

```<code>System.out.println("Hi");
System.out.println(driver);
</code>```

Rebuild the code

References

Debugging Exceptions within your App | CodePath Android Cliffnotes

Embedded print Statements != Debugging | Dr Dobb's

How do you reproduce bugs that occur sporadically?

How do you fix a bug you can't replicate?

Effective Methods for Debugging Concurrent Software (pdf)

jdb

Debugging Java Programs using JDB | PACKT Books

Body:
I am writing a android app that need to insert event to Google Calendar. I run my app in my two android phone and thay are all success. However, some crash reports from others are received. They have null pointer exception in the last line of the following code.

(BTW, I have already handled two different URIs of google calendar by following Is there a way to access the calendar's entries without using gdata-java-client?)

Entire source code file: http://gonow.no-ip.org/hkpl/GoogleCalendar.java

I call function addEvent in another class by this

GoogleCalendar.addEvent(getContentResolver(),EVENT_TITLE,CONTENT);

Extracted:

ContentValues event = new ContentValues();
event.put("title", title);
event.put("description", description);
event.put("calendar_id",calId);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, 1);
long start = cal.getTime().getTime();
event.put("dtstart", start);
cal.add(Calendar.DAY_OF_MONTH, 1);
long end = cal.getTime().getTime();
event.put("dtend", end);
event.put("hasAlarm",1);
event.put("allDay", 1);
Uri newEvent = cr.insert(Uri.parse(calanderEventURL), event); <-- exception here

Crash report here

java.lang.RuntimeException: An error occured while executing
  doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:200) at
  java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
  at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
  at java.util.concurrent.FutureTask.run(FutureTask.java:138) at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
  at java.lang.Thread.run(Thread.java:1019) Caused by:
  java.lang.NullPointerException at
  android.os.Parcel.readException(Parcel.java:1328) at
  android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:160)
  at
  android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:114)
  at
  android.content.ContentProviderProxy.insert(ContentProviderNative.java:408)
  at android.content.ContentResolver.insert(ContentResolver.java:604) at
  ming.hkpl.GoogleCalendar.addEvent(GoogleCalendar.java:93)

Body:
In general, use the following process:

Find the line number of the failure in the bottom of the stack trace with the company namespace (ming.hkpl.GoogleCalendar.addEvent)

Go to the line number of the file mentioned in the stack trace in an IDE or text editor

Add a breakpoint

Compile the code

Run jdb
OR

Add a print statement to the previous line, printing the variable referenced in the line that throws an error. For example:

System.out.println("Hi");
System.out.println(driver);

Rebuild the code

References

Debugging Exceptions within your App | CodePath Android Cliffnotes

Embedded print Statements != Debugging | Dr Dobb's

How do you reproduce bugs that occur sporadically?

How do you fix a bug you can't replicate?

Effective Methods for Debugging Concurrent Software (pdf)

jdb

Debugging Java Programs using JDB | PACKT Books


问:
Difference between [Object, Object] and Array(2)
I am working in AngularJS and trying to send data to my backend.

I noticed that when the variable in my service has this structure test = [Object, Object] it gets passed into a List<String> in my ASP.NET backend, but i have trouble passing test = Array(2) into my backend.

I see the formats when i am debugging and set a breakpoint on the variable.

Is there a difference between the two? Thanks

答:
The first case:

```<code>var x = { foo: "bar", qux: 123 };
var y = { baz: "123", yeen: { arr: [1,2,3] };

var test = [ x, y ]; // [Object,Object]
</code>```

For the second case, refer to MDN's documentation for Array():

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

```<code>new Array(arrayLength)
</code>```

If the only argument passed to the Array constructor is an integer between 0 and 2^32 - 1 (inclusive), this returns a new JavaScript array with its length property set to that number

So your second case code presumably is:

```<code>var test = Array(2);
</code>```

...this actually evaluates to [undefined,undefined]), however .NET (thus ASP.NET) does not have a concept of "undefined" (compared to null), so this value is not serializable to JSON (as JSON does not allow undefined values) - so this explains why it's failing.

If an "empty" array element is meaningful in your application you should use explicit null values instead - ideally using an array-literal like so:

```<code>var ret = [ null, null ];
</code>```

Or if the number of elements is variable:

```<code>var ret = Array( 123 ); // This creates a 123-sized array, where every element is undefined. This cannot be serialized to JSON
ret.fill( null );       // This explicitly sets every element to a null value. The array can now be serialized to JSON.
</code>```

Body:
The first case:

var x = { foo: "bar", qux: 123 };
var y = { baz: "123", yeen: { arr: [1,2,3] };

var test = [ x, y ]; // [Object,Object]

For the second case, refer to MDN's documentation for Array():

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

new Array(arrayLength)

If the only argument passed to the Array constructor is an integer between 0 and 2^32 - 1 (inclusive), this returns a new JavaScript array with its length property set to that number

So your second case code presumably is:

var test = Array(2);

...this actually evaluates to [undefined,undefined]), however .NET (thus ASP.NET) does not have a concept of "undefined" (compared to null), so this value is not serializable to JSON (as JSON does not allow undefined values) - so this explains why it's failing.

If an "empty" array element is meaningful in your application you should use explicit null values instead - ideally using an array-literal like so:

var ret = [ null, null ];

Or if the number of elements is variable:

var ret = Array( 123 ); // This creates a 123-sized array, where every element is undefined. This cannot be serialized to JSON
ret.fill( null );       // This explicitly sets every element to a null value. The array can now be serialized to JSON.


问:
MIT OCW Python Course in Highest Quality
I am currently learning Python from MIT OCW courses ? Anyone who have used it might know this...
where can I get the highest quality video to download from offline usage ? </p>

答: A question was posted earlier asking for a link to Handouts. It was answered here</p>


问:
Get diagonal elements from tf.matmul(tf.transpose(A), A) in Tensorflow
I have a matrix A with several columns, and I need to compute the self dot products, i.e. tf.matmul(A[:,i]), A[:,i], transpose_a=True) where i indexes columns of A. One way is to just compute tf.matmul(A,A, transpose_a=True) and extract the diagonal, but this involves a lot of superfluous multiplication (all non-diagonal results are discarded, and the non-diagonal results are most of the results for any matrix larger than 2 x 2). Another way is to do something like

```<code>out = []
for i in range(tf.shape(A)[1]):
    out.append(tf.matmul((A[:,i],A[:,i],transpose_a=True))
</code>```

and then collect out into a tf.Tensor. But it seems like this is a fairly common computation, so I would expect a function to exist for it (i.e. computing squared norms of weight vectors).

答:
Just a little bit of linear algebra and you have your solution:

Which means that you need to do: tf.reduce_sum(tf.square(A), axis=0)

Body:
I have a matrix A with several columns, and I need to compute the self dot products, i.e. tf.matmul(A[:,i]), A[:,i], transpose_a=True) where i indexes columns of A. One way is to just compute tf.matmul(A,A, transpose_a=True) and extract the diagonal, but this involves a lot of superfluous multiplication (all non-diagonal results are discarded, and the non-diagonal results are most of the results for any matrix larger than 2 x 2). Another way is to do something like

out = []
for i in range(tf.shape(A)[1]):
    out.append(tf.matmul((A[:,i],A[:,i],transpose_a=True))

and then collect out into a tf.Tensor. But it seems like this is a fairly common computation, so I would expect a function to exist for it (i.e. computing squared norms of weight vectors).


问:
How to prevent IE from whole-page-zooming when someone "pinches" on touch screen?
I have an element with a line graph in it that I want to be able to handle pinch zooms, so the user can zoom in or out on a certain part of the graph.  This works great in every browser except IE11, where instead of zooming the element, it zooms the entire page.

Is there an obvious way to prevent this kind of functionality, so IE allows for pinch-zooming on specific elements?  Or maybe there's some way to capture the pinch event, e.preventDefault(), and maybe zoom the graph manually?

I have asked a few other people to try to reproduce the issue, and it seems like it's not a problem on Windows 10... I'm on Windows 7.  Could this really be platform dependent?  But even if it is, maybe intercepting the events is a good approach?  Any suggestions would be greatly appreciated.

Here's an example of a chart where I am having this problem:
http://demos.wijmo.com/5/Angular/FlexChartZoom/FlexChartZoom/

答: According to the official documentation, programmatic control of touch and gesture recognition requires Windows 8 or later.</p>


问:
How to get a string from a string, starting and ending with a specific string
I've got a string containing similar text like below

```<code>Name: John\n Surname: Smith\n Address: XXX\n
</code>```

It can appear in different order.

I want to get the name value, the surname value and the adress value.

So the question is: how to get a string starting from string "Name: " and ending before "\n", so I get "John" and the code is very readable?

I tried to use the Substring function but it required modyfing the string so I get the correct index of the "\n" part. And I would prefer not to modify the original string so it's more readable.

答:
You can convert this string to dictionary (i.e. set of key-value pairs). First split initial string by newline character into array of strings. Then each string from this array split by colon in two parts - key and value:

```<code>var input = "Name: John\n Surname: Smith\n Address: XXX\n";
var dictionary = input.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)
                      .Select(s => s.Split(':'))
                      .ToDictionary(p => p[0].Trim(), p => p[1].Trim());
</code>```

And then read values by their keys:

```<code>var name = dictionary["Name"]; // gives you John
</code>```

Note: if address or some other field is allowed to contain colon, you can use string.Join option from comment by @Joel Coehoorn when selecting value of dictionary.

Or you can use regex instead of splitting and joining strings. Just find pattern matches in your input:

```<code>var input = "Name: John\n Surname: Sm:ith\n Address: XX:X\n";
var dictionary = Regex.Matches(input, @"\s*([^:]+): ([^\n]+)\n").Cast<Match>()
                      .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);
var address = dictionary["Address"]; // XX:X
</code>```

Body:
I've got a string containing similar text like below

Name: John\n Surname: Smith\n Address: XXX\n

It can appear in different order.

I want to get the name value, the surname value and the adress value.

So the question is: how to get a string starting from string "Name: " and ending before "\n", so I get "John" and the code is very readable?

I tried to use the Substring function but it required modyfing the string so I get the correct index of the "\n" part. And I would prefer not to modify the original string so it's more readable.

Body:
You can convert this string to dictionary (i.e. set of key-value pairs). First split initial string by newline character into array of strings. Then each string from this array split by colon in two parts - key and value:

var input = "Name: John\n Surname: Smith\n Address: XXX\n";
var dictionary = input.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)
                      .Select(s => s.Split(':'))
                      .ToDictionary(p => p[0].Trim(), p => p[1].Trim());

And then read values by their keys:

var name = dictionary["Name"]; // gives you John

Note: if address or some other field is allowed to contain colon, you can use string.Join option from comment by @Joel Coehoorn when selecting value of dictionary.

Or you can use regex instead of splitting and joining strings. Just find pattern matches in your input:

var input = "Name: John\n Surname: Sm:ith\n Address: XX:X\n";
var dictionary = Regex.Matches(input, @"\s*([^:]+): ([^\n]+)\n").Cast<Match>()
                      .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);
var address = dictionary["Address"]; // XX:X


问:
Segmentation fault in Fortran while constructing graph using adjacency lists
I am creating graph using the adjacency list method. Each node is represented as a node which points to other nodes connected to it. The following is my  code

```<code> program main
 use graphs
 implicit none
 type(node),pointer :: start
 type(node), dimension(:), pointer :: grp
 integer :: n, ios=0, a,b, i

 open(1, file='test6.txt', status='OLD', action='READ')
 read(1,*,iostat=ios) n
 allocate(start)
 allocate(grp(n))
 do, i=1,n
   grp(i)%val=i
 enddo

 do while(ios==0)
  read(1,*, iostat=ios)a,b
  if(ios.NE.0)then
     exit
  endif
  start => grp(a)
  call add(start, b)
  start => grp(b)
  call add(start, a)
 end do
end program main
</code>```

The module graph is as follows

```<code>module graphs
 type node
  integer :: val
  type(node), pointer :: next
 end type node

contains

subroutine add(strt, nxn)
 implicit none
 type(node), pointer :: strt, new_node, lst
 integer :: nxn
 allocate(new_node)
 allocate(lst)
 lst => strt
 new_node%val = nxn
 new_node%next => NULL()
 do while(associated(lst%next))
   lst => lst%next
 enddo
 lst%next => new_node
end subroutine add
end module graphs
</code>```

File test6.txt is as follows

```<code>43
1 2
1 10
2 3
2 11
3 4
4 5
5 6
6 7
7 8
8 9
3 12
4 13
5 14
6 15
7 16
8 17
9 18
10 11
11 12
12 13
13 14
14 15
15 16
16 17
17 18
10 19
11 19
12 20
</code>```

I am getting the following error

```<code>Program received signal SIGSEGV: Segmentation fault - invalid memory
reference

Backtrace for this error:
#0  0x7f786df6bef7 in ???
#1  0x7f786df6b12d in ???
#2  0x7f786dbbc4af in ???
#3  0x401db0 in __graphs_MOD_add
at /home/nav/MS project/new/grph.f90:18
#4  0x400f48 in ???
#5  0x400f85 in ???
#6  0x7f786dba782f in ???
#7  0x400a18 in ???
#8  0xffffffffffffffff in ???
Segmentation fault (core dumped)
</code>```

The above program is running smooth for small graphs but not working for large graphs. I am not able to get what am I doing wrong? I am using the gfortran compiler.

答:
Nowhere in your code you set the starting %next pointer to null. So when you come to

```<code>do while(associated(lst%next))
</code>```

the address where lst%next points to is undefined. You are not allowed to ask whether it is associated, because the result associated() will return is also undefined. See also this classical resource for some more explanation http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html#5

The best cure is to the default initialization of pointer components

```<code> type node
  integer :: val
  type(node), pointer :: next =>  null()
 end type node
</code>```

Make it a habit to always set pointer components to null.

Body:
I am creating graph using the adjacency list method. Each node is represented as a node which points to other nodes connected to it. The following is my  code

 program main
 use graphs
 implicit none
 type(node),pointer :: start
 type(node), dimension(:), pointer :: grp
 integer :: n, ios=0, a,b, i

 open(1, file='test6.txt', status='OLD', action='READ')
 read(1,*,iostat=ios) n
 allocate(start)
 allocate(grp(n))
 do, i=1,n
   grp(i)%val=i
 enddo

 do while(ios==0)
  read(1,*, iostat=ios)a,b
  if(ios.NE.0)then
     exit
  endif
  start => grp(a)
  call add(start, b)
  start => grp(b)
  call add(start, a)
 end do
end program main

The module graph is as follows

module graphs
 type node
  integer :: val
  type(node), pointer :: next
 end type node

contains

subroutine add(strt, nxn)
 implicit none
 type(node), pointer :: strt, new_node, lst
 integer :: nxn
 allocate(new_node)
 allocate(lst)
 lst => strt
 new_node%val = nxn
 new_node%next => NULL()
 do while(associated(lst%next))
   lst => lst%next
 enddo
 lst%next => new_node
end subroutine add
end module graphs

File test6.txt is as follows

43
1 2
1 10
2 3
2 11
3 4
4 5
5 6
6 7
7 8
8 9
3 12
4 13
5 14
6 15
7 16
8 17
9 18
10 11
11 12
12 13
13 14
14 15
15 16
16 17
17 18
10 19
11 19
12 20

I am getting the following error

Program received signal SIGSEGV: Segmentation fault - invalid memory
reference

Backtrace for this error:
#0  0x7f786df6bef7 in ???
#1  0x7f786df6b12d in ???
#2  0x7f786dbbc4af in ???
#3  0x401db0 in __graphs_MOD_add
at /home/nav/MS project/new/grph.f90:18
#4  0x400f48 in ???
#5  0x400f85 in ???
#6  0x7f786dba782f in ???
#7  0x400a18 in ???
#8  0xffffffffffffffff in ???
Segmentation fault (core dumped)

The above program is running smooth for small graphs but not working for large graphs. I am not able to get what am I doing wrong? I am using the gfortran compiler.

Body:
Nowhere in your code you set the starting %next pointer to null. So when you come to

do while(associated(lst%next))

the address where lst%next points to is undefined. You are not allowed to ask whether it is associated, because the result associated() will return is also undefined. See also this classical resource for some more explanation http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html#5

The best cure is to the default initialization of pointer components

 type node
  integer :: val
  type(node), pointer :: next =>  null()
 end type node

Make it a habit to always set pointer components to null.