问:
RequestFactory & reverse with pk (must be called with either an object pk or a slug)
So I have this code:

```<code>request = self.factory.get(reverse('portal-edit-automation', args=(self.rule.id,)))
response = EditAutomation.as_view()(request)
</code>```

And if I set a pdb break point right before it and do:

```<code>(Pdb) reverse('portal-edit-automation', args=(self.rule.id,))
u'/portal/automations/edit/1/'
</code>```

I get the expected response.

So why am I getting this when running the test suite?

```<code>AttributeError: Generic detail view EditAutomation must be called with either an object pk or a slug.
</code>```

答:
You have to call the view with the request and the primary key, for example:</p>

```<code>EditAutomation.as_view()(request, pk=self.rule.id)
</code>```

Body:
So I have this code:

request = self.factory.get(reverse('portal-edit-automation', args=(self.rule.id,)))
response = EditAutomation.as_view()(request)

And if I set a pdb break point right before it and do:

(Pdb) reverse('portal-edit-automation', args=(self.rule.id,))
u'/portal/automations/edit/1/'

I get the expected response.

So why am I getting this when running the test suite?

AttributeError: Generic detail view EditAutomation must be called with either an object pk or a slug.

Body:
You have to call the view with the request and the primary key, for example:

EditAutomation.as_view()(request, pk=self.rule.id)


来源: stackexchange

问:
Adam optimizer in MatConvNet
I tried implementing Adam instead of default SGD optimizer by changing following code in cnn_train from:

```<code>opts.solver = [] ;  % Empty array means use the default SGD solver
[opts, varargin] = vl_argparse(opts, varargin) ;
if ~isempty(opts.solver)
  assert(isa(opts.solver, 'function_handle') && nargout(opts.solver) == 2,...
    'Invalid solver; expected a function handle with two outputs.') ;
  % Call without input arguments, to get default options
  opts.solverOpts = opts.solver() ;
end
</code>```

to:

```<code>opts.solver = 'adam';
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.solverOpts = opts.solver() ;
</code>```

However, I get an error:

```<code>Insufficient number of outputs from right hand side of equal sign to satisfy assignment.
Error in cnn_train>accumulateGradients (line 508)
params.solver(net.layers{l}.weights{j}, state.solverState{l}{j}, ...
</code>```

Have any of you tried changing from default compiler? What else should I change in cnn_train?

The code for Adam function:

```<code>function [w, state] = adam(w, state, grad, opts, lr)
%ADAM
%   Adam solver for use with CNN_TRAIN and CNN_TRAIN_DAG
%
%   See [Kingma et. al., 2014](http://arxiv.org/abs/1412.6980)
%    |  ([pdf](http://arxiv.org/pdf/1412.6980.pdf)).
%
%   If called without any input argument, returns the default options
%   structure. Otherwise provide all input arguments.
%
%   W is the vector/matrix/tensor of parameters. It can be single/double
%   precision and can be a `gpuArray`.
%
%   STATE is as defined below and so are supported OPTS.
%
%   GRAD is the gradient of the objective w.r.t W
%
%   LR is the learning rate, referred to as \alpha by Algorithm 1 in
%   [Kingma et. al., 2014].
%
%   Solver options: (opts.train.solverOpts)
%
%   `beta1`:: 0.9
%      Decay for 1st moment vector. See algorithm 1 in [Kingma et.al. 2014]
%
%   `beta2`:: 0.999
%      Decay for 2nd moment vector
%
%   `eps`:: 1e-8
%      Additive offset when dividing by state.v
%
%   The state is initialized as 0 (number) to start with. The first call to
%   this function will initialize it with the default state consisting of
%
%   `m`:: 0
%      First moment vector
%
%   `v`:: 0
%      Second moment vector
%
%   `t`:: 0
%      Global iteration number across epochs
%
%   This implementation borrowed from torch optim.adam

% Copyright (C) 2016 Aravindh Mahendran.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

if nargin == 0 % Returns the default solver options
  w = struct('beta1', 0.9, 'beta2', 0.999, 'eps', 1e-8) ;
  return ;
end

if isequal(state, 0) % start off with state = 0 so as to get default state
  state = struct('m', 0, 'v', 0, 't', 0);
end

% update first moment vector `m`
state.m = opts.beta1 * state.m + (1 - opts.beta1) * grad ;

% update second moment vector `v`
state.v = opts.beta2 * state.v + (1 - opts.beta2) * grad.^2 ;

% update the time step
state.t = state.t + 1 ;

% This implicitly corrects for biased estimates of first and second moment
% vectors
lr_t = lr * (((1 - opts.beta2^state.t)^0.5) / (1 - opts.beta1^state.t)) ;

% Update `w`
w = w - lr_t * state.m ./ (state.v.^0.5 + opts.eps) ;
</code>```

答:
"Insufficient number of outputs from right hand side of equal sign to satisfy assignment."
It seems your number of outputs doesn't match what's required by cnn_train.
Could you show your adam function?

In the latest version of MatConvNet

```<code>    [net.layers{l}.weights{j}, state.solverState{l}{j}] = ...
        params.solver(net.layers{l}.weights{j}, state.solverState{l}{j}, ...
        parDer, params.solverOpts, thisLR) ;
</code>```

It seems to match your adam function

Why don't you try this:

```<code>opts.solver = @adam;
</code>```

Instead of opts.solver = 'adam';

ContentLicense: CC BY-SA 3.0

Title: Adam optimizer in MatConvNet

Body:
I tried implementing Adam instead of default SGD optimizer by changing following code in cnn_train from:

opts.solver = [] ;  % Empty array means use the default SGD solver
[opts, varargin] = vl_argparse(opts, varargin) ;
if ~isempty(opts.solver)
  assert(isa(opts.solver, 'function_handle') && nargout(opts.solver) == 2,...
    'Invalid solver; expected a function handle with two outputs.') ;
  % Call without input arguments, to get default options
  opts.solverOpts = opts.solver() ;
end

to:

opts.solver = 'adam';
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.solverOpts = opts.solver() ;

However, I get an error:

