问:
wxwidgets wxtreectrl wxTR_HAS_BUTTONS does not enable plus minus buttons next to tree
When I create a treectrl item with wxTR_HAS_BUTTONS enabled, no buttons seem to show. I am compiling using VC++ 2008.

```<code>    treectrlModelTree = new wxTreeCtrl( itemPanel3, ID_TREECTRL_MODEL_TREE, wxDefaultPosition, wxDefaultSize, wxTR_EDIT_LABELS|wxTR_HAS_BUTTONS |wxTR_SINGLE|wxSUNKEN_BORDER );
</code>```

I am adding the root with:

```<code>wxTreeItemId rootId = treectrlModelTree->AddRoot("Model Tree", -1, -1,  new MyTreeItemData((void*)group));
</code>```

and appending data to the tree with the AppendItem() command:

```<code>wxTreeItemId tempItem = treectrlModelTree->AppendItem(groupId, tmpstr, -1, -1, new MyTreeItemData(tracker->model));
</code>```

I tried searching around but it does not seem like there are too many posts online about treectrl problems.

答:
I figured it out,

It has to do with a bug in wxwidgets 2.8.9 where dragging items within the treectrl will give an error when there is no images assigned to a treectrl (i.e. folder images).

See: [http://trac.wxwidgets.org/ticket/4390][1]

I was using a quick fix suggested, to add a dummy image list

```<code>treectrlModelTree->AssignImageList(new wxImageList(1, 1));
</code>```

which suppressed the plus/minus buttons for the treectrl.

Body:
When I create a treectrl item with wxTR_HAS_BUTTONS enabled, no buttons seem to show. I am compiling using VC++ 2008.

    treectrlModelTree = new wxTreeCtrl( itemPanel3, ID_TREECTRL_MODEL_TREE, wxDefaultPosition, wxDefaultSize, wxTR_EDIT_LABELS|wxTR_HAS_BUTTONS |wxTR_SINGLE|wxSUNKEN_BORDER );

I am adding the root with:

wxTreeItemId rootId = treectrlModelTree->AddRoot("Model Tree", -1, -1,  new MyTreeItemData((void*)group));

and appending data to the tree with the AppendItem() command:

wxTreeItemId tempItem = treectrlModelTree->AppendItem(groupId, tmpstr, -1, -1, new MyTreeItemData(tracker->model));

I tried searching around but it does not seem like there are too many posts online about treectrl problems.

Body:
I figured it out,

It has to do with a bug in wxwidgets 2.8.9 where dragging items within the treectrl will give an error when there is no images assigned to a treectrl (i.e. folder images).

See: [http://trac.wxwidgets.org/ticket/4390][1]

I was using a quick fix suggested, to add a dummy image list

treectrlModelTree->AssignImageList(new wxImageList(1, 1));

which suppressed the plus/minus buttons for the treectrl.


来源: stackexchange

问:
Laravel Passport - Get Client Secret by client id
I have the client_id from oauth_clients and need to get the secret.
Not possible to make a normal Model query or DB query, since the secret property is protected.

答:
You can access the client_id and client_secret if you know the oauth_clients id:

```<code>/**
     * DefaultController constructor.
     */
    public function __construct()
    {
        $this->client = DB::table('oauth_clients')->where('id', 2)->first();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    protected function authenticate(Request $request)
    {
        $request->request->add([
            'username' => $request->username,
            'password' => $request->password,
            'grant_type' => 'password',
            'client_id' => $this->client->id,
            'client_secret' => $this->client->secret,
            'scope' => '*'
        ]);

        $proxy = Request::create(
            'oauth/token',
            'POST'
        );

        return Route::dispatch($proxy);
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can access the client_id and client_secret if you know the oauth_clients id:

/**
     * DefaultController constructor.
     */
    public function __construct()
    {
        $this->client = DB::table('oauth_clients')->where('id', 2)->first();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    protected function authenticate(Request $request)
    {
        $request->request->add([
            'username' => $request->username,
            'password' => $request->password,
            'grant_type' => 'password',
            'client_id' => $this->client->id,
            'client_secret' => $this->client->secret,
            'scope' => '*'
        ]);

        $proxy = Request::create(
            'oauth/token',
            'POST'
        );

        return Route::dispatch($proxy);
    }


问:
Scheme lambda and let errors
A beginner in scheme.. trying out the following code to test the equivalence of lambda and let

```<code>(lambda (x y)
  (+ x y)
  10
  (* x 2))

(let ((k 10)
      (y (* 2 k)))
  (+ k y))
</code>```

the output is

```<code>#<procedure>
. . k: undefined;
 cannot reference undefined identifier
>
</code>```

Any help would be appreciated

答:
Scheme's let has two restrictions.

The variables defined by let are not visible to the body of subsequent definitions.

The variables defined by let are not visible to the body of the definition itself.

The first restriction applies to your example.

```<code>(let ((k 10)
      (y (* 2 k)))
  (+ k y))
</code>```

In this example k and y are defined in the same let. The body of y does know know k. In order to make k visible to the body of y, you have to use two let expressions.

```<code>(let ((k 10))
  (let ((y (* 2 k)))
    (+ k y)))
</code>```

In order to avoid this kind of nesting, Scheme provides the let* alternative.

```<code>(let* ((k 10)
       (y (* 2 k)))
  (+ k y))
</code>```

If you read the specification of let*, you should consider also reading the specification of letrec, which is eliminates the second restriction.

Title: Scheme lambda and let errors

Body:
A beginner in scheme.. trying out the following code to test the equivalence of lambda and let

(lambda (x y)
  (+ x y)
  10
  (* x 2))

(let ((k 10)
      (y (* 2 k)))
  (+ k y))

the output is

#<procedure>
. . k: undefined;
 cannot reference undefined identifier
>

Any help would be appreciated

Body:
Scheme's let has two restrictions.

The variables defined by let are not visible to the body of subsequent definitions.

The variables defined by let are not visible to the body of the definition itself.

The first restriction applies to your example.

(let ((k 10)
      (y (* 2 k)))
  (+ k y))

In this example k and y are defined in the same let. The body of y does know know k. In order to make k visible to the body of y, you have to use two let expressions.

(let ((k 10))
  (let ((y (* 2 k)))
    (+ k y)))

In order to avoid this kind of nesting, Scheme provides the let* alternative.

(let* ((k 10)
       (y (* 2 k)))
  (+ k y))

If you read the specification of let*, you should consider also reading the specification of letrec, which is eliminates the second restriction.


问:
Plaid API quickstart project error http://127.0.0.1:5000/get_access_token
I am trying to get started with the plaid API. I created my account to get the API keys and I have the quickstart project. I put my keys in the code(they are not applied in the code below) and when I run it I use the sandbox credentials. Unfortunately after the log in succeeds I always receive the same error when trying to receive the access token:

HTTP500: SERVER ERROR - The server encountered an unexpected condition
  that prevented it from fulfilling the request.(XHR)POST -
  http://127.0.0.1:5000/get_access_token

Here is the code:

```<code>import os
import datetime
import plaid
from flask import Flask
from flask import render_template
from flask import request
from flask import jsonify

app = Flask(__name__)

# Fill in your Plaid API keys - https://dashboard.plaid.com/account/keys
PLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID')
PLAID_SECRET = os.getenv('PLAID_SECRET')
PLAID_PUBLIC_KEY = os.getenv('PLAID_PUBLIC_KEY')
# Use 'sandbox' to test with Plaid's Sandbox environment (username:
user_good,
# password: pass_good)
# Use `development` to test with live users and credentials and `production`
# to go live
PLAID_ENV = os.getenv('PLAID_ENV', 'sandbox')

client = plaid.Client(client_id = PLAID_CLIENT_ID, secret=PLAID_SECRET,
                  public_key=PLAID_PUBLIC_KEY, environment=PLAID_ENV)

@app.route("/")
def index():
   return render_template('index.ejs', plaid_public_key=PLAID_PUBLIC_KEY,
plaid_environment=PLAID_ENV)

access_token = None
public_token = None

@app.route("/get_access_token", methods=['POST'])
def get_access_token():
  global access_token
  public_token = request.form['public_token']
  exchange_response = client.Item.public_token.exchange(public_token)
  print ('public token: ' + public_token)
  print ('access token: ' + exchange_response['access_token'])
  print ('item ID: ' + exchange_response['item_id'])

  access_token = exchange_response['access_token']

  return jsonify(exchange_response)

@app.route("/accounts", methods=['GET'])
def accounts():
  global access_token
  accounts = client.Auth.get(access_token)
  return jsonify(accounts)

@app.route("/item", methods=['GET', 'POST'])
def item():
  global access_token
  item_response = client.Item.get(access_token)
  institution_response = client.Institutions.get_by_id(item_response['item']
['institution_id'])
  return jsonify({'item': item_response['item'], 'institution':
institution_response['institution']})

@app.route("/transactions", methods=['GET', 'POST'])
def transactions():
  global access_token
  # Pull transactions for the last 30 days
  start_date = "{:%Y-%m-%d}".format(datetime.datetime.now() +
datetime.timedelta(-30))
  end_date = "{:%Y-%m-%d}".format(datetime.datetime.now())

  try:
    response = client.Transactions.get(access_token, start_date, end_date)
    return jsonify(response)
  except plaid.errors.PlaidError as e:
    return jsonify({'error': {'error_code': e.code, 'error_message':
str(e)}})

@app.route("/create_public_token", methods=['GET'])
def create_public_token():
  global access_token
  # Create a one-time use public_token for the Item. This public_token can
be used to
  # initialize Link in update mode for the user.
  response = client.Item.public_token.create(access_token)
  return jsonify(response)

if __name__ == "__main__":
    app.run(port=os.getenv('PORT', 5000))
</code>```

答: the problem was solved by putting the credentials to the client.py-file which is being created while you install plaid</p>

Body:
I am trying to get started with the plaid API. I created my account to get the API keys and I have the quickstart project. I put my keys in the code(they are not applied in the code below) and when I run it I use the sandbox credentials. Unfortunately after the log in succeeds I always receive the same error when trying to receive the access token:

HTTP500: SERVER ERROR - The server encountered an unexpected condition
  that prevented it from fulfilling the request.(XHR)POST -
  http://127.0.0.1:5000/get_access_token

Here is the code:

import os
import datetime
import plaid
from flask import Flask
from flask import render_template
from flask import request
from flask import jsonify

app = Flask(__name__)

# Fill in your Plaid API keys - https://dashboard.plaid.com/account/keys
PLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID')
PLAID_SECRET = os.getenv('PLAID_SECRET')
PLAID_PUBLIC_KEY = os.getenv('PLAID_PUBLIC_KEY')
# Use 'sandbox' to test with Plaid's Sandbox environment (username:
user_good,
# password: pass_good)
# Use `development` to test with live users and credentials and `production`
# to go live
PLAID_ENV = os.getenv('PLAID_ENV', 'sandbox')

client = plaid.Client(client_id = PLAID_CLIENT_ID, secret=PLAID_SECRET,
                  public_key=PLAID_PUBLIC_KEY, environment=PLAID_ENV)

@app.route("/")
def index():
   return render_template('index.ejs', plaid_public_key=PLAID_PUBLIC_KEY,
plaid_environment=PLAID_ENV)

access_token = None
public_token = None

@app.route("/get_access_token", methods=['POST'])
def get_access_token():
  global access_token
  public_token = request.form['public_token']
  exchange_response = client.Item.public_token.exchange(public_token)
  print ('public token: ' + public_token)
  print ('access token: ' + exchange_response['access_token'])
  print ('item ID: ' + exchange_response['item_id'])

  access_token = exchange_response['access_token']

  return jsonify(exchange_response)

@app.route("/accounts", methods=['GET'])
def accounts():
  global access_token
  accounts = client.Auth.get(access_token)
  return jsonify(accounts)

@app.route("/item", methods=['GET', 'POST'])
def item():
  global access_token
  item_response = client.Item.get(access_token)
  institution_response = client.Institutions.get_by_id(item_response['item']
['institution_id'])
  return jsonify({'item': item_response['item'], 'institution':
institution_response['institution']})

@app.route("/transactions", methods=['GET', 'POST'])
def transactions():
  global access_token
  # Pull transactions for the last 30 days
  start_date = "{:%Y-%m-%d}".format(datetime.datetime.now() +
datetime.timedelta(-30))
  end_date = "{:%Y-%m-%d}".format(datetime.datetime.now())

  try:
    response = client.Transactions.get(access_token, start_date, end_date)
    return jsonify(response)
  except plaid.errors.PlaidError as e:
    return jsonify({'error': {'error_code': e.code, 'error_message':
str(e)}})

@app.route("/create_public_token", methods=['GET'])
def create_public_token():
  global access_token
  # Create a one-time use public_token for the Item. This public_token can
be used to
  # initialize Link in update mode for the user.
  response = client.Item.public_token.create(access_token)
  return jsonify(response)

if __name__ == "__main__":
    app.run(port=os.getenv('PORT', 5000))


问:
ViewPort method without zoom effect in JavaFX
I'm trying to Slice an image to show on a screen.
For example if I change the right margin to 20 of the flower picture on the left and the bottom margin of the flower picture in the right to 20 they should behave as follow:

(the original pictures are shown in the first column)
enter image description here

ViewPort method does exactly what I want, cutting the image and leaving the margin empty but it uses image's original size displaying a zoom effect as it says in the javafx website:

"The rectangular viewport into the image. The viewport is specified in the coordinates of the image, prior to scaling or any other transformations.
If viewport is null, the entire image is displayed. If viewport is non-null, only the portion of the image which falls within the viewport will be displayed. If the image does not fully cover the viewport then any remaining area of the viewport will be empty."

I already tried to use imageView.resize(screenWidth, screenHeight) before setting the viewport but it doesn't work.

Also tried to imageView.setFitWidth(screenWidth), imageView.setFitHeight(screenHeight)

Is it possible to rescale the image so it's displayed as described?
Or any other work-around?

Here is my code for left margin as an example:

mediaContent.resize(screenWidth, screen.getHeight());
//  mediaContent.setFitWidth(screenWidth);
//  mediaContent.setFitHeight(screen.getHeight());
 mediaContent.setViewport(new Rectangle2D(screenWidth-dXLeft, 0, screenWidth, screen.getHeight()));

Update: Tried setting setFitWidth and setFitHeightas suggested stills displays the image zoomed in

```<code>    `imageView.setFitWidth(space.getX());
    imageView.setFitHeight(space.getY());
    imageView.setViewport(new Rectangle2D(screen.getWidth()-space.getX(), 0, screen.getWidth(), screen.getHeight()));
    imageView.setFitWidth(space.getX());
    imageView.setFitHeight(space.getY());

    return imageView;`
</code>```

This is the result when I use the setViewport method when not
setting margins: enter image description here

How it should be when not setting margins: enter image description here

Update 2: Example (modified from java-buddy) zooming in

```<code>package javafx_imageview_viewport;

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_ImageView_Viewport extends Application {

@Override
public void start(Stage primaryStage) {

    ImageView imageView1 = new ImageView(new Image("https://i.imgur.com/6Zl0eQB.jpg"));
    imageView1.setFitWidth(150);
    imageView1.setFitHeight(100);

    //Example to rotate ImageView
    Image image2 = new Image("https://i.imgur.com/6Zl0eQB.jpg");
    Rectangle2D viewportRect2 = new Rectangle2D(
            image2.getWidth()/4,
            image2.getHeight()/4,
            image2.getWidth()*3/4,
            image2.getHeight()*3/4);
    ImageView imageView2 = new ImageView(image2);
    imageView2.setFitWidth(150);
    imageView2.setFitHeight(100);
    imageView2.setViewport(viewportRect2);

    Slider sliderRotate = new Slider();
    sliderRotate.setMin(0);
    sliderRotate.setMax(360);
    sliderRotate.setValue(0);
    sliderRotate.valueProperty().addListener(
            (ObservableValue<? extends Number> observable,
                    Number oldValue, Number newValue) -> {
        imageView2.setRotate((double)newValue);
    });

    //Example to change ViewPort
    Image image3 = new Image("https://i.imgur.com/6Zl0eQB.jpg");
    Rectangle2D viewportRect3 = new Rectangle2D(
            0,
            0,
            image3.getWidth(),
            image3.getHeight());
    ImageView imageView3 = new ImageView(image3);
    imageView3.setFitWidth(150);
    imageView3.setFitHeight(100);
    imageView3.setViewport(viewportRect3);

    Slider sliderViewPort = new Slider();
    sliderViewPort.setMin(0);
    sliderViewPort.setMax(1.0);
    sliderViewPort.setValue(1.0);
    sliderViewPort.valueProperty().addListener(
            (ObservableValue<? extends Number> observable,
                    Number oldValue, Number newValue) -> {
        Rectangle2D newViewportRect3 = new Rectangle2D(
                0,
                0,
                (double)newValue*image3.getWidth(),
                (double)newValue*image3.getHeight());
        imageView3.setViewport(newViewportRect3);
    });

    VBox vBox = new VBox();
    vBox.getChildren().addAll(imageView1,
            imageView2, sliderRotate,
            imageView3, sliderViewPort);

    StackPane root = new StackPane();
    root.getChildren().add(vBox);

    Scene scene = new Scene(root, 300, 350);

    primaryStage.setTitle("java-buddy: ImageVIew ViewPort");
    primaryStage.setScene(scene);
    primaryStage.show();
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}
}
</code>```

Example 2 from java-buddy how I want it to behave, cutting the image:

```<code>package javafx_imageview_viewport;

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_ImageView_Viewport extends Application {

@Override
public void start(Stage primaryStage) {

    ImageView imageView1 = new ImageView(new Image("https://i.imgur.com/294AEFU.png"));

    //Example to rotate ImageView
    Image image2 = new Image("https://i.imgur.com/294AEFU.png");
    Rectangle2D viewportRect2 = new Rectangle2D(
            image2.getWidth()/4,
            image2.getHeight()/4,
            image2.getWidth()*3/4,
            image2.getHeight()*3/4);
    ImageView imageView2 = new ImageView(image2);
    imageView2.setViewport(viewportRect2);

    Slider sliderRotate = new Slider();
    sliderRotate.setMin(0);
    sliderRotate.setMax(360);
    sliderRotate.setValue(0);
    sliderRotate.valueProperty().addListener(
            (ObservableValue<? extends Number> observable,
                    Number oldValue, Number newValue) -> {
        imageView2.setRotate((double)newValue);
    });

    //Example to change ViewPort
    Image image3 = new Image("https://i.imgur.com/294AEFU.png");
    Rectangle2D viewportRect3 = new Rectangle2D(
            0,
            0,
            image3.getWidth(),
            image3.getHeight());
    ImageView imageView3 = new ImageView(image3);
    imageView3.setViewport(viewportRect3);

    Slider sliderViewPort = new Slider();
    sliderViewPort.setMin(0);
    sliderViewPort.setMax(1.0);
    sliderViewPort.setValue(1.0);
    sliderViewPort.valueProperty().addListener(
            (ObservableValue<? extends Number> observable,
                    Number oldValue, Number newValue) -> {
        Rectangle2D newViewportRect3 = new Rectangle2D(
                0,
                0,
                (double)newValue*image3.getWidth(),
                (double)newValue*image3.getHeight());
        imageView3.setViewport(newViewportRect3);
    });

    VBox vBox = new VBox();
    vBox.getChildren().addAll(imageView1,
            imageView2, sliderRotate,
            imageView3, sliderViewPort);

    StackPane root = new StackPane();
    root.getChildren().add(vBox);

    Scene scene = new Scene(root, 300, 350);

    primaryStage.setTitle("java-buddy: ImageVIew ViewPort");
    primaryStage.setScene(scene);
    primaryStage.show();
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

}
</code>```

答:
It seems that what I wanted does not make sense.

If I want the image to fit the screen I have to use fitScreenWidth(screenWidth)and fitScreenHeight(screenHeight) but it does not make sense to use viewPort method in this case since the image has been resized already.

viewPort method should be used only with the original image's dimensions.

Body:
I'm trying to Slice an image to show on a screen.
For example if I change the right margin to 20 of the flower picture on the left and the bottom margin of the flower picture in the right to 20 they should behave as follow:

(the original pictures are shown in the first column)
enter image description here

ViewPort method does exactly what I want, cutting the image and leaving the margin empty but it uses image's original size displaying a zoom effect as it says in the javafx website:

"The rectangular viewport into the image. The viewport is specified in the coordinates of the image, prior to scaling or any other transformations.
If viewport is null, the entire image is displayed. If viewport is non-null, only the portion of the image which falls within the viewport will be displayed. If the image does not fully cover the viewport then any remaining area of the viewport will be empty."

I already tried to use imageView.resize(screenWidth, screenHeight) before setting the viewport but it doesn't work.

Also tried to imageView.setFitWidth(screenWidth), imageView.setFitHeight(screenHeight)

Is it possible to rescale the image so it's displayed as described?
Or any other work-around?

Here is my code for left margin as an example:

mediaContent.resize(screenWidth, screen.getHeight());
//  mediaContent.setFitWidth(screenWidth);
//  mediaContent.setFitHeight(screen.getHeight());
 mediaContent.setViewport(new Rectangle2D(screenWidth-dXLeft, 0, screenWidth, screen.getHeight()));

Update: Tried setting setFitWidth and setFitHeightas suggested stills displays the image zoomed in

    `imageView.setFitWidth(space.getX());
    imageView.setFitHeight(space.getY());
    imageView.setViewport(new Rectangle2D(screen.getWidth()-space.getX(), 0, screen.getWidth(), screen.getHeight()));
    imageView.setFitWidth(space.getX());
    imageView.setFitHeight(space.getY());

    return imageView;`

This is the result when I use the setViewport method when not
setting margins: enter image description here

How it should be when not setting margins: enter image description here

Update 2: Example (modified from java-buddy) zooming in

package javafx_imageview_viewport;

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_ImageView_Viewport extends Application {

@Override
public void start(Stage primaryStage) {

    ImageView imageView1 = new ImageView(new Image("https://i.imgur.com/6Zl0eQB.jpg"));
    imageView1.setFitWidth(150);
    imageView1.setFitHeight(100);

    //Example to rotate ImageView
    Image image2 = new Image("https://i.imgur.com/6Zl0eQB.jpg");
    Rectangle2D viewportRect2 = new Rectangle2D(
            image2.getWidth()/4,
            image2.getHeight()/4,
            image2.getWidth()*3/4,
            image2.getHeight()*3/4);
    ImageView imageView2 = new ImageView(image2);
    imageView2.setFitWidth(150);
    imageView2.setFitHeight(100);
    imageView2.setViewport(viewportRect2);

    Slider sliderRotate = new Slider();
    sliderRotate.setMin(0);
    sliderRotate.setMax(360);
    sliderRotate.setValue(0);
    sliderRotate.valueProperty().addListener(
            (ObservableValue<? extends Number> observable,
                    Number oldValue, Number newValue) -> {
        imageView2.setRotate((double)newValue);
    });

    //Example to change ViewPort
    Image image3 = new Image("https://i.imgur.com/6Zl0eQB.jpg");
    Rectangle2D viewportRect3 = new Rectangle2D(
            0,
            0,
            image3.getWidth(),
            image3.getHeight());
    ImageView imageView3 = new ImageView(image3);
    imageView3.setFitWidth(150);
    imageView3.setFitHeight(100);
    imageView3.setViewport(viewportRect3);

    Slider sliderViewPort = new Slider();
    sliderViewPort.setMin(0);
    sliderViewPort.setMax(1.0);
    sliderViewPort.setValue(1.0);
    sliderViewPort.valueProperty().addListener(
            (ObservableValue<? extends Number> observable,
                    Number oldValue, Number newValue) -> {
        Rectangle2D newViewportRect3 = new Rectangle2D(
                0,
                0,
                (double)newValue*image3.getWidth(),
                (double)newValue*image3.getHeight());
        imageView3.setViewport(newViewportRect3);
    });

    VBox vBox = new VBox();
    vBox.getChildren().addAll(imageView1,
            imageView2, sliderRotate,
            imageView3, sliderViewPort);

    StackPane root = new StackPane();
    root.getChildren().add(vBox);

    Scene scene = new Scene(root, 300, 350);

    primaryStage.setTitle("java-buddy: ImageVIew ViewPort");
    primaryStage.setScene(scene);
    primaryStage.show();
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}
}

Example 2 from java-buddy how I want it to behave, cutting the image:

package javafx_imageview_viewport;

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_ImageView_Viewport extends Application {

@Override
public void start(Stage primaryStage) {

    ImageView imageView1 = new ImageView(new Image("https://i.imgur.com/294AEFU.png"));

    //Example to rotate ImageView
    Image image2 = new Image("https://i.imgur.com/294AEFU.png");
    Rectangle2D viewportRect2 = new Rectangle2D(
            image2.getWidth()/4,
            image2.getHeight()/4,
            image2.getWidth()*3/4,
            image2.getHeight()*3/4);
    ImageView imageView2 = new ImageView(image2);
    imageView2.setViewport(viewportRect2);

    Slider sliderRotate = new Slider();
    sliderRotate.setMin(0);
    sliderRotate.setMax(360);
    sliderRotate.setValue(0);
    sliderRotate.valueProperty().addListener(
            (ObservableValue<? extends Number> observable,
                    Number oldValue, Number newValue) -> {
        imageView2.setRotate((double)newValue);
    });

    //Example to change ViewPort
    Image image3 = new Image("https://i.imgur.com/294AEFU.png");
    Rectangle2D viewportRect3 = new Rectangle2D(
            0,
            0,
            image3.getWidth(),
            image3.getHeight());
    ImageView imageView3 = new ImageView(image3);
    imageView3.setViewport(viewportRect3);

    Slider sliderViewPort = new Slider();
    sliderViewPort.setMin(0);
    sliderViewPort.setMax(1.0);
    sliderViewPort.setValue(1.0);
    sliderViewPort.valueProperty().addListener(
            (ObservableValue<? extends Number> observable,
                    Number oldValue, Number newValue) -> {
        Rectangle2D newViewportRect3 = new Rectangle2D(
                0,
                0,
                (double)newValue*image3.getWidth(),
                (double)newValue*image3.getHeight());
        imageView3.setViewport(newViewportRect3);
    });

    VBox vBox = new VBox();
    vBox.getChildren().addAll(imageView1,
            imageView2, sliderRotate,
            imageView3, sliderViewPort);

    StackPane root = new StackPane();
    root.getChildren().add(vBox);

    Scene scene = new Scene(root, 300, 350);

    primaryStage.setTitle("java-buddy: ImageVIew ViewPort");
    primaryStage.setScene(scene);
    primaryStage.show();
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

}


问:
How to prevent background image from scrolling in form field in IE?
The problem is in IE7 and 6 (I have to support 6 at work).

```<code>.myForm input { background: url(../images/input_bg.jpg) no-repeat; }

<form class='myForm'>
     <input type="text" />
     <input type="text" />
     <button>Submit</button>
</form>
</code>```

In IE when you type in the input field, once you reach the end the image stops repeating and text is shown without any background image in the back of the input field. In firefox and other browsers including IE8 the text just scrolls but the image stays in place. Why does it end in IE7 and 6?

P.S. I can't remove no-repeat in the image since it has borders and you can tell it's repeating in a weird way.

答: I don't have IE6 or 7 to test, but have you tried background-attachment: fixed?

ContentLicense: CC BY-SA 2.5

Body:
The problem is in IE7 and 6 (I have to support 6 at work).

.myForm input { background: url(../images/input_bg.jpg) no-repeat; }

<form class='myForm'>
     <input type="text" />
     <input type="text" />
     <button>Submit</button>
</form>

In IE when you type in the input field, once you reach the end the image stops repeating and text is shown without any background image in the back of the input field. In firefox and other browsers including IE8 the text just scrolls but the image stays in place. Why does it end in IE7 and 6?

P.S. I can't remove no-repeat in the image since it has borders and you can tell it's repeating in a weird way.


问:
JSON move child keys up one level
I have a Python script that parses a JSON file like below:

```<code>[
  {
    "_index": "bulletins",
    "_type": "bulletin",
    "_id": "OPENWRT-SA-000001",
    "_score": null,
    "_source": {
      "lastseen": "2016-09-26T15:45:23",
      "references": [
        "http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-3193",
      ],
      "affectedPackage": [
        {
          "OS": "OpenWrt",
          "OSVersion": "15.05",
          "packageVersion": "9.9.8-P3-1",
          "packageFilename": "UNKNOWN",
          "arch": "all",
          "packageName": "bind",
          "operator": "lt"
        }
      ],
      "edition": 1,
      "description": "value in here,
      "reporter": "OpenWrt Project",
      "published": "2016-01-24T13:33:41",
      "title": "bind: Security update (4 CVEs)",
      "type": "openwrt",
      "bulletinFamily": "unix",
      "cvelist": [
        "CVE-2015-8704",
      ],
      "modified": "2016-01-24T13:33:41",
      "id": "OPENWRT-SA-000001",
      "href": "https://lists.openwrt.org/pipermail/openwrt-security-announce/2016-January/000001.html",
      "cvss": {
        "score": 7.1,
        "vector": "AV:NETWORK/AC:MEDIUM/Au:NONE/C:NONE/I:NONE/A:COMPLETE/"
      }
    },
    "sort": [
      34872
    ]
  },
</code>```

I have removed some of the values to keep the post shorter but leaving some in to try to keep the structure.

I want to take all sub keys from the _source key and move them up to the same level as _source and then delete the _source key.

My code to parse the JSON is:

```<code>import json
import logging
import logging.handlers
import os
import pymongo
from pymongo import MongoClient

def import_json(mongo_server,mongo_port, vuln_folder):
    try:
        logging.info('Connecting to MongoDB')
        client = MongoClient(mongo_server, mongo_port)
        db = client['vuln_sets']
        coll = db['vulnerabilities']
        logging.info('Connected to MongoDB')
        basepath = os.path.dirname(__file__)
        filepath = os.path.abspath(os.path.join(basepath, ".."))
        archive_filepath = filepath + vuln_folder
        filedir = os.chdir(archive_filepath)
        file_count = 0
        for item in os.listdir(filedir):
            if item.endswith('.json'):
                file_name = os.path.abspath(item)
                with open(item, 'r') as currentfile:
                    vuln_counter = 0
                    duplicate_count = 0
                    logging.info('Currently processing ' + item)
                    file_count +=1
                    json_data = currentfile.read()
                    vuln_content = json.loads(json_data)
                    for vuln in vuln_content:
                        try:
                            del vuln['_type']
                            coll.insert(vuln, continue_on_error=True)
                            vuln_counter +=1
                        except pymongo.errors.DuplicateKeyError:
                            duplicate_count +=1

                logging.info('Added ' + str(vuln_counter) + ' vulnerabilities for ' + item)
                logging.info('Found ' + str(duplicate_count) + ' duplicate records!')
                os.remove(file_name)
        logging.info('Processed ' + str(file_count) + ' files')
    except Exception as e:
        logging.exception(e)
</code>```

Which you can see already deletes one key that is not needed but that key has no needed data where as I need the sub keys from _source. I am not sure on the best way to achieve this, whether it would be programmatically correct to just re-create the JSON file with the new info but I need to keep the order of the keys and structure apart from moving the sub keys up one level.

答:
You can use the dictionary update() function to achieve what you're trying to do, but it's important to note that dictionaries don't have an "order of the keys" - see: Key Order in Python Dictionaries.

Here's an example of one way to do this, starting with a dictionary definition.

```<code>d = {
    "_index": "bulletins",
    "_type": "bulletin",
    "_id": "OPENWRT-SA-000001",
    "_score": None,
    "_source": {
        "lastseen": "2016-09-26T15:45:23",
        "references": [
            "http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-3193",
        ],
        "affectedPackage": [
            {
              "OS": "OpenWrt",
              "OSVersion": "15.05",
              "packageVersion": "9.9.8-P3-1",
              "packageFilename": "UNKNOWN",
              "arch": "all",
              "packageName": "bind",
              "operator": "lt"
            }
        ],
        "edition": 1,
        "description": "value in here",
        "reporter": "OpenWrt Project",
        "published": "2016-01-24T13:33:41",
        "title": "bind: Security update (4 CVEs)",
        "type": "openwrt",
        "bulletinFamily": "unix",
        "cvelist": [
            "CVE-2015-8704",
        ],
        "modified": "2016-01-24T13:33:41",
        "id": "OPENWRT-SA-000001",
        "href": "https://lists.openwrt.org/pipermail/openwrt-security-announce/2016-January/000001.html",
        "cvss": {
            "score": 7.1,
            "vector":     "AV:NETWORK/AC:MEDIUM/Au:NONE/C:NONE/I:NONE/A:COMPLETE/"
        }
    }
}

# create a new dictionary with everything except the key "_source"
new_d = {key: d[key] for key in d if key != '_source'}

# add the keys/values from "_source" to new dictionary
new_d.update(d['_source'])  # This will overwriting any existing keys
</code>```

The output of new_d:

```<code>{'_id': 'OPENWRT-SA-000001',
 '_index': 'bulletins',
 '_score': None,
 '_type': 'bulletin',
 'affectedPackage': [{'OS': 'OpenWrt',
   'OSVersion': '15.05',
   'arch': 'all',
   'operator': 'lt',
   'packageFilename': 'UNKNOWN',
   'packageName': 'bind',
   'packageVersion': '9.9.8-P3-1'}],
 'bulletinFamily': 'unix',
 'cvelist': ['CVE-2015-8704'],
 'cvss': {
   'score': 7.1,
   'vector': 'AV:NETWORK/AC:MEDIUM/Au:NONE/C:NONE/I:NONE/A:COMPLETE/'},
 'description': 'value in here',
 'edition': 1,
 'href': 'https://lists.openwrt.org/pipermail/openwrt-security-announce/2016-January/000001.html',
 'id': 'OPENWRT-SA-000001',
 'lastseen': '2016-09-26T15:45:23',
 'modified': '2016-01-24T13:33:41',
 'published': '2016-01-24T13:33:41',
 'references': ['http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-
3193'],
 'reporter': 'OpenWrt Project',
 'title': 'bind: Security update (4 CVEs)',
 'type': 'openwrt'}
</code>```

ContentLicense: CC BY-SA 4.0

Title: JSON move child keys up one level

Body:
I have a Python script that parses a JSON file like below:

[
  {
    "_index": "bulletins",
    "_type": "bulletin",
    "_id": "OPENWRT-SA-000001",
    "_score": null,
    "_source": {
      "lastseen": "2016-09-26T15:45:23",
      "references": [
        "http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-3193",
      ],
      "affectedPackage": [
        {
          "OS": "OpenWrt",
          "OSVersion": "15.05",
          "packageVersion": "9.9.8-P3-1",
          "packageFilename": "UNKNOWN",
          "arch": "all",
          "packageName": "bind",
          "operator": "lt"
        }
      ],
      "edition": 1,
      "description": "value in here,
      "reporter": "OpenWrt Project",
      "published": "2016-01-24T13:33:41",
      "title": "bind: Security update (4 CVEs)",
      "type": "openwrt",
      "bulletinFamily": "unix",
      "cvelist": [
        "CVE-2015-8704",
      ],
      "modified": "2016-01-24T13:33:41",
      "id": "OPENWRT-SA-000001",
      "href": "https://lists.openwrt.org/pipermail/openwrt-security-announce/2016-January/000001.html",
      "cvss": {
        "score": 7.1,
        "vector": "AV:NETWORK/AC:MEDIUM/Au:NONE/C:NONE/I:NONE/A:COMPLETE/"
      }
    },
    "sort": [
      34872
    ]
  },

I have removed some of the values to keep the post shorter but leaving some in to try to keep the structure.

I want to take all sub keys from the _source key and move them up to the same level as _source and then delete the _source key.

My code to parse the JSON is:

import json
import logging
import logging.handlers
import os
import pymongo
from pymongo import MongoClient

def import_json(mongo_server,mongo_port, vuln_folder):
    try:
        logging.info('Connecting to MongoDB')
        client = MongoClient(mongo_server, mongo_port)
        db = client['vuln_sets']
        coll = db['vulnerabilities']
        logging.info('Connected to MongoDB')
        basepath = os.path.dirname(__file__)
        filepath = os.path.abspath(os.path.join(basepath, ".."))
        archive_filepath = filepath + vuln_folder
        filedir = os.chdir(archive_filepath)
        file_count = 0
        for item in os.listdir(filedir):
            if item.endswith('.json'):
                file_name = os.path.abspath(item)
                with open(item, 'r') as currentfile:
                    vuln_counter = 0
                    duplicate_count = 0
                    logging.info('Currently processing ' + item)
                    file_count +=1
                    json_data = currentfile.read()
                    vuln_content = json.loads(json_data)
                    for vuln in vuln_content:
                        try:
                            del vuln['_type']
                            coll.insert(vuln, continue_on_error=True)
                            vuln_counter +=1
                        except pymongo.errors.DuplicateKeyError:
                            duplicate_count +=1

                logging.info('Added ' + str(vuln_counter) + ' vulnerabilities for ' + item)
                logging.info('Found ' + str(duplicate_count) + ' duplicate records!')
                os.remove(file_name)
        logging.info('Processed ' + str(file_count) + ' files')
    except Exception as e:
        logging.exception(e)

Which you can see already deletes one key that is not needed but that key has no needed data where as I need the sub keys from _source. I am not sure on the best way to achieve this, whether it would be programmatically correct to just re-create the JSON file with the new info but I need to keep the order of the keys and structure apart from moving the sub keys up one level.

Body:
You can use the dictionary update() function to achieve what you're trying to do, but it's important to note that dictionaries don't have an "order of the keys" - see: Key Order in Python Dictionaries.

Here's an example of one way to do this, starting with a dictionary definition.

d = {
    "_index": "bulletins",
    "_type": "bulletin",
    "_id": "OPENWRT-SA-000001",
    "_score": None,
    "_source": {
        "lastseen": "2016-09-26T15:45:23",
        "references": [
            "http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-3193",
        ],
        "affectedPackage": [
            {
              "OS": "OpenWrt",
              "OSVersion": "15.05",
              "packageVersion": "9.9.8-P3-1",
              "packageFilename": "UNKNOWN",
              "arch": "all",
              "packageName": "bind",
              "operator": "lt"
            }
        ],
        "edition": 1,
        "description": "value in here",
        "reporter": "OpenWrt Project",
        "published": "2016-01-24T13:33:41",
        "title": "bind: Security update (4 CVEs)",
        "type": "openwrt",
        "bulletinFamily": "unix",
        "cvelist": [
            "CVE-2015-8704",
        ],
        "modified": "2016-01-24T13:33:41",
        "id": "OPENWRT-SA-000001",
        "href": "https://lists.openwrt.org/pipermail/openwrt-security-announce/2016-January/000001.html",
        "cvss": {
            "score": 7.1,
            "vector":     "AV:NETWORK/AC:MEDIUM/Au:NONE/C:NONE/I:NONE/A:COMPLETE/"
        }
    }
}

# create a new dictionary with everything except the key "_source"
new_d = {key: d[key] for key in d if key != '_source'}

# add the keys/values from "_source" to new dictionary
new_d.update(d['_source'])  # This will overwriting any existing keys

The output of new_d:

{'_id': 'OPENWRT-SA-000001',
 '_index': 'bulletins',
 '_score': None,
 '_type': 'bulletin',
 'affectedPackage': [{'OS': 'OpenWrt',
   'OSVersion': '15.05',
   'arch': 'all',
   'operator': 'lt',
   'packageFilename': 'UNKNOWN',
   'packageName': 'bind',
   'packageVersion': '9.9.8-P3-1'}],
 'bulletinFamily': 'unix',
 'cvelist': ['CVE-2015-8704'],
 'cvss': {
   'score': 7.1,
   'vector': 'AV:NETWORK/AC:MEDIUM/Au:NONE/C:NONE/I:NONE/A:COMPLETE/'},
 'description': 'value in here',
 'edition': 1,
 'href': 'https://lists.openwrt.org/pipermail/openwrt-security-announce/2016-January/000001.html',
 'id': 'OPENWRT-SA-000001',
 'lastseen': '2016-09-26T15:45:23',
 'modified': '2016-01-24T13:33:41',
 'published': '2016-01-24T13:33:41',
 'references': ['http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-
3193'],
 'reporter': 'OpenWrt Project',
 'title': 'bind: Security update (4 CVEs)',
 'type': 'openwrt'}


问:
You have requested a non-existent service "Users_Users". Symfony3
When I try to access at my service, got this error :

You have requested a non-existent service "Users_Users".

But the namespace, the name of the class, name of the file, name of folder is ok. I have already copy paste the name to be sure.

Controller ->

```<code><?php

namespace UsersBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use UsersBundle\Form\UsersForm;
use Symfony\Component\HttpFoundation\Request;

class UsersController extends Controller
{
    public function UsersAction($Id)
    {
        $Users = $this->container->get('Users_Users')->ListeUsers($Id);
        return $this->render('UsersBundle:Users:users.html.twig', array('Users' => $Users));
    }
</code>```

Service :

```<code><?php

namespace UsersBundle\Services;

class Users
{
    public function __construct($ldap,$Core_ConnexionsBDD,$MySql_ConnexionsBDD, $session)
    {
        $this->ldap = $ldap;
        $this->Core_ConnexionsBDD = $Core_ConnexionsBDD;
        $this->MySql_ConnexionsBDD = $MySql_ConnexionsBDD;
        $this->session = $session;
    }

    public function ListeUsers($Id)
    {
        $lists = $this->MySql_ConnexionsBDD->getUsers();
        return $lists->Liste($Id);
    }

}
</code>```

Un the service file, no problem, it's a copy paste of the

get('Users_Users')

Where is the problem? I use the same method for my 4 other bundle :/

答:
In app/config.yml missing import :

```<code>   - { resource: "@UsersBundle/Resources/config/services.yml" }
</code>```

Content of UsersBundle/Resources/config/services.yml :

```<code>services:

Users_Users:
    class: UsersBundle\Services\Users
    arguments: ["@Core_ConnexionsBDD","@MySql_ConnexionsBDD","@session"]
</code>```

Body:
When I try to access at my service, got this error :

You have requested a non-existent service "Users_Users".

But the namespace, the name of the class, name of the file, name of folder is ok. I have already copy paste the name to be sure.

Controller ->

<?php

namespace UsersBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use UsersBundle\Form\UsersForm;
use Symfony\Component\HttpFoundation\Request;

class UsersController extends Controller
{
    public function UsersAction($Id)
    {
        $Users = $this->container->get('Users_Users')->ListeUsers($Id);
        return $this->render('UsersBundle:Users:users.html.twig', array('Users' => $Users));
    }

Service :

<?php

namespace UsersBundle\Services;

class Users
{
    public function __construct($ldap,$Core_ConnexionsBDD,$MySql_ConnexionsBDD, $session)
    {
        $this->ldap = $ldap;
        $this->Core_ConnexionsBDD = $Core_ConnexionsBDD;
        $this->MySql_ConnexionsBDD = $MySql_ConnexionsBDD;
        $this->session = $session;
    }

    public function ListeUsers($Id)
    {
        $lists = $this->MySql_ConnexionsBDD->getUsers();
        return $lists->Liste($Id);
    }

}

Un the service file, no problem, it's a copy paste of the

get('Users_Users')

Where is the problem? I use the same method for my 4 other bundle :/

Body:
In app/config.yml missing import :

   - { resource: "@UsersBundle/Resources/config/services.yml" }

Content of UsersBundle/Resources/config/services.yml :

services:

Users_Users:
    class: UsersBundle\Services\Users
    arguments: ["@Core_ConnexionsBDD","@MySql_ConnexionsBDD","@session"]


问:
How to disable selenium server port to outside world?
When I run selenium on server:

```<code>java -jar /usr/lib/selenium/selenium-server-standalone-3.7.0.jar
</code>```

The port 4444 is opened on all network interfaces also to outside world. Is there a way to run it only on 127.0.0.1 so I can run test only internally?

答:
I tried to read this page, and here is my answer. Let me first point to your comment, and then i will answer your question:

I was wondering is it possible to do it by some command line switch
  in selenium

There is no way to do it by commands line of selenium. And there are two reasons:

Reason 1:

Because none of the Selenium Server or Client Libraries are designed to cover such need, therefore such feature is not provided in them. You are actually asking a security question, but expect that a testing tool supports it.

Reason 2:

Let's assume there is a command for it, and using it your command line would ask Selenium Server to not answer the http requests outside of 127.0.0.1.

2.1. Do you think, the selenium web server can distinguish between the IPs of the requests?

2.2. Do you think, it is able to have a policy to reject some of the requests in behavioral  testing?

(Just remember what is selenium test server: The Selenium Server which launches and kills browsers, interprets and runs the Selenese commands passed from the test program, and acts as an HTTP proxy.)

How to disable selenium server port to outside world?

Here i provide you 2 solutions:

One tool is docker. Docker is a virtualization tool, which helps you to separate the test environment from production. So, no one else outside this virtual environment has access to the system. Additionally, the opened port (444) is on the virtual machine. Meaning that no malicious user can reach this port. In other word, if you use docker then your selenium server has nothing to do with your real world application, although you are testing the same application.The below image explains the Docker.

The best option for you is a Firewall. It is the exact tool which is meant to deal with suspicious requests. It receives a malicious request on port 444, and it checks its defined policy, and then rejects it.

Body:
When I run selenium on server:

java -jar /usr/lib/selenium/selenium-server-standalone-3.7.0.jar

The port 4444 is opened on all network interfaces also to outside world. Is there a way to run it only on 127.0.0.1 so I can run test only internally?


问:
Why is arrow function sent as a parameter when it simply returns the value it takes as is?
I am new to JavaScript and I am learning React using the following tutorial.

It also teaches to use Alt as a state management library and my question is related to the connect method syntax. I am not explaining the problem in detail as I believe my question is only related to understanding the syntax.

I understand that here connect passes comma separated parameters as props to the component App. I however do not understand the first parameter.

The arrow functions I have come across all use {} after => such as () => {}, where parameters will be in () and body of the function will be in {}

My understanding of ({lanes}) => ({lanes}) is that this is a function that takes an array of objects named lanes and returns the same array .The code snippet is as below:

```<code>export default connect(({lanes}) => ({lanes}), {
    LaneActions
})(App)
</code>```

My questions are:

Am I right that the first parameter is indeed a function?

is lanes enclosed in {} to specify it's an array?  If no, what does it represent?

If 1. is right, why pass a function that passes the parameter as is. Why not write connect as connect(lanes,LaneActions)(App) or connect({lanes},LaneActions)(App)

Would enclosing lanes in {} make a difference and what is it?

If 1. is wrong please explain what the first parameter means.

答:
Yes, that is indeed an arrow function.

No, that is not an "array" in JS (although if you've used PHP, you might mistakenly call it that, since the PHP community often uses "(associative) array" for this concept). That's an "object" in JS jargon, i.e., a key-value data structure (whereas in JS, arrays are numerically indexed). Specifically, the left-hand side is a new feature called "destructuring arguments", which takes an object and pulls out specific keys into local variables. On the right-hand side, there's an object literal, creating a new object based on local data (note that the value is omitted, a trick possible in recent JS).

Presumably because connect expects a callback as the first argument, and would break if you passed a non-function. Also, note that this isn't plain passthrough; it strips every key except lanes from the first argument, before returning it.

Since (1) is right, no answer needed here.

5 & 6: These are a bit broad. I'd recommend asking a new question or checking MDN's page on arrow functions if you want to find out all there is to know. To answer for this specific case: the () on the argument is needed because the arguments are more complex than a single identifier, the {} in the arguments are for destructuring, the () on the body is to distinguish between an object literal and a block consisting only of the single statement lanes, and the {} in the body creates an object literal.

If you're wondering exactly what the (somewhat densely-coded) arrow function does, by the way, it does roughly the same thing as the following (give or take a few currently-irrelevant quirks of arrow functions):

```<code>function(obj) {
    return { lanes: obj.lanes };
}
</code>```

Body:
I am new to JavaScript and I am learning React using the following tutorial.

It also teaches to use Alt as a state management library and my question is related to the connect method syntax. I am not explaining the problem in detail as I believe my question is only related to understanding the syntax.

I understand that here connect passes comma separated parameters as props to the component App. I however do not understand the first parameter.

The arrow functions I have come across all use {} after => such as () => {}, where parameters will be in () and body of the function will be in {}

My understanding of ({lanes}) => ({lanes}) is that this is a function that takes an array of objects named lanes and returns the same array .The code snippet is as below:

export default connect(({lanes}) => ({lanes}), {
    LaneActions
})(App)

My questions are:

Am I right that the first parameter is indeed a function?

is lanes enclosed in {} to specify it's an array?  If no, what does it represent?

If 1. is right, why pass a function that passes the parameter as is. Why not write connect as connect(lanes,LaneActions)(App) or connect({lanes},LaneActions)(App)

Would enclosing lanes in {} make a difference and what is it?

If 1. is wrong please explain what the first parameter means.

Body:
Yes, that is indeed an arrow function.

No, that is not an "array" in JS (although if you've used PHP, you might mistakenly call it that, since the PHP community often uses "(associative) array" for this concept). That's an "object" in JS jargon, i.e., a key-value data structure (whereas in JS, arrays are numerically indexed). Specifically, the left-hand side is a new feature called "destructuring arguments", which takes an object and pulls out specific keys into local variables. On the right-hand side, there's an object literal, creating a new object based on local data (note that the value is omitted, a trick possible in recent JS).

Presumably because connect expects a callback as the first argument, and would break if you passed a non-function. Also, note that this isn't plain passthrough; it strips every key except lanes from the first argument, before returning it.

Since (1) is right, no answer needed here.

5 & 6: These are a bit broad. I'd recommend asking a new question or checking MDN's page on arrow functions if you want to find out all there is to know. To answer for this specific case: the () on the argument is needed because the arguments are more complex than a single identifier, the {} in the arguments are for destructuring, the () on the body is to distinguish between an object literal and a block consisting only of the single statement lanes, and the {} in the body creates an object literal.

If you're wondering exactly what the (somewhat densely-coded) arrow function does, by the way, it does roughly the same thing as the following (give or take a few currently-irrelevant quirks of arrow functions):

function(obj) {
    return { lanes: obj.lanes };
}


问:
find largest value of a tuple element c++
I was wondering if there is a succinct way of finding the max value of one of the elements in a vector of tuples. e.g. for the following, say I want to find the largest second value of the tuple in the vector of tuples.

```<code>vector<tuple<int, int>> foo = { {12,1},{12,5},{5,6} };
</code>```

The result should be 6.

One way I could do this would be something like:

```<code>vector<double> allFoo;
for (int i = 0; i != size(foo); i++) {
    allFoo.emplace_back(get<1>(foo[i]));
}
double maxVal = *max_element(allFoo.begin(), allFoo.end());
</code>```

I feel though, that because you are essentially iterating over things twice, this could be done much more simply?

My tuple skills are a bit limited and it seems like you should be able to do some kind of max_element directly on foo...

答:
Use max_element with a custom predicate:

```<code>auto maxVal = get<1>(*max_element(foo.begin(), foo.end(),
                      [](auto& l, auto& r) {return get<1>(l) < get<1>(r);}));
</code>```

Body:
I was wondering if there is a succinct way of finding the max value of one of the elements in a vector of tuples. e.g. for the following, say I want to find the largest second value of the tuple in the vector of tuples.

vector<tuple<int, int>> foo = { {12,1},{12,5},{5,6} };

The result should be 6.

One way I could do this would be something like:

vector<double> allFoo;
for (int i = 0; i != size(foo); i++) {
    allFoo.emplace_back(get<1>(foo[i]));
}
double maxVal = *max_element(allFoo.begin(), allFoo.end());

I feel though, that because you are essentially iterating over things twice, this could be done much more simply?

My tuple skills are a bit limited and it seems like you should be able to do some kind of max_element directly on foo...

Body:
Use max_element with a custom predicate:

auto maxVal = get<1>(*max_element(foo.begin(), foo.end(),
                      [](auto& l, auto& r) {return get<1>(l) < get<1>(r);}));


答:
In one pass, with custom comparer:</p>

```<code>std::vector<std::tuple<int, int>> foo = { {12,1},{12,5},{5,6} };

const auto less_by_second = [](const auto& lhs, const auto& rhs)
    { return std::get<1>(lhs) < std::get<1>(rhs); };
const double maxVal = std::get<1>(*std::max_element(foo.begin(), foo.end(), less_by_second));
</code>```

Title: find largest value of a tuple element c++

Body:
In one pass, with custom comparer:

std::vector<std::tuple<int, int>> foo = { {12,1},{12,5},{5,6} };

const auto less_by_second = [](const auto& lhs, const auto& rhs)
    { return std::get<1>(lhs) < std::get<1>(rhs); };
const double maxVal = std::get<1>(*std::max_element(foo.begin(), foo.end(), less_by_second));


问:
How to initialize List<String> object in Java?
I can not initialize a List as in the following code:

```<code>List<String> supplierNames = new List<String>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
System.out.println(supplierNames.get(1));
</code>```

I face the following error:

Cannot instantiate the type List<String>

How can I instantiate List<String>?

答:
Can't instantiate an interface but there are few implementations:

JDK2

```<code>List<String> list = Arrays.asList("one", "two", "three");
</code>```

JDK7

```<code>//diamond operator
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
</code>```

JDK8

```<code>List<String> list = Stream.of("one", "two", "three").collect(Collectors.toList());
</code>```

JDK9

```<code>// creates immutable lists, so you can't modify such list
List<String> immutableList = List.of("one", "two", "three");

// if we want mutable list we can copy content of immutable list
// to mutable one for instance via copy-constructor (which creates shallow copy)
List<String> mutableList = new ArrayList<>(List.of("one", "two", "three"));
</code>```

Plus there are lots of other ways supplied by other libraries like Guava.

```<code>List<String> list = Lists.newArrayList("one", "two", "three");
</code>```

Body:
I can not initialize a List as in the following code:

List<String> supplierNames = new List<String>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
System.out.println(supplierNames.get(1));

I face the following error:

Cannot instantiate the type List<String>

How can I instantiate List<String>?

Body:
Can't instantiate an interface but there are few implementations:

JDK2

List<String> list = Arrays.asList("one", "two", "three");

JDK7

//diamond operator
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");

JDK8

List<String> list = Stream.of("one", "two", "three").collect(Collectors.toList());

JDK9

// creates immutable lists, so you can't modify such list
List<String> immutableList = List.of("one", "two", "three");

// if we want mutable list we can copy content of immutable list
// to mutable one for instance via copy-constructor (which creates shallow copy)
List<String> mutableList = new ArrayList<>(List.of("one", "two", "three"));

Plus there are lots of other ways supplied by other libraries like Guava.

List<String> list = Lists.newArrayList("one", "two", "three");


问:
how do i format my JSON responce in PHP to look like this
My PHP code:

```<code>require ("connect.php");

$input = $_GET["query"];
$data = array();

$query = mysql_query("SELECT `abbr` FROM `states_list` WHERE `abbr` LIKE '{$input}%'") or die(mysql_error());
while ($obj = mysql_fetch_object($query)) {
    //$json = array();
    //$json['query'] = $input;
    //$json['suggestion'] = $row['abbr'];
    $json[] = $obj;
    $data = array("query"=>"$input", "suggestion"=>array($obj));
}
header("Content-type: application/json");
//echo json_encode($data);
echo '{"query":'.$input.' "suggestion":'.json_encode($json).'}';
</code>```

This is my actual response:

```<code>{"query":c "suggestion":[{"abbr":"CA"},{"abbr":"CO"},{"abbr":"CT"}]}
</code>```

This is how I would like it to look like:

```<code>{"query":c "suggestion":["CA","CO","CT"]}
</code>```

I can't seem to figure out the right way to arrange the output to get what I want ;(

答: Try changing your $json[] = $obj; to $json[] = $obj->abbr;.

Body:
My PHP code:

require ("connect.php");

$input = $_GET["query"];
$data = array();

$query = mysql_query("SELECT `abbr` FROM `states_list` WHERE `abbr` LIKE '{$input}%'") or die(mysql_error());
while ($obj = mysql_fetch_object($query)) {
    //$json = array();
    //$json['query'] = $input;
    //$json['suggestion'] = $row['abbr'];
    $json[] = $obj;
    $data = array("query"=>"$input", "suggestion"=>array($obj));
}
header("Content-type: application/json");
//echo json_encode($data);
echo '{"query":'.$input.' "suggestion":'.json_encode($json).'}';

This is my actual response:

{"query":c "suggestion":[{"abbr":"CA"},{"abbr":"CO"},{"abbr":"CT"}]}

This is how I would like it to look like:

{"query":c "suggestion":["CA","CO","CT"]}

I can't seem to figure out the right way to arrange the output to get what I want ;(


问:
GCC, compare the effect of using -O2 and using all the optimization flags it turns on
From gcc5.4 documentation, it says

-O2 turns on all optimization flags specified by -O. It also turns on the following optimization flags:

-fthread-jumps
            -falign-functions  -falign-jumps
            -falign-loops  -falign-labels
            -fcaller-saves
            -fcrossjumping
            -fcse-follow-jumps, etc

It seems that using -O2 has the same effect of using all the 83 optimization flags turned on by -O2 in gcc 5.4.0 on the performance of the test programs.

However, I compare the running time of the executable files test1 and test2 obtained by

gcc-5.4 -O2 test.c -o test1

and

gcc-5.4 -fauto-inc-dec
  -fbranch-count-reg
  -fcombine-stack-adjustments
  -fcompare-elim ... -fthread-jumps -falign-functions ...(all the 83 flags) test.c -o test2

I tested on 20 random generated c programs and running each test case 100000 times to make sure the measurement of running time is accurate enough. But the result is that using -O2 is averagely about 60% faster than using all the 83 flags.

I am really confused why the effect of using -O2 is not equivalent to using all the optimization flags it turns on.

I must misunderstood something, but I couldn't find any explanation yet. I'd appreciate any help. Thanks a lot.

答:
The optimisation level affects decisions in other parts of the compiler besides determining which passes get run. These can be during mandatory processes like transforming between internal representations of the code, register allocation etc, so the optimisation level is not exactly equivalent to a set of switches enabling every compiler pass.
Look at this thread for some discussion on this topic.</p>


问:
execute script on remote using curl
I uploaded a file script.cmd to a Windows FTP server via curl.

No I'd like to execute this script on the remote server via curl.
When I just do this:

```<code>curl <FTPURL> -Q 'call ./path/to/my/script.cmd'
</code>```

then I get a 500 Command not understood.

What's the correct way to do this?

答: You can not run a command/script via ftp (at least not that I've ever seen). If you have a web server on the same box or you use curl to call the script via http(s) or you can write a script that ssh's into the box and executes the command, see Ssh and run command upon connection in another question for help.</p>

Title: execute script on remote using curl

Body:
I uploaded a file script.cmd to a Windows FTP server via curl.

No I'd like to execute this script on the remote server via curl.
When I just do this:

curl <FTPURL> -Q 'call ./path/to/my/script.cmd'

then I get a 500 Command not understood.

What's the correct way to do this?


问:
Date comparison in mongodb
I want to retrieve all the documents after a particular date.
My database has date as - DateAdded:"2014-12-17 10:03:46.000Z"

I wrote the following query-

```<code>db.collection.find({DateAdded:{"$lte":new Date("2015-06-17 10:03:46.000Z")}})
</code>```

But the results doesn't fetches any record even though there are records for the dates upto 2015-06-24.

答:
You can use this:

```<code>db.collection.find({DateAdded:{"$lte":new Date("2017-11-01")}})
</code>```

It will convert your date format into this:

```<code>ISODate("2017-11-01T00:00:00Z")
</code>```

Title: Date comparison in mongodb

Body:
I want to retrieve all the documents after a particular date.
My database has date as - DateAdded:"2014-12-17 10:03:46.000Z"

I wrote the following query-

db.collection.find({DateAdded:{"$lte":new Date("2015-06-17 10:03:46.000Z")}})

But the results doesn't fetches any record even though there are records for the dates upto 2015-06-24.

Body:
You can use this:

db.collection.find({DateAdded:{"$lte":new Date("2017-11-01")}})

It will convert your date format into this:

ISODate("2017-11-01T00:00:00Z")


问:
Retrieving source code using XMLhttpRequest in javascript
I am trying to get the source code of a website by using XMLhttpRequest in javascript, but I cannot get the response. How do I get source code using XMLhttpRequest? Here is what I have right now:</p>

```<code><script language="Javascript" type="text/javascript">
var req = new XMLHttpRequest();
req.open(
    "GET",
    "http://www.google.com",
    true);
req.onreadystatechange = statusListener;
req.send(null);

function statusListener()
{
if (req.readyState == 4)
    {
        var docx=req.responseXML;
        alert(docx);
    }
}
</script>
</code>```

答: You set up the XHR object in a variable called "req", but then your callback uses "xmlhttp".</p>


问:
How to set session configuration in example CNN Estimator for MNIST (built with tf.layers)
I am new to TensorFlow and learning about how to implement CNN (Convolutional Neural Networks). I am using this official example (code). When I try to run it on GPU it gives cuda_error_out_of_memory, as it tries to allocate the entire GPU memory available. I ran it on CPU by setting CUDA_VISIBLE_DEVICES="" environment variable and it worked fine but took lot of time.

I looked for solution to cuda_error_out_of_memory and found it can be mitigated by setting config.gpu_options.allow_growth = True or config.gpu_options.per_process_gpu_memory_fraction = in the tf session.

Question: In the code I shared above for CNN where do I set the session configuration as I don't see any session.run() type of command. I assume its being called internally in the layer methods. So, where do it set it? Is there any way I can set session configuration globally for one file?

答:
You can add any configuration in the Estimator's constructor: </p>

```<code>gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)
config = tf.ConfigProto(gpu_options=gpu_options)
mnist_classifier = tf.estimator.Estimator(
    model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model", session_config=config)
</code>```

Body:
You can add any configuration in the Estimator's constructor:

gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)
config = tf.ConfigProto(gpu_options=gpu_options)
mnist_classifier = tf.estimator.Estimator(
    model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model", session_config=config)


问:
React functional props
Let me show you an example first:

<List hidden={this.state.hideList} />
```

<p>For this case I would like <code>hidden</code> prop to function in the following way: if value is true – hide component or show otherwise. And <code>List</code> shouldn't be aware about this prop.</p>

<p>I don't know much about React internals, but it seems to be possible. We just need to extended <code>React.Component</code> class. Maybe extending globally with all functional props isn't good idea, but having something like this at the top would be nice:</p>

<pre class="lang-js prettyprint-override"><code>import { ReactComponent } from 'react'
import extend, { hidden } from 'react-functional-props'
const Component = extend(ReactComponent, hidden)
</code>```

It reminds me directives in Angular.js, but here we are able to combine them.

答:
You can just return null or undefined in the render method to prevent it from rendering, or use a conditional class to hide it, like this:

```<code>return !this.state.hideList && <List />;
</code>```

And about the

react-functional-props

In React, you can use higher order component (HOC) to achieve what you need, for example:

```<code>const Hideable = Component => (props) => {
  const { isHidden, ...otherProps } = props;

  return !isHidden && (<Component {...otherProps} />);
};

const HideableList = Hideable(List);

...

return (
  <div>
    <HideableList isHidden={this.state.hideList} /> // The isHidden props is handled by the HOC
  </div>
);
</code>```

But for a simple use case like this, I think just handle the hide and show in the parent component is much more clearer.

Title: React functional props

Body:
Let me show you an example first:

<List hidden={this.state.hideList} />

For this case I would like hidden prop to function in the following way: if value is true – hide component or show otherwise. And List shouldn't be aware about this prop.

I don't know much about React internals, but it seems to be possible. We just need to extended React.Component class. Maybe extending globally with all functional props isn't good idea, but having something like this at the top would be nice:

import { ReactComponent } from 'react'
import extend, { hidden } from 'react-functional-props'
const Component = extend(ReactComponent, hidden)

It reminds me directives in Angular.js, but here we are able to combine them.

Body:
You can just return null or undefined in the render method to prevent it from rendering, or use a conditional class to hide it, like this:

return !this.state.hideList && <List />;

And about the

react-functional-props

In React, you can use higher order component (HOC) to achieve what you need, for example:

const Hideable = Component => (props) => {
  const { isHidden, ...otherProps } = props;

  return !isHidden && (<Component {...otherProps} />);
};

const HideableList = Hideable(List);

...

return (
  <div>
    <HideableList isHidden={this.state.hideList} /> // The isHidden props is handled by the HOC
  </div>
);

But for a simple use case like this, I think just handle the hide and show in the parent component is much more clearer.


问:
SQL Server Update Field Max Value Subset of Data
I'm trying to update a filed based on a subset of data within the table. If an assembly requires 3 components that have varying arrival dates, but can only be assembled once all three have arrived, how do I update the completed field? The Complete field would need to be the Max of the DateAdd between the like assembly, but I don't know how to define the WHERE statement to compare based on assembly.

Sample Data

```<code>SN      Assembly  Arrival       ProcessingDays
1000    A1        2017-07-03    2
1001    A1        2017-06-02    2
1002    A1        2017-05-01    2
1003    A2        2017-12-15    2
1004    A3        2017-07-03    2
1005    A3        2017-06-02    2
1006    A3        2017-05-01    2
</code>```

Desired Output

```<code>SN      Assembly  Arrival       ProcessingDays  Complete
1000    A1        2017-07-03    2               2017-07-05
1001    A1        2017-06-02    2               2017-07-05
1002    A1        2017-05-01    2               2017-07-05
1003    A2        2017-12-15    2               2017-12-17
1004    A3        2017-09-03    2               2017-09-05
1005    A3        2017-08-02    2               2017-09-05
1006    A3        2017-07-01    2               2017-09-05
</code>```

答:
I don't know if you really want to update your table or just generate the Complete column, but the following CTE should be on the right track.  The trick baked into the cake with your question is that the number of processing days for the most recent record of each assembly also has to be identified, in addition to the max date.  For this, I use a two step CTE below.

```<code>WITH cte1 AS (
    SELECT SN, Assembly, Arrival, ProcessingDays,
        ROW_NUMBER() OVER (PARTITION BY Assembly ORDER BY Arrival DESC) rn
    FROM yourTable
),
cte2 AS (
    SELECT t1.SN, t1.Assembly, t1.Arrival, t1.ProcessingDays, t1.Complete,
        DATEADD(dd, t2.ProcessingDays, t2.Arrival) AS NewComplete
    FROM yourTable t1
    INNER JOIN cte1 t2
        ON t1.Assembly = t2.Assembly
    WHERE
        t2.rn = 1
)
</code>```

CTEs are useful in so many ways, including making it easy to update a table using complex logic, but in an easy way.  Now we can update your Complete column as follows:

```<code>UPDATE cte2
SET Complete = NewComplete;
</code>```

This is a blanket update, which is what your question seems to imply what you want, but you are free to add a WHERE clause to the above update if that makes sense.

Body:
I'm trying to update a filed based on a subset of data within the table. If an assembly requires 3 components that have varying arrival dates, but can only be assembled once all three have arrived, how do I update the completed field? The Complete field would need to be the Max of the DateAdd between the like assembly, but I don't know how to define the WHERE statement to compare based on assembly.

Sample Data

SN      Assembly  Arrival       ProcessingDays
1000    A1        2017-07-03    2
1001    A1        2017-06-02    2
1002    A1        2017-05-01    2
1003    A2        2017-12-15    2
1004    A3        2017-07-03    2
1005    A3        2017-06-02    2
1006    A3        2017-05-01    2

Desired Output

SN      Assembly  Arrival       ProcessingDays  Complete
1000    A1        2017-07-03    2               2017-07-05
1001    A1        2017-06-02    2               2017-07-05
1002    A1        2017-05-01    2               2017-07-05
1003    A2        2017-12-15    2               2017-12-17
1004    A3        2017-09-03    2               2017-09-05
1005    A3        2017-08-02    2               2017-09-05
1006    A3        2017-07-01    2               2017-09-05

Body:
I don't know if you really want to update your table or just generate the Complete column, but the following CTE should be on the right track.  The trick baked into the cake with your question is that the number of processing days for the most recent record of each assembly also has to be identified, in addition to the max date.  For this, I use a two step CTE below.

WITH cte1 AS (
    SELECT SN, Assembly, Arrival, ProcessingDays,
        ROW_NUMBER() OVER (PARTITION BY Assembly ORDER BY Arrival DESC) rn
    FROM yourTable
),
cte2 AS (
    SELECT t1.SN, t1.Assembly, t1.Arrival, t1.ProcessingDays, t1.Complete,
        DATEADD(dd, t2.ProcessingDays, t2.Arrival) AS NewComplete
    FROM yourTable t1
    INNER JOIN cte1 t2
        ON t1.Assembly = t2.Assembly
    WHERE
        t2.rn = 1
)

CTEs are useful in so many ways, including making it easy to update a table using complex logic, but in an easy way.  Now we can update your Complete column as follows:

UPDATE cte2
SET Complete = NewComplete;

This is a blanket update, which is what your question seems to imply what you want, but you are free to add a WHERE clause to the above update if that makes sense.


问:
Count milliseconds between two times
I need an algorithm that counts milliseconds between these times

```<code>HH:MM:SS,MS  --> HH:MM:SS,MS

00:08:50,800 --> 00:08:55,250
</code>```

I write a java code for 4 times but I think I did not understand the idea, I searched for it but all solutions used a libraries and I do not want to use a library.

Here is the java code I wrote, but it does not give me correct offset

```<code>private int findOffset(Time t1, Time t2) {
        int offset = 0;
        int diffHH = (t2.getHH() - t1.getHH());
        int diffMM = (t2.getMM() - t1.getMM());
        int diffSS = (t2.getSS() - t1.getSS());
        int diffMS = (t2.getMS() - t1.getMS());
        if (diffHH != 0) {
            if (diffHH < 0) {
                diffHH = 24 - t1.getHH() + t2.getHH();
            }
            offset += (3600000 * diffHH);
        }

        if (diffMM != 0) {
            if (diffMM < 0) {
                diffMM = 60 - t1.getMM() + t2.getMM();
            }
            offset += (60000 * diffMM);
        }
        if (diffSS != 0) {
            if (diffSS < 0) {
                diffSS = 60 - t1.getSS() + t2.getSS();
            }
            offset += (1000 * diffSS);
        }

        if (diffMS != 0) {

            if (diffMS < 0) {
                diffMS =  t1.getMS() + t2.getMS();
            }

            offset -= diffMS;
        }

        return offset;
    }
</code>```

here is another code

```<code>private int findOffset2(Time t1, Time t2) {
        int offset = 0;
        int hh1 = t1.getHH(), hh2 = t2.getHH();
        int mm1 = t1.getMM(), mm2 = t2.getMM();
        int ss1 = t1.getSS(), ss2 = t2.getSS();
        int ms1 = t1.getMS(), ms2 = t2.getMS();

        while (hh1 != hh2 || mm1 != mm2
                || ss1 != ss2 || ms1 != ms2) {
            offset++;

            ms1++;
            while (ms1 >= 1000) {
                ss1++;

                while (ss1 >= 60) {
                    ss1 -= 60;
                    mm1++;
                }

                while (mm1 >= 60) {
                    mm1 -= 60;
                    hh1++;
                }

                ms1 -= 1000;
            }

            if(hh1 == hh2 && mm1 == mm2
                && ss1 == ss2 && ms1 == ms2){
                  System.out.println("test");
                }

        }

        return offset;
    }
</code>```

答:
```<code>private int findOffset(Time t1, Time t2) {
    int hh1 = t1.getHH(), hh2 = t2.getHH();
    int mm1 = t1.getMM(), mm2 = t2.getMM();
    int ss1 = t1.getSS(), ss2 = t2.getSS();
    int ms1 = t1.getMS(), ms2 = t2.getMS();

    int offset = ((((hh2 - hh1) * 60) + (mm2 - mm1)) * 60) + (ss2 - ss1)) * 1000 + (ms2 - ms1);

    if (offset < 0)
        offset += 24*60*60*1000;
    return offset;
}
</code>```

Note that this always gives an answer in the range 0 to 23h 59m 59.999ms. The question didn't specify any dates for the two given times; therefore, the real answer could be + or - N days (where N can be any integer).

Title: Count milliseconds between two times

Body:
I need an algorithm that counts milliseconds between these times

HH:MM:SS,MS  --> HH:MM:SS,MS

00:08:50,800 --> 00:08:55,250

I write a java code for 4 times but I think I did not understand the idea, I searched for it but all solutions used a libraries and I do not want to use a library.

Here is the java code I wrote, but it does not give me correct offset

private int findOffset(Time t1, Time t2) {
        int offset = 0;
        int diffHH = (t2.getHH() - t1.getHH());
        int diffMM = (t2.getMM() - t1.getMM());
        int diffSS = (t2.getSS() - t1.getSS());
        int diffMS = (t2.getMS() - t1.getMS());
        if (diffHH != 0) {
            if (diffHH < 0) {
                diffHH = 24 - t1.getHH() + t2.getHH();
            }
            offset += (3600000 * diffHH);
        }

        if (diffMM != 0) {
            if (diffMM < 0) {
                diffMM = 60 - t1.getMM() + t2.getMM();
            }
            offset += (60000 * diffMM);
        }
        if (diffSS != 0) {
            if (diffSS < 0) {
                diffSS = 60 - t1.getSS() + t2.getSS();
            }
            offset += (1000 * diffSS);
        }

        if (diffMS != 0) {

            if (diffMS < 0) {
                diffMS =  t1.getMS() + t2.getMS();
            }

            offset -= diffMS;
        }

        return offset;
    }

here is another code

private int findOffset2(Time t1, Time t2) {
        int offset = 0;
        int hh1 = t1.getHH(), hh2 = t2.getHH();
        int mm1 = t1.getMM(), mm2 = t2.getMM();
        int ss1 = t1.getSS(), ss2 = t2.getSS();
        int ms1 = t1.getMS(), ms2 = t2.getMS();

        while (hh1 != hh2 || mm1 != mm2
                || ss1 != ss2 || ms1 != ms2) {
            offset++;

            ms1++;
            while (ms1 >= 1000) {
                ss1++;

                while (ss1 >= 60) {
                    ss1 -= 60;
                    mm1++;
                }

                while (mm1 >= 60) {
                    mm1 -= 60;
                    hh1++;
                }

                ms1 -= 1000;
            }

            if(hh1 == hh2 && mm1 == mm2
                && ss1 == ss2 && ms1 == ms2){
                  System.out.println("test");
                }

        }

        return offset;
    }

Body:
private int findOffset(Time t1, Time t2) {
    int hh1 = t1.getHH(), hh2 = t2.getHH();
    int mm1 = t1.getMM(), mm2 = t2.getMM();
    int ss1 = t1.getSS(), ss2 = t2.getSS();
    int ms1 = t1.getMS(), ms2 = t2.getMS();

    int offset = ((((hh2 - hh1) * 60) + (mm2 - mm1)) * 60) + (ss2 - ss1)) * 1000 + (ms2 - ms1);

    if (offset < 0)
        offset += 24*60*60*1000;
    return offset;
}

Note that this always gives an answer in the range 0 to 23h 59m 59.999ms. The question didn't specify any dates for the two given times; therefore, the real answer could be + or - N days (where N can be any integer).


问:
Magento 1.9 categories not loading after import
I'm currently stuck at my magento shop and I can't find a solution. I want to import almost 600.000 products. The process of it is really slow. The more product are in the system, the slower the import of new products works. I also can't open some category pages. Its simply not loading.

Any idea what could be the problem?

答:
You should look into https://github.com/avstudnitz/AvS_FastSimpleImport

This one is based on Mage_ImportExport_Model_Import_Entity_Product and is therefore much faster, than instantiating new product model on each iteration


问:
Unable to get any data when spark streaming program in run taking source as textFileStream
I am running following code on Spark shell

```<code> >`spark-shell
scala> import org.apache.spark.streaming._
import org.apache.spark.streaming._

scala> import org.apache.spark._
import org.apache.spark._

scala> object sparkClient{
 | def main(args : Array[String])
 | {
 | val ssc = new StreamingContext(sc,Seconds(1))
 | val Dstreaminput = ssc.textFileStream("hdfs:///POC/SPARK/DATA/*")
 | val transformed = Dstreaminput.flatMap(word => word.split(" "))
 | val mapped = transformed.map(word => if(word.contains("error"))(word,"defect")else(word,"non-defect"))
 | mapped.print()
 | ssc.start()
 | ssc.awaitTermination()
 | }
 | }
defined object sparkClient

scala> sparkClient.main(null)
</code>```

Output is blank as follows. No file is read and no streaming took place.

Time: 1510663547000 ms

Time: 1510663548000 ms

Time: 1510663549000 ms

Time: 1510663550000 ms

Time: 1510663551000 ms

Time: 1510663552000 ms

Time: 1510663553000 ms

Time: 1510663554000 ms

Time: 1510663555000 ms

The path which I have given as input in the above code is as follows:

```<code>[hadoopadmin@master ~]$ hadoop fs -ls /POC/SPARK/DATA/
17/11/14 18:04:32 WARN util.NativeCodeLoader: Unable to load native-hadoop
library for your platform... using builtin-java classes where applicable
Found 3 items
-rw-r--r--   2 hadoopadmin supergroup      17881 2017-09-21 11:02
 /POC/SPARK/DATA/LICENSE
-rw-r--r--   2 hadoopadmin supergroup      24645 2017-09-21 11:04
 /POC/SPARK/DATA/NOTICE
 -rw-r--r--   2 hadoopadmin supergroup        845 2017-09-21 12:35
 /POC/SPARK/DATA/confusion.txt
</code>```

Could anyone please explain where I am going wrong? Or is there anything wrong with the syntax(although I did not encounter any error) as I am new to spark?

答:
textFileStream won't read pre-existing data. It will include only new files:

created in the dataDirectory by atomically moving or renaming them into the data directory.

https://spark.apache.org/docs/latest/streaming-programming-guide.html#basic-sources

Body:
I am running following code on Spark shell

 >`spark-shell
scala> import org.apache.spark.streaming._
import org.apache.spark.streaming._

scala> import org.apache.spark._
import org.apache.spark._

scala> object sparkClient{
 | def main(args : Array[String])
 | {
 | val ssc = new StreamingContext(sc,Seconds(1))
 | val Dstreaminput = ssc.textFileStream("hdfs:///POC/SPARK/DATA/*")
 | val transformed = Dstreaminput.flatMap(word => word.split(" "))
 | val mapped = transformed.map(word => if(word.contains("error"))(word,"defect")else(word,"non-defect"))
 | mapped.print()
 | ssc.start()
 | ssc.awaitTermination()
 | }
 | }
defined object sparkClient

scala> sparkClient.main(null)

Output is blank as follows. No file is read and no streaming took place.

Time: 1510663547000 ms

Time: 1510663548000 ms

Time: 1510663549000 ms

Time: 1510663550000 ms

Time: 1510663551000 ms

Time: 1510663552000 ms

Time: 1510663553000 ms

Time: 1510663554000 ms

Time: 1510663555000 ms

The path which I have given as input in the above code is as follows:

[hadoopadmin@master ~]$ hadoop fs -ls /POC/SPARK/DATA/
17/11/14 18:04:32 WARN util.NativeCodeLoader: Unable to load native-hadoop
library for your platform... using builtin-java classes where applicable
Found 3 items
-rw-r--r--   2 hadoopadmin supergroup      17881 2017-09-21 11:02
 /POC/SPARK/DATA/LICENSE
-rw-r--r--   2 hadoopadmin supergroup      24645 2017-09-21 11:04
 /POC/SPARK/DATA/NOTICE
 -rw-r--r--   2 hadoopadmin supergroup        845 2017-09-21 12:35
 /POC/SPARK/DATA/confusion.txt

Could anyone please explain where I am going wrong? Or is there anything wrong with the syntax(although I did not encounter any error) as I am new to spark?


问:
Cannot use object of type Google_Auth_LoginTicket as array
I was performing Google Sign in on Android Application for the first time. At the client side, I obtained the access token and sent to the PHP server via POST.

By referring to Google's Documentation, the code I used in backend is as follows:

```<code>$id_token = $_POST['id_token'];

$CLIENT_ID = "** MY WEB APPLICATION CLIENT ID **";

$client = new Google_Client(['client_id' => $CLIENT_ID]);
$client->setAuthConfigFile('client_secret.json');

...

$payload = $client->verifyIdToken($id_token);
if ($payload) {
    $userid = $payload['sub'];
} else {
    echo "Invalid Token";
}
</code>```

When obtaining user id, the error is : "Cannot use object of type Google_Auth_LoginTicket as array"

I am pretty new to Google sign in. Please point out what all has gone wrong.

答:
Found It. I made some modifications to the code

```<code>$token_data = $client->verifyIdToken($id_token)->getAttributes();
$user_id = $token_data['payload']['sub'];
</code>```

Now the user id is retrieved fine.

Body:
I was performing Google Sign in on Android Application for the first time. At the client side, I obtained the access token and sent to the PHP server via POST.

By referring to Google's Documentation, the code I used in backend is as follows:

$id_token = $_POST['id_token'];

$CLIENT_ID = "** MY WEB APPLICATION CLIENT ID **";

$client = new Google_Client(['client_id' => $CLIENT_ID]);
$client->setAuthConfigFile('client_secret.json');

...

$payload = $client->verifyIdToken($id_token);
if ($payload) {
    $userid = $payload['sub'];
} else {
    echo "Invalid Token";
}

When obtaining user id, the error is : "Cannot use object of type Google_Auth_LoginTicket as array"

I am pretty new to Google sign in. Please point out what all has gone wrong.

Body:
Found It. I made some modifications to the code

$token_data = $client->verifyIdToken($id_token)->getAttributes();
$user_id = $token_data['payload']['sub'];

Now the user id is retrieved fine.