Insufficient number of outputs from right hand side of equal sign to satisfy assignment.
Error in cnn_train>accumulateGradients (line 508)
params.solver(net.layers{l}.weights{j}, state.solverState{l}{j}, ...

Have any of you tried changing from default compiler? What else should I change in cnn_train?

The code for Adam function:

function [w, state] = adam(w, state, grad, opts, lr)
%ADAM
%   Adam solver for use with CNN_TRAIN and CNN_TRAIN_DAG
%
%   See [Kingma et. al., 2014](http://arxiv.org/abs/1412.6980)
%    |  ([pdf](http://arxiv.org/pdf/1412.6980.pdf)).
%
%   If called without any input argument, returns the default options
%   structure. Otherwise provide all input arguments.
%
%   W is the vector/matrix/tensor of parameters. It can be single/double
%   precision and can be a `gpuArray`.
%
%   STATE is as defined below and so are supported OPTS.
%
%   GRAD is the gradient of the objective w.r.t W
%
%   LR is the learning rate, referred to as \alpha by Algorithm 1 in
%   [Kingma et. al., 2014].
%
%   Solver options: (opts.train.solverOpts)
%
%   `beta1`:: 0.9
%      Decay for 1st moment vector. See algorithm 1 in [Kingma et.al. 2014]
%
%   `beta2`:: 0.999
%      Decay for 2nd moment vector
%
%   `eps`:: 1e-8
%      Additive offset when dividing by state.v
%
%   The state is initialized as 0 (number) to start with. The first call to
%   this function will initialize it with the default state consisting of
%
%   `m`:: 0
%      First moment vector
%
%   `v`:: 0
%      Second moment vector
%
%   `t`:: 0
%      Global iteration number across epochs
%
%   This implementation borrowed from torch optim.adam

% Copyright (C) 2016 Aravindh Mahendran.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

if nargin == 0 % Returns the default solver options
  w = struct('beta1', 0.9, 'beta2', 0.999, 'eps', 1e-8) ;
  return ;
end

if isequal(state, 0) % start off with state = 0 so as to get default state
  state = struct('m', 0, 'v', 0, 't', 0);
end

% update first moment vector `m`
state.m = opts.beta1 * state.m + (1 - opts.beta1) * grad ;

% update second moment vector `v`
state.v = opts.beta2 * state.v + (1 - opts.beta2) * grad.^2 ;

% update the time step
state.t = state.t + 1 ;

% This implicitly corrects for biased estimates of first and second moment
% vectors
lr_t = lr * (((1 - opts.beta2^state.t)^0.5) / (1 - opts.beta1^state.t)) ;

% Update `w`
w = w - lr_t * state.m ./ (state.v.^0.5 + opts.eps) ;

Body:
"Insufficient number of outputs from right hand side of equal sign to satisfy assignment."
It seems your number of outputs doesn't match what's required by cnn_train.
Could you show your adam function?

In the latest version of MatConvNet

    [net.layers{l}.weights{j}, state.solverState{l}{j}] = ...
        params.solver(net.layers{l}.weights{j}, state.solverState{l}{j}, ...
        parDer, params.solverOpts, thisLR) ;

It seems to match your adam function

Why don't you try this:

opts.solver = @adam;

Instead of opts.solver = 'adam';


问:
TRACE Macro Not Compiled Out Properly in Release Build - C++
When I do a Release build of my Visual Studio 2008 solution I get a bunch of errors like this:

error C2059: syntax error : ','

This is how I typically use TRACE:

```<code>TRACE(_T("My error message.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
</code>```

There is also an instance where I use it with 5 parameters.

I thought TRACE was suppose to compile out completely for Release builds.  What do I need to do to make it compile out complete?  Thanks.

答:
The definition of your __WFILE__ macro is causing the problem. There are two ways to solve this. First, you can define the macro as shown here:

http://msdn.microsoft.com/en-us/library/b0084kay(v=vs.80).aspx

Note they don’t wrap the macro in #ifdef _DEBUG, which makes sense since the corresponding __FILE__ macro is not removed in release mode either.

But that documentation is for VS2005. It’s been removed from newer versions of the documentation. That’s why you may want to do this:

```<code>_T(__FILE__)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
When I do a Release build of my Visual Studio 2008 solution I get a bunch of errors like this:

error C2059: syntax error : ','

This is how I typically use TRACE:

TRACE(_T("My error message.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);

There is also an instance where I use it with 5 parameters.

I thought TRACE was suppose to compile out completely for Release builds.  What do I need to do to make it compile out complete?  Thanks.

Body:
The definition of your __WFILE__ macro is causing the problem. There are two ways to solve this. First, you can define the macro as shown here:

http://msdn.microsoft.com/en-us/library/b0084kay(v=vs.80).aspx

Note they don’t wrap the macro in #ifdef _DEBUG, which makes sense since the corresponding __FILE__ macro is not removed in release mode either.

But that documentation is for VS2005. It’s been removed from newer versions of the documentation. That’s why you may want to do this:

_T(__FILE__)


问:
Deploy from Maven to JFrog Artifactory WITH properties
I have a Jenkins job, that has REPOSITORY and BRANCH input variables and uses
Invoke top-level Maven targets plugin. It makes maven clean deploy to jfrog artifactory.

But there is a problem: I don't know, how to send properties to the artifacts, that were deployed. I mean properties like these, that we have in JFROG ARTIFACTORY:

I know, that there is Maven3-Artifactory Integration plugin that makes a deploy with properties, but it doesn't work in my case, because my job should be general for different artifactory servers.

I also found a parameter Properties in Invoke top-level Maven targets

but it does nothing (the list of properties of deployed artifacts is still empty)

How can I send properties to JFROG ARTIFACTORY by maven Invoke top-level Maven targets plugin? Thanks in advance.

答:
Taking into consideration you have a requirement to dynamically control the target repository for deployment, you have multiple option:

1) Use the pipeline support of the Artifactory Jenkins plugin. The pipeline DSL allows you to dynamically control the repositories you are using for Maven resolution/deployment, for example:

```<code>def rtMaven = Artifactory.newMavenBuild()
rtMaven.resolver server: server, releaseRepo: 'libs-release', snapshotRepo: 'libs-snapshot'
rtMaven.deployer server: server, releaseRepo: 'libs-release-local', snapshotRepo: 'libs-snapshot-local'
</code>```

And add properties:

```<code>rtMaven.deployer.addProperty("status", "in-qa").addProperty("compatibility", "1", "2", "3")
</code>```

2) Use the Artifactory Maven plugin which allows you to define the resolution/deployment and properties from the pom.xml. You can also leverage environment variables or system properties to define those in a dynamic way.
For example:

```<code><build>
    <plugins>
        ...
        <plugin>
            <groupId>org.jfrog.buildinfo</groupId>
            <artifactId>artifactory-maven-plugin</artifactId>
            <version>2.6.1</version>
            <inherited>false</inherited>
            <executions>
                <execution>
                    <id>build-info</id>
                    <goals>
                        <goal>publish</goal>
                    </goals>
                    <configuration>
                        <deployProperties>
                            <build.name>{{BUILD_NAME}}</build.name>
                        </deployProperties>
                        <publisher>
                            <contextUrl>https://artifactory.mycompany.com</contextUrl>
                            <username>deployer</username>
                            <password>******</password>
                            <repoKey>{{RELEASE_REPO}}</repoKey>
                            <snapshotRepoKey>{{SNAPSHOT_REPO}}</snapshotRepoKey>
                        </publisher>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

3) As already answered by @viniciusartur, you can use matrix parameters in the repository URL to define properties

Body:
Taking into consideration you have a requirement to dynamically control the target repository for deployment, you have multiple option:

1) Use the pipeline support of the Artifactory Jenkins plugin. The pipeline DSL allows you to dynamically control the repositories you are using for Maven resolution/deployment, for example:

def rtMaven = Artifactory.newMavenBuild()
rtMaven.resolver server: server, releaseRepo: 'libs-release', snapshotRepo: 'libs-snapshot'
rtMaven.deployer server: server, releaseRepo: 'libs-release-local', snapshotRepo: 'libs-snapshot-local'

And add properties:

rtMaven.deployer.addProperty("status", "in-qa").addProperty("compatibility", "1", "2", "3")

2) Use the Artifactory Maven plugin which allows you to define the resolution/deployment and properties from the pom.xml. You can also leverage environment variables or system properties to define those in a dynamic way.
For example:

<build>
    <plugins>
        ...
        <plugin>
            <groupId>org.jfrog.buildinfo</groupId>
            <artifactId>artifactory-maven-plugin</artifactId>
            <version>2.6.1</version>
            <inherited>false</inherited>
            <executions>
                <execution>
                    <id>build-info</id>
                    <goals>
                        <goal>publish</goal>
                    </goals>
                    <configuration>
                        <deployProperties>
                            <build.name>{{BUILD_NAME}}</build.name>
                        </deployProperties>
                        <publisher>
                            <contextUrl>https://artifactory.mycompany.com</contextUrl>
                            <username>deployer</username>
                            <password>******</password>
                            <repoKey>{{RELEASE_REPO}}</repoKey>
                            <snapshotRepoKey>{{SNAPSHOT_REPO}}</snapshotRepoKey>
                        </publisher>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

3) As already answered by @viniciusartur, you can use matrix parameters in the repository URL to define properties


问:
Are valid `tf.matmul` arguments described correctly in the TensorFlow documentation?
Maybe I'm confused about what "inner" and "outer" tensor dimensions are, but the documentation for tf.matmul puzzles me:

The inputs must be matrices (or tensors of rank > 2, representing
  batches of matrices), with matching inner dimensions, possibly after
  transposition.

Isn't it the case that R-rank arguments need to have matching (or no) R-2 outer dimensions, and that (as in normal matrix multiplication) the Rth, inner dimension of the first argument must match the R-1st dimension of the second. That is, in

```<code>A = tf.constant(..., shape=[a, ..., z, p, x])
B = tf.constant(..., shape=[a', ..., z', x', q])
C = tf.matmul(A, B)
</code>```

The outer dimensions a, ..., z must be identical to a', ..., z' (or not exist), and x and x' must match (while p and q can be anything).

Or put another way, shouldn't the docs say:

The inputs must, following any transpositions, be tensors of rank ≥ 2 where the inner 2 dimensions specify valid matrix multiplication arguments, and any further outer dimensions match.

答:
This has been fixed in a recent merge. The documentation will now read:

The inputs must, following any transpositions, be tensors of rank >= 2
  where the inner 2 dimensions specify valid matrix multiplication
  arguments, and any further outer dimensions match.

Body:
Maybe I'm confused about what "inner" and "outer" tensor dimensions are, but the documentation for tf.matmul puzzles me:

The inputs must be matrices (or tensors of rank > 2, representing
  batches of matrices), with matching inner dimensions, possibly after
  transposition.

Isn't it the case that R-rank arguments need to have matching (or no) R-2 outer dimensions, and that (as in normal matrix multiplication) the Rth, inner dimension of the first argument must match the R-1st dimension of the second. That is, in

A = tf.constant(..., shape=[a, ..., z, p, x])
B = tf.constant(..., shape=[a', ..., z', x', q])
C = tf.matmul(A, B)

The outer dimensions a, ..., z must be identical to a', ..., z' (or not exist), and x and x' must match (while p and q can be anything).

Or put another way, shouldn't the docs say:

The inputs must, following any transpositions, be tensors of rank ≥ 2 where the inner 2 dimensions specify valid matrix multiplication arguments, and any further outer dimensions match.


问:
Why is sfinae on if constexpr not allowed?
The detection idiom works as follows

```<code>template<typename T, typename = void>
struct has_foo {static constexpr bool value = false;};
template<typename T>
struct has_foo<T, std::void_t<decltype(&T::foo)>> {static constexpr bool value = true;};
template<typename T>
constexpr bool has_foo_v = has_foo<T>::value;
</code>```

And then we can detect the presence of foo in any type T.

```<code>if constexpr(has_foo_v<decltype(var)>)
    var.foo();
</code>```

My problem is, that is quite a lot to type (read: want to smash my keyboard a lot to type), and I wondered if the following is possible

```<code>if constexpr(std::void_t<decltype(&decltype(var)::foo)>(), true)
    var.foo();
</code>```

It is not.

Is there a reason behind this?

More specifically, what trade-offs will have to be made if this were allowed?

答:
You can also reduce the amount of code by using std::experimental::is_detected.

In your example, the code would then look like:

```<code>template <class T>
using has_foo_t = decltype(std::declval<T>().foo());

if constexpr(is_detected_v<has_foo_t,decltype(var)>)
  var.foo();
</code>```

Body:
The detection idiom works as follows

template<typename T, typename = void>
struct has_foo {static constexpr bool value = false;};
template<typename T>
struct has_foo<T, std::void_t<decltype(&T::foo)>> {static constexpr bool value = true;};
template<typename T>
constexpr bool has_foo_v = has_foo<T>::value;

And then we can detect the presence of foo in any type T.

if constexpr(has_foo_v<decltype(var)>)
    var.foo();

My problem is, that is quite a lot to type (read: want to smash my keyboard a lot to type), and I wondered if the following is possible

if constexpr(std::void_t<decltype(&decltype(var)::foo)>(), true)
    var.foo();

It is not.

Is there a reason behind this?

More specifically, what trade-offs will have to be made if this were allowed?

Body:
You can also reduce the amount of code by using std::experimental::is_detected.

In your example, the code would then look like:

template <class T>
using has_foo_t = decltype(std::declval<T>().foo());

if constexpr(is_detected_v<has_foo_t,decltype(var)>)
  var.foo();

ContentLicense: CC BY-SA 4.0


问:
Why is this unicode emoji showing as characters and not as an image when pushed live?
I have had an emoji in my website for months, but suddenly it's showing as the code or characters rather than as an image? When I look at it locally, it displays as it should, but when I view it on the live website, I get the characters instead. I have tried clearing my cache.

Also if I paste in a finger pointing upward it works. I'm sure this comes from a lack of understanding about how unicode works, but I haven't found a decent resource to help me.

Example for this :

Thanks for your help!

答:
The HTML is most likely not encoded in the charset that it (or the webserver) claims it is encoded in, causing the browser to interpret the data incorrectly.

The Emoji you have shown, U+1F447 (), is encoded as bytes F0 9F 91 87 in UTF-8.  Those same bytes are ðŸ‘‡ when interpreted as Latin-1.

You probably have your web browser configured to force the data to be interpreted as UTF-8, which would explain why you see the Emoji correctly.  Double-check your HTML's <meta> tags, and/or your webserver's Content-Type header, to make sure the correct charset is being reporting to browsers.

Alternatively, you can use HTML entities instead of raw UTF-8 octets, then you don't have to worry about charsets.  The HTML entity for U+1F447 can be written as either:

👇 (👇)

👇 (👇)

Body:
The HTML is most likely not encoded in the charset that it (or the webserver) claims it is encoded in, causing the browser to interpret the data incorrectly.

The Emoji you have shown, U+1F447 (), is encoded as bytes F0 9F 91 87 in UTF-8.  Those same bytes are ðŸ‘‡ when interpreted as Latin-1.

You probably have your web browser configured to force the data to be interpreted as UTF-8, which would explain why you see the Emoji correctly.  Double-check your HTML's <meta> tags, and/or your webserver's Content-Type header, to make sure the correct charset is being reporting to browsers.

Alternatively, you can use HTML entities instead of raw UTF-8 octets, then you don't have to worry about charsets.  The HTML entity for U+1F447 can be written as either:

&#128071; (👇)

&#x1f447; (👇)


问:
how to add image in button with text?
```<code>enter code here

package buttonfx;

/**
*
* @author 1407305
*/
          import javafx.application.*;
          import javafx.event.*;
          import javafx.scene.*;
          import javafx.scene.control.*;
          import javafx.scene.image.Image;
          import javafx.scene.image.ImageView;
          import javafx.scene.layout.*;
          import javafx.stage.*;
          public class Buttonfx extends Application {
          Label l=new Label("press the button");    // adding label
  public void start(Stage mystage) throws Exception  //starting   mystage
          {
          mystage.setTitle(("Button new gen"));
          FlowPane f=new FlowPane(); //creating flowpane
          //  Pane f=new Pane();
          Scene myscene=new Scene(f, 500,300);
          mystage.setScene(myscene);   //setting scene to stage
          ImageView imageDecline = new ImageView("C:\\Users\\kiit\\Documents\\icons\\colour.png");
          Button b=new Button("alpha" , imageDecline);
          Button b1=new Button("Beta" , imageDecline) ;
          b.setOnAction(MEHANDLER1);
          b1.setOnAction(MEHANDLER1);
          b.setLayoutX(200);
          b.setLayoutY(100);
          f.getChildren().addAll(l , b, b1);
          mystage.show();
          }
          EventHandler<ActionEvent> MEHANDLER1 = new EventHandler<ActionEvent>()
          {
          public void handle(ActionEvent ae)
          {
          String str=((Button)ae.getTarget()).getText();
          if(str.equals("Alpha"))
          {
          l.setText( str + " was pressed");
          }
          if (str.equals("Beta"))
          {
          l.setText(str + " was pressed");
          }
          }
          };
          public static void main(String[] args) throws Exception {
          launch(args);
          }
          }
</code>```

In this code i am unable to insert image in button. in this m using two buttons which doing some small operation my only intension is to add image in both the button so please rectify this programe , and give me the correct way to do it.

答:
You cannot have the same node in two different places in the scene graph. Create one image (images are not nodes, they just encapsulate the image data), and create two image views from the image.

Additionally, the Image and ImageView constructors are expecting the URL of the image, not a path to a file.

```<code>File imageFile = new File("C:/Users/kiit/Documents/icons/colour.png");
Image imageDecline = new Image(imageFile.toURI().toString());
Button b=new Button("alpha" , new ImageView(imageDecline));
Button b1=new Button("Beta" , new ImageView(imageDecline)) ;
</code>```

Title: how to add image in button with text?

Body:
enter code here

package buttonfx;

/**
*
* @author 1407305
*/
          import javafx.application.*;
          import javafx.event.*;
          import javafx.scene.*;
          import javafx.scene.control.*;
          import javafx.scene.image.Image;
          import javafx.scene.image.ImageView;
          import javafx.scene.layout.*;
          import javafx.stage.*;
          public class Buttonfx extends Application {
          Label l=new Label("press the button");    // adding label
  public void start(Stage mystage) throws Exception  //starting   mystage
          {
          mystage.setTitle(("Button new gen"));
          FlowPane f=new FlowPane(); //creating flowpane
          //  Pane f=new Pane();
          Scene myscene=new Scene(f, 500,300);
          mystage.setScene(myscene);   //setting scene to stage
          ImageView imageDecline = new ImageView("C:\\Users\\kiit\\Documents\\icons\\colour.png");
          Button b=new Button("alpha" , imageDecline);
          Button b1=new Button("Beta" , imageDecline) ;
          b.setOnAction(MEHANDLER1);
          b1.setOnAction(MEHANDLER1);
          b.setLayoutX(200);
          b.setLayoutY(100);
          f.getChildren().addAll(l , b, b1);
          mystage.show();
          }
          EventHandler<ActionEvent> MEHANDLER1 = new EventHandler<ActionEvent>()
          {
          public void handle(ActionEvent ae)
          {
          String str=((Button)ae.getTarget()).getText();
          if(str.equals("Alpha"))
          {
          l.setText( str + " was pressed");
          }
          if (str.equals("Beta"))
          {
          l.setText(str + " was pressed");
          }
          }
          };
          public static void main(String[] args) throws Exception {
          launch(args);
          }
          }

In this code i am unable to insert image in button. in this m using two buttons which doing some small operation my only intension is to add image in both the button so please rectify this programe , and give me the correct way to do it.

Body:
You cannot have the same node in two different places in the scene graph. Create one image (images are not nodes, they just encapsulate the image data), and create two image views from the image.

Additionally, the Image and ImageView constructors are expecting the URL of the image, not a path to a file.

File imageFile = new File("C:/Users/kiit/Documents/icons/colour.png");
Image imageDecline = new Image(imageFile.toURI().toString());
Button b=new Button("alpha" , new ImageView(imageDecline));
Button b1=new Button("Beta" , new ImageView(imageDecline)) ;


问:
How to define the AST for this boost spirit rule?
I have a more complex rule, but this one will suffice for this question (I hope). Consider the rule:

```<code>result = double_ >> *(char_ > int_);
</code>```

where result is declared in terms of a struct result in namespace ast:

```<code>qi::rule<Iterator, ast::result(), qi::space_type> result;
</code>```

Then how does ast::result have to look like?
According to the boost::spirit docs (http://www.boost.org/doc/libs/develop/libs/spirit/doc/html/spirit/abstracts/attributes/compound_attributes.html), the attribute of
char_ > int_ is tuple<char, int> or std::pair<char, int>.
So, I tried:

```<code>namespace ast
{

using second_type = std::vector<std::pair<char, int>>;

struct result
{
  double first;
  second_type second;
};

} // namespace ast
</code>```

in addition to

```<code>BOOST_FUSION_ADAPT_STRUCT(
  ast::result,
  (double, first),
  (ast::second_type, second)
)
</code>```

But this gives me the compile error:

```<code>error: no matching function for call to 'std::pair<char, int>::pair(const char&)'
</code>```

This rule is simple, creating the AST struct that the result will be stored in should be simple too... but how?

Here is a complete test program with my attempt:

```<code> #include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <iostream>
#include <string>
#include <vector>

namespace ast
{

using second_type = std::vector<std::pair<char, int>>;

struct result
{
  double first;
  second_type second;

  friend std::ostream& operator<<(std::ostream& os, result const& result);
};

std::ostream& operator<<(std::ostream& os, second_type::value_type val)
{
  return os << val.first << ' ' << val.second;
}

std::ostream& operator<<(std::ostream& os, result const& result)
{
  os << result.first;
  for (auto& i : result.second)
      os << ' ' << i;
  return os;
}

} // namespace ast

BOOST_FUSION_ADAPT_STRUCT(
  ast::result,
  (double, first),
  (ast::second_type, second)
)

namespace client
{

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;

template <typename Iterator>
class test_grammar : public qi::grammar<Iterator, ast::result(), qi::space_type>
{
 private:
  qi::rule<Iterator, ast::result(), qi::space_type> result;

 public:
  test_grammar() : test_grammar::base_type(result, "result_grammar")
  {
    using qi::double_;
    using qi::char_;
    using qi::int_;

    result = double_ >> *(char_ > int_);
  }
};

} // namespace client

int main()
{
  std::string const input{"3.4 a 5 b 6 c 7"};
  using iterator_type = std::string::const_iterator;
  using test_grammar = client::test_grammar<iterator_type>;
  namespace qi = boost::spirit::qi;

  test_grammar program;
  iterator_type iter{input.begin()};
  iterator_type const end{input.end()};
  ast::result out;
  bool r = qi::phrase_parse(iter, end, program, qi::space, out);

  if (!r || iter != end)
  {
    std::cerr << "Parsing failed." << std::endl;
    return 1;
  }
  std::cout << "Parsed: " << out << std::endl;
}
</code>```

答:
SirGuy changed the AST to suit the default synthesized attributes. At the cost of, indeed complicating the AST.

However, you could leverage attribute compatibity rules by adapting std::pair. In fact, that is as simple as including 1 header:

```<code>#include <boost/fusion/include/std_pair.hpp>
</code>```

Then, everything compiles without change, printing:

```<code>Parsed: 3.4 a 5 b 6 c 7
</code>```

Body:
I have a more complex rule, but this one will suffice for this question (I hope). Consider the rule:

result = double_ >> *(char_ > int_);

where result is declared in terms of a struct result in namespace ast:

qi::rule<Iterator, ast::result(), qi::space_type> result;

Then how does ast::result have to look like?
According to the boost::spirit docs (http://www.boost.org/doc/libs/develop/libs/spirit/doc/html/spirit/abstracts/attributes/compound_attributes.html), the attribute of
char_ > int_ is tuple<char, int> or std::pair<char, int>.
So, I tried:

namespace ast
{

using second_type = std::vector<std::pair<char, int>>;

struct result
{
  double first;
  second_type second;
};

} // namespace ast

in addition to

BOOST_FUSION_ADAPT_STRUCT(
  ast::result,
  (double, first),
  (ast::second_type, second)
)

But this gives me the compile error:

error: no matching function for call to 'std::pair<char, int>::pair(const char&)'

This rule is simple, creating the AST struct that the result will be stored in should be simple too... but how?

Here is a complete test program with my attempt:

 #include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <iostream>
#include <string>
#include <vector>

namespace ast
{

using second_type = std::vector<std::pair<char, int>>;

struct result
{
  double first;
  second_type second;

  friend std::ostream& operator<<(std::ostream& os, result const& result);
};

std::ostream& operator<<(std::ostream& os, second_type::value_type val)
{
  return os << val.first << ' ' << val.second;
}

std::ostream& operator<<(std::ostream& os, result const& result)
{
  os << result.first;
  for (auto& i : result.second)
      os << ' ' << i;
  return os;
}

} // namespace ast

BOOST_FUSION_ADAPT_STRUCT(
  ast::result,
  (double, first),
  (ast::second_type, second)
)

namespace client
{

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;

template <typename Iterator>
class test_grammar : public qi::grammar<Iterator, ast::result(), qi::space_type>
{
 private:
  qi::rule<Iterator, ast::result(), qi::space_type> result;

 public:
  test_grammar() : test_grammar::base_type(result, "result_grammar")
  {
    using qi::double_;
    using qi::char_;
    using qi::int_;

    result = double_ >> *(char_ > int_);
  }
};

} // namespace client

int main()
{
  std::string const input{"3.4 a 5 b 6 c 7"};
  using iterator_type = std::string::const_iterator;
  using test_grammar = client::test_grammar<iterator_type>;
  namespace qi = boost::spirit::qi;

  test_grammar program;
  iterator_type iter{input.begin()};
  iterator_type const end{input.end()};
  ast::result out;
  bool r = qi::phrase_parse(iter, end, program, qi::space, out);

  if (!r || iter != end)
  {
    std::cerr << "Parsing failed." << std::endl;
    return 1;
  }
  std::cout << "Parsed: " << out << std::endl;
}

Body:
SirGuy changed the AST to suit the default synthesized attributes. At the cost of, indeed complicating the AST.

However, you could leverage attribute compatibity rules by adapting std::pair. In fact, that is as simple as including 1 header:

#include <boost/fusion/include/std_pair.hpp>

Then, everything compiles without change, printing:

Parsed: 3.4 a 5 b 6 c 7


问:
MVVM: Tutorial from start to finish?
I'm a C#/Windows Forms programmer with more than 5 years experience. I've been investigating WPF using the MVVM (Model-View-ViewModel) design pattern. I have searched the Internet for tutorials. I have even watched the entirety of Jason Dolinger's awesome video. Although I have found many, I have not found one that takes me from start to finish. What I really want is a tutorial that doesn't assume any previous WPF knowledge.

What are your favorite WPF-MVVM tutorials that helped you to learn?

答: Don't skip John Papa's presentation from PDC Conference 2010. See it here.</p>

Title: MVVM: Tutorial from start to finish?


问:
How to calculate nearest restaurant, but my code is showing all nearby restaurants
My code is searching for nearby restaurants and working well by showing all nearest restaurants on Map,
But i want to get very near restaurant, i want to show only 1 restaurant in TextView, i don't know how i can calculate shortest path for that. Please help, Thanks:) </p>

```<code>import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.util.HashMap;
import java.util.List;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private GoogleMap mMap;
    double latitude;
    double longitude;
    private int PROXIMITY_RADIUS = 10000;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }

    //Check if Google Play Services Available or not
    if (!CheckGooglePlayServices()) {
        Log.d("onCreate", "Finishing test case since Google Play Services are not available");
        finish();
    }
    else {
        Log.d("onCreate","Google Play Services available.");
    }

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

private boolean CheckGooglePlayServices() {
    GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
    int result = googleAPI.isGooglePlayServicesAvailable(this);
    if(result != ConnectionResult.SUCCESS) {
        if(googleAPI.isUserResolvableError(result)) {
            googleAPI.getErrorDialog(this, result,
                    0).show();
        }
        return false;
    }
    return true;
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    }
    else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }

    Button btnRestaurant = (Button) findViewById(R.id.btnRestaurant);
    btnRestaurant.setOnClickListener(new View.OnClickListener() {
        String Restaurant = "restaurant";
        @Override
        public void onClick(View v) {
            Log.d("onClick", "Button is Clicked");
            mMap.clear();
            String url = getUrl(latitude, longitude, Restaurant);
            Object[] DataTransfer = new Object[2];
            DataTransfer[0] = mMap;
            DataTransfer[1] = url;
            Log.d("onClick", url);
            GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
            getNearbyPlacesData.execute(DataTransfer);
            Toast.makeText(MapsActivity.this,"Nearby Restaurants", Toast.LENGTH_LONG).show();
        }
    });

}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
}

private String getUrl(double latitude, double longitude, String nearbyPlace) {

    StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
    googlePlacesUrl.append("location=" + latitude + "," + longitude);
    googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
    googlePlacesUrl.append("&type=" + nearbyPlace);
    googlePlacesUrl.append("&sensor=true");
    googlePlacesUrl.append("&key=" + "AIzaSyATuUiZUkEc_UgHuqsBJa1oqaODI-3mLs0");
    Log.d("getUrl", googlePlacesUrl.toString());
    return (googlePlacesUrl.toString());
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {
    Log.d("onLocationChanged", "entered");

    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }

    //Place current location marker
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    mCurrLocationMarker = mMap.addMarker(markerOptions);

    //move map camera
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
    Toast.makeText(MapsActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();

    Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));

    //stop location updates
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        Log.d("onLocationChanged", "Removing Location Updates");
    }
    Log.d("onLocationChanged", "Exit");

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Asking user if explanation is needed
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

            //Prompt the user once explanation has been shown
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);

        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted. Do the
                // contacts-related task you need to do.
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                    if (mGoogleApiClient == null) {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }

            } else {

                // Permission denied, Disable the functionality that depends on this permission.
                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }

        // other 'case' lines to check for other permissions this app might request.
        // You can add here other case statements according to your requirement.
    }
}
</code>```

<p>}</p>

答:
you can use the latest google api

http://developer.android.com/google/play-services/maps.html

You can take a look at following link to draw path

Drawing a line/path on Google Maps

How to Draw Route in Google Maps API V2 from my location

Android: How to draw route directions google maps API V2 from current location to destination

Body:
My code is searching for nearby restaurants and working well by showing all nearest restaurants on Map,
But i want to get very near restaurant, i want to show only 1 restaurant in TextView, i don't know how i can calculate shortest path for that. Please help, Thanks:)

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.util.HashMap;
import java.util.List;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private GoogleMap mMap;
    double latitude;
    double longitude;
    private int PROXIMITY_RADIUS = 10000;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }

    //Check if Google Play Services Available or not
    if (!CheckGooglePlayServices()) {
        Log.d("onCreate", "Finishing test case since Google Play Services are not available");
        finish();
    }
    else {
        Log.d("onCreate","Google Play Services available.");
    }

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

private boolean CheckGooglePlayServices() {
    GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
    int result = googleAPI.isGooglePlayServicesAvailable(this);
    if(result != ConnectionResult.SUCCESS) {
        if(googleAPI.isUserResolvableError(result)) {
            googleAPI.getErrorDialog(this, result,
                    0).show();
        }
        return false;
    }
    return true;
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    }
    else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }

    Button btnRestaurant = (Button) findViewById(R.id.btnRestaurant);
    btnRestaurant.setOnClickListener(new View.OnClickListener() {
        String Restaurant = "restaurant";
        @Override
        public void onClick(View v) {
            Log.d("onClick", "Button is Clicked");
            mMap.clear();
            String url = getUrl(latitude, longitude, Restaurant);
            Object[] DataTransfer = new Object[2];
            DataTransfer[0] = mMap;
            DataTransfer[1] = url;
            Log.d("onClick", url);
            GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
            getNearbyPlacesData.execute(DataTransfer);
            Toast.makeText(MapsActivity.this,"Nearby Restaurants", Toast.LENGTH_LONG).show();
        }
    });

}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
}

private String getUrl(double latitude, double longitude, String nearbyPlace) {

    StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
    googlePlacesUrl.append("location=" + latitude + "," + longitude);
    googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
    googlePlacesUrl.append("&type=" + nearbyPlace);
    googlePlacesUrl.append("&sensor=true");
    googlePlacesUrl.append("&key=" + "AIzaSyATuUiZUkEc_UgHuqsBJa1oqaODI-3mLs0");
    Log.d("getUrl", googlePlacesUrl.toString());
    return (googlePlacesUrl.toString());
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {
    Log.d("onLocationChanged", "entered");

    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }

    //Place current location marker
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    mCurrLocationMarker = mMap.addMarker(markerOptions);

    //move map camera
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
    Toast.makeText(MapsActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();

    Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));

    //stop location updates
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        Log.d("onLocationChanged", "Removing Location Updates");
    }
    Log.d("onLocationChanged", "Exit");

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Asking user if explanation is needed
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

            //Prompt the user once explanation has been shown
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);

        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted. Do the
                // contacts-related task you need to do.
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                    if (mGoogleApiClient == null) {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }

            } else {

                // Permission denied, Disable the functionality that depends on this permission.
                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }

        // other 'case' lines to check for other permissions this app might request.
        // You can add here other case statements according to your requirement.
    }
}

}


问:
"'init' is deprecated" warning after Swift4 convert
In Swift3, I previously converted a Bool to an Int using the following method

```<code>let _ = Int(NSNumber(value: false))
</code>```

After converting to Swift4, I'm getting a "'init' is deprecated" warning. How else should this be done?

答:
You can use NSNumber property intValue:

```<code>let x = NSNumber(value: false).intValue
</code>```

You can also use init?(exactly number: NSNumber) initializer:

```<code>let y = Int(exactly: NSNumber(value: false))
</code>```

or as mentioned in comments by @Hamish the numeric initializer has been renamed to init(truncating:)

```<code>let z = Int(truncating: NSNumber(value: false))
</code>```

or let Xcode implicitly create a NSNumber from it as mentioned by @MartinR

```<code>let z = Int(truncating: false)
</code>```

Another option you have is to extend protocol BinaryInteger (Swift 4) or Integer (Swift3) and create your own non fallible initializer that takes a Bool as parameter and returns the original type using the ternary operator as suggested in comments by @vadian:

```<code>extension BinaryInteger {
    init(_ bool: Bool) {
        self = bool ? 1 : 0
    }
}
</code>```

```<code>let a = Int(true)   // 1
let b = Int(false)  // 0

let c = UInt8(true)  // 1
let d = UInt8(false) // 0
</code>```

Body:
In Swift3, I previously converted a Bool to an Int using the following method

let _ = Int(NSNumber(value: false))

After converting to Swift4, I'm getting a "'init' is deprecated" warning. How else should this be done?

Body:
You can use NSNumber property intValue:

let x = NSNumber(value: false).intValue

You can also use init?(exactly number: NSNumber) initializer:

let y = Int(exactly: NSNumber(value: false))

or as mentioned in comments by @Hamish the numeric initializer has been renamed to init(truncating:)

let z = Int(truncating: NSNumber(value: false))

or let Xcode implicitly create a NSNumber from it as mentioned by @MartinR

let z = Int(truncating: false)

Another option you have is to extend protocol BinaryInteger (Swift 4) or Integer (Swift3) and create your own non fallible initializer that takes a Bool as parameter and returns the original type using the ternary operator as suggested in comments by @vadian:

extension BinaryInteger {
    init(_ bool: Bool) {
        self = bool ? 1 : 0
    }
}

let a = Int(true)   // 1
let b = Int(false)  // 0

let c = UInt8(true)  // 1
let d = UInt8(false) // 0


问:
Xdebug profiler output file
X debug is returning output as parts instead of just one file.
I am using ubuntu 16 and don't know why suddenly the output is  in several files.
The problem that i have is that i cannot open this files in Kcachegrind as the output have different parts in separated files.
Anyone?
Thanks in advance</p>

答:
With the default configuration xdebug creates one file per PID.

when you profile a website with ajax calls, the browser will make more than one request, and maybe these are processed by different PIDs/Instances of your webserver and so you get multiple files.

you could check your php.ini. there are multiple xdebug settings to control how the profiling data is stored. for example:

xdebug.profiler_aggregate:
  Type: integer, Default value: 0 When this setting is set to 1, a
  single profiler file will be written for multiple requests. One can
  surf to multiple pages or reload a page to get an average across all
  requests. The file will be named .cachegrind.aggregate. You will need
  to move this file to get another round of aggregate data.

xdebug.profiler_append:
  Type: integer, Default value: 0 When this setting is set to 1,
  profiler files will not be overwritten when a new request would map to
  the same file (depending on the xdebug.profiler_output_name setting.
  Instead the file will be appended to with the new profile.

xdebug.profiler_output_name
  Type: string, Default value:
  cachegrind.out.%p

This setting determines the name of the file that is used to dump
  traces into. The setting specifies the format with format specifiers,
  very similar to sprintf() and strftime(). There are several format
  specifiers that can be used to format the file name.

see more in the xdebug documentation

the other option is to use the File/Add menu in KCachegrind:

Adds a profile data file to the current window. By this, you can force
  multiple data files to be loaded into the same toplevel window even if
  they are not from the same run as given by the profile data file
  naming convention.

Title: Xdebug profiler output file


问:
Good way to sanitize input in classic asp
I have to update old projects at work. I do not have any experience with classic asp, although i'm familiar with php scripting.

Are there any functions I should use?

Can you provide me with a good function for some basic protection?

Is there something like a parameterized query in asp?

Thanks!

答:
Always use Server.HTMLEncode to sanitize user input.

For example, if you're setting a variable from a form text box:

firstName = Server.HTMLEncode(trim(request.form("firstname")))

OwnerDisplayName: Sander Versluys

LastEditorDisplayName: Sander Versluys

OwnerDisplayName: Don

LastEditorDisplayName: Don


问:
SQL Windowed functions Error - Looking for a code fix / suggestion
Updated question

I want to get the COUNTS and SUMS of LOT items numbers. The lots have different BATCH numbers, each BATCH can have different REVISION numbers. REVISION numbers have to be the MAX(Revision) number within each batch number for PROPOSALSTATUS that are "awarded" or "closed/cancelled". If the proposal status is "ROR Awarded" or "OAA Awarded" then all values me be counted.

THIS is what I'm trying to use. Because of my MAX(revision) over statements I keep receiving a Windowed Functions Error. I do not understand how to work around that. If someone could take one of these counts and one sum and show me how to work around it would be awesome.

```<code>SELECT
COUNT(PB.lot)AS SubmittedCount,

COUNT(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot,pb.batch,(CASE WHEN pb.ProposalStatus = 'Closed/Cancelled'   OR pb.proposalstatus = 'Awarded' THEN 1 ELSE NULL END))) +
COUNT(CASE WHEN pb.proposalstatus = 'ROR Awarded'  or pb.ProposalStatus = 'OAA Awarded' THEN 1 ELSE NULL END)AS DecidedCount,

COUNT(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot, pb.batch,(CASE WHEN pb.proposalstatus = 'OAA Partially Awarded' OR pb.ProposalStatus = 'ROR Partially Awarded'  OR pb.proposalstatus = 'OAA Proposal Submitted - Pending Award' THEN 1 ELSE NULL END))) +
COUNT(CASE WHEN pb.ProposalStatus = 'Awarded' OR pb.ProposalStatus = 'ROR Awarded' OR pb.ProposalStatus = 'OAA Awarded' THEN 1 ELSE NULL END) AS WonCount,

COUNT(CASE WHEN pb.ProposalStatus = 'Disapproved' THEN 1 ELSE NULL END) AS DisapprovedCount,

SUM(pb.materialvalue + pb.shippingValue)AS Total,

SUM(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot,pb.batch,(CASE WHEN pb.ProposalStatus = 'Closed/Cancelled'   OR pb.proposalstatus = 'Awarded' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END))) +
SUM(CASE WHEN pb.proposalstatus = 'ROR Awarded'  or pb.ProposalStatus = 'OAA Awarded' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END)AS DecidedTotal,

SUM(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot,pb.batch,(CASE WHEN pb.proposalstatus = 'OAA Partially Awarded' OR pb.ProposalStatus = 'ROR Partially Awarded'  OR pb.proposalstatus = 'OAA Proposal Submitted - Pending Award' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END))) +
SUM(CASE WHEN pb.ProposalStatus = 'Awarded' OR pb.ProposalStatus = 'ROR Awarded' OR pb.ProposalStatus = 'OAA Awarded' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END) AS WonTotal,

SUM(CASE WHEN pb.proposalStatus = 'Disapproved' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END) AS DisapprovedTotal

FROM  DB1 ps
INNER JOIN DB2 pb
ON ps.Title = pb.Lot

WHERE  (pb.ProposalSubmitted IS NOT NULL)  AND BATCH <> 6 AND (ps.Contract LIKE 'CLS')
GROUP BY pb.lot, pb.batch, pb.revision, pb.proposalstatus
ORDER BY pb.lot
</code>```

Realistically -  I want to be able to put this into a small table that looks like this:
Sample Input

Final Results

```<code>    declare @pb table
              (lot, proposalStatus, proposalSubmitted datetime,
               revision, materialValue, shippingValue, batch);

    insert into @pb
    values ('1', 'Awarded', '5/23/2016', '0', '200', '100', '2'),
           ('1', 'Awarded', '5/23/2016', '0', '200', '300', '4'),
           ('2', 'Pending', '  ', '1', '100', '400', '2'),
           ('3', 'Cancelled', '6/12/2016', '4', '200', '100', '4'),
           ('4', 'Awarded', '5/12/2016', '2', '300', '100', '3')

    declare @ps table
                   (title, contract);
    insert into ps
values ('1', 'CLS'),
       ('1', 'AFC'),
       ('2', 'CLS'),
       ('3', 'AFC'),
       ('4', 'CLS')
</code>```

My join is on pb.lot = ps.title

答:
You can use this code to calculate MaxRevision Count, replace ROW_NUMBER with RANK if you want to count all max revisions (not first only):

```<code>WITH Data AS (
    SELECT *,
        IsMaxRevision = IIF(ROW_NUMBER() OVER(PARTITION BY PB.lot,PB.batch ORDER BY Revision DESC) = 1, 1, 0)
    FROM @ps        PS
    INNER JOIN @pb  PB ON ps.Title = pb.Lot
)
SELECT
    lot, batch,
    DecidedCount        = SUM(CASE WHEN proposalstatus IN ('ROR Awarded', 'OAA Awarded') THEN 1
                                   WHEN proposalstatus IN ('Closed/Cancelled', 'Awarded') THEN IsMaxRevision
                              END),

    SubmittedCount      = COUNT(lot),
    OutstandingCount    = COUNT(CASE WHEN proposalstatus IN ('Partially Awarded', 'OAA Partially Awarded', 'ROR Partially Awarded', 'Proposal Submitted - Pending Award', 'OAA Proposal Submitted - Pending Award') THEN 1 ELSE NULL END),
    WonCount            = COUNT(CASE WHEN ProposalStatus IN ('Awarded', 'ROR Awarded', 'OAA Awarded') THEN 1 ELSE NULL END),
    DisapprovedCount    = COUNT(CASE WHEN ProposalStatus = 'Disapproved' THEN 1 ELSE NULL END),

    Total               = SUM(materialvalue + shippingValue),
    DecidedTotal        = SUM(CASE WHEN proposalstatus IN ('Closed/Cancelled', 'Awarded', 'ROR Awarded', 'OAA Awarded') THEN materialvalue + shippingValue ELSE NULL END),
    OutstandingTotal    = SUM(CASE WHEN proposalstatus IN ('Partially Awarded', 'OAA Partially Awarded', 'ROR Partially Awarded', 'Proposal Submitted - Pending Award', 'OAA Proposal Submitted - Pending Award') THEN materialvalue + shippingValue ELSE NULL END),
    WonTotal            = SUM(CASE WHEN proposalstatus IN ('Awarded', 'ROR Awarded', 'OAA Awarded') THEN materialvalue + shippingValue ELSE NULL END),
    DisapprovedTotal    = SUM(CASE WHEN proposalStatus = 'Disapproved' THEN MaterialValue + ShippingValue ELSE NULL END)
FROM Data   D
GROUP BY lot, batch
</code>```

Body:
Updated question

I want to get the COUNTS and SUMS of LOT items numbers. The lots have different BATCH numbers, each BATCH can have different REVISION numbers. REVISION numbers have to be the MAX(Revision) number within each batch number for PROPOSALSTATUS that are "awarded" or "closed/cancelled". If the proposal status is "ROR Awarded" or "OAA Awarded" then all values me be counted.

THIS is what I'm trying to use. Because of my MAX(revision) over statements I keep receiving a Windowed Functions Error. I do not understand how to work around that. If someone could take one of these counts and one sum and show me how to work around it would be awesome.

SELECT
COUNT(PB.lot)AS SubmittedCount,

COUNT(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot,pb.batch,(CASE WHEN pb.ProposalStatus = 'Closed/Cancelled'   OR pb.proposalstatus = 'Awarded' THEN 1 ELSE NULL END))) +
COUNT(CASE WHEN pb.proposalstatus = 'ROR Awarded'  or pb.ProposalStatus = 'OAA Awarded' THEN 1 ELSE NULL END)AS DecidedCount,

COUNT(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot, pb.batch,(CASE WHEN pb.proposalstatus = 'OAA Partially Awarded' OR pb.ProposalStatus = 'ROR Partially Awarded'  OR pb.proposalstatus = 'OAA Proposal Submitted - Pending Award' THEN 1 ELSE NULL END))) +
COUNT(CASE WHEN pb.ProposalStatus = 'Awarded' OR pb.ProposalStatus = 'ROR Awarded' OR pb.ProposalStatus = 'OAA Awarded' THEN 1 ELSE NULL END) AS WonCount,

COUNT(CASE WHEN pb.ProposalStatus = 'Disapproved' THEN 1 ELSE NULL END) AS DisapprovedCount,

SUM(pb.materialvalue + pb.shippingValue)AS Total,

SUM(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot,pb.batch,(CASE WHEN pb.ProposalStatus = 'Closed/Cancelled'   OR pb.proposalstatus = 'Awarded' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END))) +
SUM(CASE WHEN pb.proposalstatus = 'ROR Awarded'  or pb.ProposalStatus = 'OAA Awarded' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END)AS DecidedTotal,

SUM(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot,pb.batch,(CASE WHEN pb.proposalstatus = 'OAA Partially Awarded' OR pb.ProposalStatus = 'ROR Partially Awarded'  OR pb.proposalstatus = 'OAA Proposal Submitted - Pending Award' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END))) +
SUM(CASE WHEN pb.ProposalStatus = 'Awarded' OR pb.ProposalStatus = 'ROR Awarded' OR pb.ProposalStatus = 'OAA Awarded' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END) AS WonTotal,

SUM(CASE WHEN pb.proposalStatus = 'Disapproved' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END) AS DisapprovedTotal

FROM  DB1 ps
INNER JOIN DB2 pb
ON ps.Title = pb.Lot

WHERE  (pb.ProposalSubmitted IS NOT NULL)  AND BATCH <> 6 AND (ps.Contract LIKE 'CLS')
GROUP BY pb.lot, pb.batch, pb.revision, pb.proposalstatus
ORDER BY pb.lot

Realistically -  I want to be able to put this into a small table that looks like this:
Sample Input

Final Results

    declare @pb table
              (lot, proposalStatus, proposalSubmitted datetime,
               revision, materialValue, shippingValue, batch);

    insert into @pb
    values ('1', 'Awarded', '5/23/2016', '0', '200', '100', '2'),
           ('1', 'Awarded', '5/23/2016', '0', '200', '300', '4'),
           ('2', 'Pending', '  ', '1', '100', '400', '2'),
           ('3', 'Cancelled', '6/12/2016', '4', '200', '100', '4'),
           ('4', 'Awarded', '5/12/2016', '2', '300', '100', '3')

    declare @ps table
                   (title, contract);
    insert into ps
values ('1', 'CLS'),
       ('1', 'AFC'),
       ('2', 'CLS'),
       ('3', 'AFC'),
       ('4', 'CLS')

My join is on pb.lot = ps.title

Body:
You can use this code to calculate MaxRevision Count, replace ROW_NUMBER with RANK if you want to count all max revisions (not first only):

WITH Data AS (
    SELECT *,
        IsMaxRevision = IIF(ROW_NUMBER() OVER(PARTITION BY PB.lot,PB.batch ORDER BY Revision DESC) = 1, 1, 0)
    FROM @ps        PS
    INNER JOIN @pb  PB ON ps.Title = pb.Lot
)
SELECT
    lot, batch,
    DecidedCount        = SUM(CASE WHEN proposalstatus IN ('ROR Awarded', 'OAA Awarded') THEN 1
                                   WHEN proposalstatus IN ('Closed/Cancelled', 'Awarded') THEN IsMaxRevision
                              END),

    SubmittedCount      = COUNT(lot),
    OutstandingCount    = COUNT(CASE WHEN proposalstatus IN ('Partially Awarded', 'OAA Partially Awarded', 'ROR Partially Awarded', 'Proposal Submitted - Pending Award', 'OAA Proposal Submitted - Pending Award') THEN 1 ELSE NULL END),
    WonCount            = COUNT(CASE WHEN ProposalStatus IN ('Awarded', 'ROR Awarded', 'OAA Awarded') THEN 1 ELSE NULL END),
    DisapprovedCount    = COUNT(CASE WHEN ProposalStatus = 'Disapproved' THEN 1 ELSE NULL END),

    Total               = SUM(materialvalue + shippingValue),
    DecidedTotal        = SUM(CASE WHEN proposalstatus IN ('Closed/Cancelled', 'Awarded', 'ROR Awarded', 'OAA Awarded') THEN materialvalue + shippingValue ELSE NULL END),
    OutstandingTotal    = SUM(CASE WHEN proposalstatus IN ('Partially Awarded', 'OAA Partially Awarded', 'ROR Partially Awarded', 'Proposal Submitted - Pending Award', 'OAA Proposal Submitted - Pending Award') THEN materialvalue + shippingValue ELSE NULL END),
    WonTotal            = SUM(CASE WHEN proposalstatus IN ('Awarded', 'ROR Awarded', 'OAA Awarded') THEN materialvalue + shippingValue ELSE NULL END),
    DisapprovedTotal    = SUM(CASE WHEN proposalStatus = 'Disapproved' THEN MaterialValue + ShippingValue ELSE NULL END)
FROM Data   D
GROUP BY lot, batch


问:
scraping website with login page
I currently login to the time from website using the following script.

```<code>browser = webdriver.Chrome('E:/Shared Folders/Users/runnerjp/chromedriver/chromedriver.exe')
browser.get("https://www.timeform.com/horse-racing/account/sign-in?returnUrl=%2Fhorse-racing%2F")
time.sleep(3)
username = browser.find_element_by_id("EmailAddress")
password = browser.find_element_by_id("Password")
username.send_keys("usr")
password.send_keys("pass")
login_attempt = browser.find_element_by_xpath("//input[@type='submit']")
time.sleep(3)
login_attempt.submit()
</code>```

it works but I find using Chrome web driver is hammering my CPU. Is there an alternative code I could use that does not mean I need to physically load the page to sign in?

答:
Another alternative is 'grab' module:</p>

```<code>from grab import Grab

g = Grab()
g.go('https://www.timeform.com/horse-racing/account/sign-in?returnUrl=%2Fhorse-racing%2F')
g.doc.set_input('EmailAddress','some@email.com')
g.doc.set_input('Password','somepass')
g.doc.submit()

print g.doc.body
</code>```

Title: scraping website with login page

Body:
I currently login to the time from website using the following script.

browser = webdriver.Chrome('E:/Shared Folders/Users/runnerjp/chromedriver/chromedriver.exe')
browser.get("https://www.timeform.com/horse-racing/account/sign-in?returnUrl=%2Fhorse-racing%2F")
time.sleep(3)
username = browser.find_element_by_id("EmailAddress")
password = browser.find_element_by_id("Password")
username.send_keys("usr")
password.send_keys("pass")
login_attempt = browser.find_element_by_xpath("//input[@type='submit']")
time.sleep(3)
login_attempt.submit()

it works but I find using Chrome web driver is hammering my CPU. Is there an alternative code I could use that does not mean I need to physically load the page to sign in?

Body:
Another alternative is 'grab' module:

from grab import Grab

g = Grab()
g.go('https://www.timeform.com/horse-racing/account/sign-in?returnUrl=%2Fhorse-racing%2F')
g.doc.set_input('EmailAddress','some@email.com')
g.doc.set_input('Password','somepass')
g.doc.submit()

print g.doc.body


问:
Multiple buttons in HeroCard
I'd like to have multiple buttons on HeroCard
and be able to press all buttons one after another
but when I press click button program jumps to next function in waterfall
and expects next action instead of button action again
what should I do in this case?

```<code>bot.dialog("/showCards", [
    (session) => {
        const msg = new Message(session)
            .textFormat(TextFormat.xml)
            .attachmentLayout(AttachmentLayout.carousel)
            .attachments([{
                title: "title",
                url: "https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png"
            }].map(obj =>
                new HeroCard(session)
                    .title(obj.title)
                    .images([
                        CardImage.create(session, obj.url)
                            .tap(CardAction.showImage(session, obj.url)),
                    ])
                    .buttons([
                        CardAction.openUrl(session, obj.url),
                        CardAction.imBack(session, `click`, "Click"),
                        CardAction.imBack(session, `clack`, "Clack")
                    ])
            ));
        Prompts.choice(session, msg, ["click", "clack"]);

    },
    (session, results) => {
        // todo use results.response.entity
    }
]);
</code>```

答: Use a switch-case in the ResumeAfter function, in the default case send the user to the previous function.</p>

Title: Multiple buttons in HeroCard

Body:
I'd like to have multiple buttons on HeroCard
and be able to press all buttons one after another
but when I press click button program jumps to next function in waterfall
and expects next action instead of button action again
what should I do in this case?

bot.dialog("/showCards", [
    (session) => {
        const msg = new Message(session)
            .textFormat(TextFormat.xml)
            .attachmentLayout(AttachmentLayout.carousel)
            .attachments([{
                title: "title",
                url: "https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png"
            }].map(obj =>
                new HeroCard(session)
                    .title(obj.title)
                    .images([
                        CardImage.create(session, obj.url)
                            .tap(CardAction.showImage(session, obj.url)),
                    ])
                    .buttons([
                        CardAction.openUrl(session, obj.url),
                        CardAction.imBack(session, `click`, "Click"),
                        CardAction.imBack(session, `clack`, "Clack")
                    ])
            ));
        Prompts.choice(session, msg, ["click", "clack"]);

    },
    (session, results) => {
        // todo use results.response.entity
    }
]);


问:
Windows command for cutting columns from a text
The following content is stored in a file:

```<code>chrome.exe                   512 Console                 0     73,780 K
chrome.exe                   800 Console                 0     11,052 K
chrome.exe                  1488 Console                 0     92,720 K
chrome.exe                  1600 Console                 0     32,344 K
chrome.exe                  2240 Console                 0     35,132 K
chrome.exe                  2360 Console                 0     21,276 K
chrome.exe                  3524 Console                 0     66,732 K
chrome.exe                  3924 Console                 0     23,524 K
</code>```

Is there a way to extract the 5th column with the Windows command line?

Something like the UNIX cut command.

答:
Use double % in variable

```<code>for /f "tokens=5 delims= " %%i in (file.txt) DO echo %%i
</code>```

Body:
The following content is stored in a file:

chrome.exe                   512 Console                 0     73,780 K
chrome.exe                   800 Console                 0     11,052 K
chrome.exe                  1488 Console                 0     92,720 K
chrome.exe                  1600 Console                 0     32,344 K
chrome.exe                  2240 Console                 0     35,132 K
chrome.exe                  2360 Console                 0     21,276 K
chrome.exe                  3524 Console                 0     66,732 K
chrome.exe                  3924 Console                 0     23,524 K

Is there a way to extract the 5th column with the Windows command line?

Something like the UNIX cut command.

Body:
Use double % in variable

for /f "tokens=5 delims= " %%i in (file.txt) DO echo %%i


问:
Center figure image and caption in Bootstrap 4
I have a figure containing an image and caption as shown below:

```<code><figure class="figure">
  <img src="../img/atmpressure.svg" class="figure-img img-fluid" alt="pressue plot">
  <figcaption class="figure-caption text-center">Plot of pressure at different altitudes.</figcaption>
</figure>
</code>```

I am using Bootstrap 4 to style the web page. Using the text-center class for the caption, I'm able to center the caption text. I would also like to center the image in the figure. The mx-auto and text-center classes do not work when the image is within a figure (see example below).

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Elit ratione dolorum velit nesciunt aliquid Vitae culpa exercitationem ex animi quis praesentium Fuga sapiente dignissimos deserunt quia officiis nihil. Vero dignissimos excepturi iste ut fugiat! Nostrum quibusdam labore molestiae.

Plot of pressure at different altitudes.

```

How can I horizontally center the entire figure in the column?

答:
The problem is two fold. Your original issue was that you only had .text-center on the figcaption. To center the img and figcaption in the figure, move .text-center to figure instead and that will center the inline img and text in the figcaption horizontally.

Then when you said that didn't work and included the context of the rest of the page, turns out you're wanting the figure to be centered relative to the content around it, too. figure has class .figure, which adds display: inline-block; so it will be left aligned in the .col by default. The easiest way to center the contents of the figure relative to the content outside of the figure is to either remove the .figure class so the element can be it's native display: block and .text-center will center it's contents, or you can add the class .d-block to the figure if you want to retain the .figure class.

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Elit ratione dolorum velit nesciunt aliquid Vitae culpa exercitationem ex animi quis praesentium Fuga sapiente dignissimos deserunt quia officiis nihil. Vero dignissimos excepturi iste ut fugiat! Nostrum quibusdam labore molestiae.

Plot of pressure at different altitudes.

```

Body:
I have a figure containing an image and caption as shown below:

Plot of pressure at different altitudes.

I am using Bootstrap 4 to style the web page. Using the text-center class for the caption, I'm able to center the caption text. I would also like to center the image in the figure. The mx-auto and text-center classes do not work when the image is within a figure (see example below).

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Elit ratione dolorum velit nesciunt aliquid Vitae culpa exercitationem ex animi quis praesentium Fuga sapiente dignissimos deserunt quia officiis nihil. Vero dignissimos excepturi iste ut fugiat! Nostrum quibusdam labore molestiae.

Plot of pressure at different altitudes.

How can I horizontally center the entire figure in the column?

Body:
The problem is two fold. Your original issue was that you only had .text-center on the figcaption. To center the img and figcaption in the figure, move .text-center to figure instead and that will center the inline img and text in the figcaption horizontally.

Then when you said that didn't work and included the context of the rest of the page, turns out you're wanting the figure to be centered relative to the content around it, too. figure has class .figure, which adds display: inline-block; so it will be left aligned in the .col by default. The easiest way to center the contents of the figure relative to the content outside of the figure is to either remove the .figure class so the element can be it's native display: block and .text-center will center it's contents, or you can add the class .d-block to the figure if you want to retain the .figure class.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <!-- Styles -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="col">
        <p>Elit ratione dolorum velit nesciunt aliquid Vitae culpa exercitationem ex animi quis praesentium Fuga sapiente dignissimos deserunt quia officiis nihil. Vero dignissimos excepturi iste ut fugiat! Nostrum quibusdam labore molestiae.</p>
        <figure class="text-center">
          <img src="http://kenwheeler.github.io/slick/img/lazyfonz2.png" class="figure-img img-fluid" alt="pressue plot">
          <figcaption class="figure-caption">Plot of pressure at different altitudes.</figcaption>
        </figure>
      </div>
    </div>
  </div>
</body>

</html>


问:
AWS S3 putObject symbols special chracters
Using the aws-sdk for Javascript I'm running into a odd issue where special charaters are not being translated after putting the text into an object

Here is my code:

```<code>var AWS = require('aws-sdk');

AWS.config.update({
 region: "us-east-1",
 endpoint: "s3.amazonaws.com"
});

var s3 = new AWS.S3();

var params = {
 Bucket: 'test-example',
 Key: 'test.html',
 Body: 'Copyright © 2017',
 ACL:'public-read',
 ContentType: 'text/html'
}
s3.putObject(params, function(err, data) {
 if (err) console.log(err, err.stack); // an error occurred
 else     console.log(data);           // successful response
});
</code>```

Which renders to an HTML page that displays:
"Copyright Â© 2017"

How do I remove the addition character Â

答:
Instead of this...

```<code>ContentType: 'text/html'
</code>```

...explicitly tell the browser the character encoding of the content:

```<code>ContentType: 'text/html; charset=utf-8'
</code>```

This sets both the content type and subtype that S3 will return in the HTTP Content-Type response header, which the browser uses to correctly interpret the object data.

Body:
Using the aws-sdk for Javascript I'm running into a odd issue where special charaters are not being translated after putting the text into an object

Here is my code:

var AWS = require('aws-sdk');

AWS.config.update({
 region: "us-east-1",
 endpoint: "s3.amazonaws.com"
});

var s3 = new AWS.S3();

var params = {
 Bucket: 'test-example',
 Key: 'test.html',
 Body: 'Copyright © 2017',
 ACL:'public-read',
 ContentType: 'text/html'
}
s3.putObject(params, function(err, data) {
 if (err) console.log(err, err.stack); // an error occurred
 else     console.log(data);           // successful response
});

Which renders to an HTML page that displays:
"Copyright Â© 2017"

How do I remove the addition character Â

Body:
Instead of this...

ContentType: 'text/html'

...explicitly tell the browser the character encoding of the content:

ContentType: 'text/html; charset=utf-8'

This sets both the content type and subtype that S3 will return in the HTTP Content-Type response header, which the browser uses to correctly interpret the object data.


问:
How to set alpha on UIButton's label subviews
I want to programmatically set multiple alignment combinations for my button title, like so:

The easiest way I found to do this was to add two UILabels as subviews of my custom UIButton and set autolayout constraints accordingly.

However, I can't figure out how to make my labels behave the same way as a button title would (namely having its alpha altered when a button tap occurs).

I have tried setting their alpha property in a target-action method for .touchUpInside but since they're not attached to the button state, they won't change their alpha back to normal when the user ends tapping the button.

```<code>class Button: UIView {

var leftButton = UIButton(type: .roundedRect)
var rightButton = UIButton(type: .roundedRect)

init() {
    super.init(frame: .zero)
    createButton()
}

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

func createButton() {
    self.backgroundColor = UIColor.cyan
    self.layer.borderWidth = 0.5
    self.layer.borderColor = UIColor.blue.cgColor
    self.addSubview(leftButton)
    self.addSubview(rightButton)

    leftButton.setTitle("left", for: .normal)
    leftButton.setTitleColor(UIColor.black, for: .normal)
    leftButton.layer.borderColor = UIColor.yellow.cgColor
    leftButton.layer.borderWidth = 0.5
    leftButton.translatesAutoresizingMaskIntoConstraints = false
    leftButton.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
    leftButton.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
    leftButton.trailingAnchor.constraint(lessThanOrEqualTo: rightButton.leadingAnchor).isActive = true
    leftButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true

    rightButton.setTitle("right", for: .normal)
    rightButton.layer.borderColor = UIColor.green.cgColor
    rightButton.layer.borderWidth = 0.5
    rightButton.setTitleColor(UIColor.black, for: .normal)
    rightButton.translatesAutoresizingMaskIntoConstraints = false
    rightButton.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
    rightButton.leadingAnchor.constraint(greaterThanOrEqualTo: leftButton.trailingAnchor).isActive = true
    rightButton.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
    rightButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true

    leftButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
    rightButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
}

func buttonTapped() {
    print("button tapped")
}
</code>```

答:
there is a better approach.

Take two buttons and keep them in a stackView and do necessary settings.

But make sure that two buttons will point to same action.So that it will seem to user that it's actually one button.

here is the output.

I just made this in storyboard. As i am using stackView so programmatically creating and layouting is super easy. I think you can do it. :)

To stop flashing:

Make each button type custom.

How to make only one button action for both button?

See this popular stack answer.

Here is the result.

Body:
I want to programmatically set multiple alignment combinations for my button title, like so:

The easiest way I found to do this was to add two UILabels as subviews of my custom UIButton and set autolayout constraints accordingly.

However, I can't figure out how to make my labels behave the same way as a button title would (namely having its alpha altered when a button tap occurs).

I have tried setting their alpha property in a target-action method for .touchUpInside but since they're not attached to the button state, they won't change their alpha back to normal when the user ends tapping the button.

class Button: UIView {

var leftButton = UIButton(type: .roundedRect)
var rightButton = UIButton(type: .roundedRect)

init() {
    super.init(frame: .zero)
    createButton()
}

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

func createButton() {
    self.backgroundColor = UIColor.cyan
    self.layer.borderWidth = 0.5
    self.layer.borderColor = UIColor.blue.cgColor
    self.addSubview(leftButton)
    self.addSubview(rightButton)

    leftButton.setTitle("left", for: .normal)
    leftButton.setTitleColor(UIColor.black, for: .normal)
    leftButton.layer.borderColor = UIColor.yellow.cgColor
    leftButton.layer.borderWidth = 0.5
    leftButton.translatesAutoresizingMaskIntoConstraints = false
    leftButton.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
    leftButton.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
    leftButton.trailingAnchor.constraint(lessThanOrEqualTo: rightButton.leadingAnchor).isActive = true
    leftButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true

    rightButton.setTitle("right", for: .normal)
    rightButton.layer.borderColor = UIColor.green.cgColor
    rightButton.layer.borderWidth = 0.5
    rightButton.setTitleColor(UIColor.black, for: .normal)
    rightButton.translatesAutoresizingMaskIntoConstraints = false
    rightButton.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
    rightButton.leadingAnchor.constraint(greaterThanOrEqualTo: leftButton.trailingAnchor).isActive = true
    rightButton.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
    rightButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true

    leftButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
    rightButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
}

func buttonTapped() {
    print("button tapped")
}


问:
Which algorithm is used in google's tesseract-OCR for Recognition?
Which algorithm is used in google's tesseract-OCR for Recognition?Is it Neural Network?</p>

答:
This paper in the tesseract source provides a deep overview of the technology.

Notably:

Blobs are organized into text lines, and the lines and regions are
  analyzed for fixed pitch or proportional text.

[...]

Recognition then proceeds as a two-pass process. In the first pass, an
  attempt is made to recognize each word in turn. Each word that is
  satisfactory is passed to an adaptive classifier as training data. The
  adaptive classifier then gets a chance to more accurately recognize
  text lower down the page.

[...]

Once the text lines have been found, the baselines are fitted more
  precisely using a quadratic spline.

[...]

The baselines are fitted by partitioning the blobs into groups with a
  reasonably continuous displacement for the original straight baseline.
  A quadratic spline is fitted to the most populous partition, (assumed
  to be the baseline) by a least squares fit.

The paper does not explicitly state whether it uses a neural network, but given the content I would say it's likely, at least for parts of it.

For more on line-finding, see R. Smith, “A Simple and Efficient Skew Detection Algorithm via Text Row Accumulation”, Proc. of the 3rd Int. Conf. on Document Analysis and Recognition (Vol. 2), IEEE 1995, pp. 1145-1148.


问:
can we integrating custom filter pipe and pagination in angular2
I have a component to display a table of date with pagination, sort and filter. I have custom pagination service that slices the data and displays. But my filter and sort pipe only works for the sliced data. Where as it needs to work for the complete JSON data.
Can i have suggestions of how to parse the complete data.
Below is how Iam using the filter pipe and sort pipe.</p>

```<code><tbody  *ngFor = "let request of slicedRequestObjects | category: searchText : optionVal | orderBy: convertSorting(); let i = index;" >
</code>```

答:
You need to make sure that your filtering comes before the pagination does it work. It sounds like if you have 50 items in a list, your paginator is taking the first 10, and then you are filtering that list of 10 only.

I use a package called ng2-pagination. It functions as a pipe on your *ngFor. I then use this in tandem with a custom pipe I created to do filtering.

It looks something like

```<code>*ngFor="let item of myList | termFilter:searchTerm | paginate: { itemsPerPage: 15, currentPage: c, id: 'c' }"
</code>```

Body:
You need to make sure that your filtering comes before the pagination does it work. It sounds like if you have 50 items in a list, your paginator is taking the first 10, and then you are filtering that list of 10 only.

I use a package called ng2-pagination. It functions as a pipe on your *ngFor. I then use this in tandem with a custom pipe I created to do filtering.

It looks something like

*ngFor="let item of myList | termFilter:searchTerm | paginate: { itemsPerPage: 15, currentPage: c, id: 'c' }"