问:
JavaFx - Resize Rectangle
I am try to allow users to drag/resize a rectangle in javafx.
Rectangle in javafx uses TopLeft-X, Y, height and width to draw.

What I am trying to do is to have 4 handles at each corner of the rectangle to allow users to drag the handle. Which will result in resizing the rectangle.

My application throws a stackoverflow exception which I know is caused by the recursive call of the listener.

Did i forget something? Or is there some listener that is unnecessary?

```<code>public class Handler extends Circle
{
    private double deltaX;
    private double deltaY;

    private static final double DEFAULT_RADIUS = 10;
    private static final Color DEFAULT_COLOR = Color.GOLD;

    private DoubleProperty xProperty;
    private DoubleProperty yProperty;

    public Handler(DoubleProperty xProperty, DoubleProperty yProperty)
    {
        super(DEFAULT_RADIUS, DEFAULT_COLOR);

        this.xProperty = xProperty;
        this.yProperty = yProperty;

        init();
    }

    private void init()
    {
        setFill(DEFAULT_COLOR.deriveColor(1, 1, 1, 0.5));
        setStroke(DEFAULT_COLOR);
        setStrokeWidth(2);
        setStrokeType(StrokeType.OUTSIDE);

        centerXProperty().bind(xProperty);
        centerYProperty().bind(yProperty);

        setOnMousePressed(new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent mouseEvent)
            {
                mouseEvent.consume();

                deltaX = getCenterX() - mouseEvent.getX();
                deltaY = getCenterY() - mouseEvent.getY();

                getScene().setCursor(javafx.scene.Cursor.MOVE);
            }
        });

        setOnMouseReleased(new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent mouseEvent)
            {
                getScene().setCursor(javafx.scene.Cursor.HAND);
            }
        });

        setOnMouseEntered(new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent mouseEvent)
            {
                if (!mouseEvent.isPrimaryButtonDown())
                {
                    getScene().setCursor(javafx.scene.Cursor.HAND);
                }
            }
        });

        setOnMouseExited(new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent mouseEvent)
            {
                if (!mouseEvent.isPrimaryButtonDown())
                {
                    getScene().setCursor(javafx.scene.Cursor.DEFAULT);
                }
            }
        });

        setOnMouseDragged(new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent mouseEvent)
            {
                double newX = mouseEvent.getX() + deltaX;
                double newY = mouseEvent.getY() + deltaY;

                if (newX > 0 && newX < getScene().getWidth())
                {
                    xProperty.set(newX);
                }

                if (newY > 0 && newY < getScene().getHeight())
                {
                    yProperty.set(newY);
                }
            }
        });
    }

    //JavaFx Accessor and mutator
}

public class CustomRectangle extends Rectangle
{
    private DoubleProperty topRightX;
    private DoubleProperty topRightY;

    private DoubleProperty btmLeftX;
    private DoubleProperty btmLeftY;

    private DoubleProperty btmRightX;
    private DoubleProperty btmRightY;

    private DoubleProperty customeWidth;
    private DoubleProperty customHeight;

    public CustomRectangle()
    {
        super();
        init();
    }

    public CustomRectangle(double x, double y, double width, double height)
    {
        super(x, y, width, height);
        init();
    }

    public CustomRectangle(double width, double height, Paint fill)
    {
        super(width, height, fill);
        init();
    }

    public CustomRectangle(double width, double height)
    {
        super(width, height);
        init();
    }

    private void init()
    {
        topRightX = new SimpleDoubleProperty();
        topRightY = new SimpleDoubleProperty();

        btmLeftX = new SimpleDoubleProperty();
        btmLeftY = new SimpleDoubleProperty();

        btmRightX = new SimpleDoubleProperty();
        btmRightY = new SimpleDoubleProperty();

        topRightX.addListener((observable, oldValue, newValue) ->
        {
            this.setWidth(this.getWidth() + (newValue.doubleValue() - oldValue.doubleValue()));
        });

        topRightY.addListener((observable, oldValue, newValue) ->
        {
            this.setY(newValue.doubleValue());
            this.setHeight(this.getHeight() - (newValue.doubleValue() - oldValue.doubleValue()));
        });

        btmLeftX.addListener((observable, oldValue, newValue) ->
        {
            this.setX(newValue.doubleValue());
            this.setWidth(this.getWidth() - (newValue.doubleValue() - oldValue.doubleValue()));
        });

        btmLeftY.addListener((observable, oldValue, newValue) ->
        {
            this.setY(newValue.doubleValue());
            this.setHeight(this.getHeight() + (newValue.doubleValue() - oldValue.doubleValue()));
        });

        btmRightX.addListener((observable, oldValue, newValue) ->
        {
            this.setWidth(this.getWidth() + (newValue.doubleValue() - oldValue.doubleValue()));
        });

        btmRightY.addListener((observable, oldValue, newValue) ->
        {
            this.setHeight(this.getHeight() + (newValue.doubleValue() - oldValue.doubleValue()));
        });

        this.xProperty().addListener((observable, oldValue, newValue) ->
        {
            btmLeftX.set(newValue.doubleValue());
            topRightX.set(newValue.doubleValue() + this.getWidth());
            btmRightX.set(newValue.doubleValue() + this.getWidth());
        });

        this.yProperty().addListener((observable, oldValue, newValue) ->
        {
            btmLeftY.set(newValue.doubleValue() + this.getHeight());
            topRightY.set(newValue.doubleValue());
            btmRightY.set(newValue.doubleValue() + this.getHeight());
        });

        this.widthProperty().addListener((observable, oldValue, newValue) ->
        {
            topRightX.set(this.getX() + (newValue.doubleValue() - oldValue.doubleValue()));
            btmRightX.set(this.getX() + (newValue.doubleValue() - oldValue.doubleValue()));
        });

        this.heightProperty().addListener((observable, oldValue, newValue) ->
        {
            btmLeftY.set(this.getY() + (newValue.doubleValue() - oldValue.doubleValue()));
            btmRightY.set(this.getY() + (newValue.doubleValue() - oldValue.doubleValue()));
        });

    }
    //JavaFx Accessor and Mutator
}

public class FeatureHelper
{
    private static double orgSceneX;
    private static double orgSceneY;

    private static double orgTranslateX;
    private static double orgTranslateY;

    public static CustomRectangle createDraggableRectangle(double x, double y, double width, double height,
            boolean resizeImage)
    {
        CustomRectangle rect = new CustomRectangle(x, y, width, height);

        // top left resize handle:
        Handler topLeftHandle = new Handler(rect.topLeftXProperty(), rect.topLeftYProperty());

        // top right resize handle:
        Handler topRightHandle = new Handler(rect.topRightXProperty(), rect.topRightYProperty());

        // bottom left resize handle:
        Handler btmLeftHandle = new Handler(rect.btmLeftXProperty(), rect.btmLeftYProperty());

        // bottom right resize handle:
        Handler btmRightHandle = new Handler(rect.btmRightXProperty(), rect.btmRightYProperty());

        // force circles to live in same parent as rectangle:
        rect.parentProperty().addListener((obs, oldParent, newParent) ->
        {
            for (Circle c : Arrays.asList(topLeftHandle, topRightHandle, btmLeftHandle, btmRightHandle))
            {
                if (newParent != null)
                {
                    ((Pane) newParent).getChildren().add(c);
                }
            }
        });

        rect.setOnMousePressed(event ->
        {
            event.consume();

            orgSceneX = event.getSceneX();
            orgSceneY = event.getSceneY();

            Node p = ((Node) (event.getSource()));

            orgTranslateX = p.getTranslateX();
            orgTranslateY = p.getTranslateY();
        });

        rect.setOnMouseDragged(event ->
        {
            double offsetX = event.getSceneX() - orgSceneX;
            double offsetY = event.getSceneY() - orgSceneY;

            double newTranslateX = orgTranslateX + offsetX;
            double newTranslateY = orgTranslateY + offsetY;

            Node p = ((Node) (event.getSource()));
            p.setTranslateX(newTranslateX);
            p.setTranslateY(newTranslateY);

            for(Circle circle : Arrays.asList(topLeftHandle, topRightHandle, btmLeftHandle, btmRightHandle))
            {
                circle.setTranslateX(newTranslateX);
                circle.setTranslateY(newTranslateY);
            }
        });

        return rect;
    }
}
</code>```

答:
You should have a look at this nice Example from karakullukcuhuseyin -->
https://github.com/karakullukcuhuseyin/JavaFX-ImageCropper
He extended the Rectangle Class as well and is using his custom Rectangle to select an area in an Image.</p>

Title: JavaFx - Resize Rectangle

Body:
I am try to allow users to drag/resize a rectangle in javafx.
Rectangle in javafx uses TopLeft-X, Y, height and width to draw.

What I am trying to do is to have 4 handles at each corner of the rectangle to allow users to drag the handle. Which will result in resizing the rectangle.

My application throws a stackoverflow exception which I know is caused by the recursive call of the listener.

Did i forget something? Or is there some listener that is unnecessary?

public class Handler extends Circle
{
    private double deltaX;
    private double deltaY;

    private static final double DEFAULT_RADIUS = 10;
    private static final Color DEFAULT_COLOR = Color.GOLD;

    private DoubleProperty xProperty;
    private DoubleProperty yProperty;

    public Handler(DoubleProperty xProperty, DoubleProperty yProperty)
    {
        super(DEFAULT_RADIUS, DEFAULT_COLOR);

        this.xProperty = xProperty;
        this.yProperty = yProperty;

        init();
    }

    private void init()
    {
        setFill(DEFAULT_COLOR.deriveColor(1, 1, 1, 0.5));
        setStroke(DEFAULT_COLOR);
        setStrokeWidth(2);
        setStrokeType(StrokeType.OUTSIDE);

        centerXProperty().bind(xProperty);
        centerYProperty().bind(yProperty);

        setOnMousePressed(new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent mouseEvent)
            {
                mouseEvent.consume();

                deltaX = getCenterX() - mouseEvent.getX();
                deltaY = getCenterY() - mouseEvent.getY();

                getScene().setCursor(javafx.scene.Cursor.MOVE);
            }
        });

        setOnMouseReleased(new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent mouseEvent)
            {
                getScene().setCursor(javafx.scene.Cursor.HAND);
            }
        });

        setOnMouseEntered(new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent mouseEvent)
            {
                if (!mouseEvent.isPrimaryButtonDown())
                {
                    getScene().setCursor(javafx.scene.Cursor.HAND);
                }
            }
        });

        setOnMouseExited(new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent mouseEvent)
            {
                if (!mouseEvent.isPrimaryButtonDown())
                {
                    getScene().setCursor(javafx.scene.Cursor.DEFAULT);
                }
            }
        });

        setOnMouseDragged(new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent mouseEvent)
            {
                double newX = mouseEvent.getX() + deltaX;
                double newY = mouseEvent.getY() + deltaY;

                if (newX > 0 && newX < getScene().getWidth())
                {
                    xProperty.set(newX);
                }

                if (newY > 0 && newY < getScene().getHeight())
                {
                    yProperty.set(newY);
                }
            }
        });
    }

    //JavaFx Accessor and mutator
}

public class CustomRectangle extends Rectangle
{
    private DoubleProperty topRightX;
    private DoubleProperty topRightY;

    private DoubleProperty btmLeftX;
    private DoubleProperty btmLeftY;

    private DoubleProperty btmRightX;
    private DoubleProperty btmRightY;

    private DoubleProperty customeWidth;
    private DoubleProperty customHeight;

    public CustomRectangle()
    {
        super();
        init();
    }

    public CustomRectangle(double x, double y, double width, double height)
    {
        super(x, y, width, height);
        init();
    }

    public CustomRectangle(double width, double height, Paint fill)
    {
        super(width, height, fill);
        init();
    }

    public CustomRectangle(double width, double height)
    {
        super(width, height);
        init();
    }

    private void init()
    {
        topRightX = new SimpleDoubleProperty();
        topRightY = new SimpleDoubleProperty();

        btmLeftX = new SimpleDoubleProperty();
        btmLeftY = new SimpleDoubleProperty();

        btmRightX = new SimpleDoubleProperty();
        btmRightY = new SimpleDoubleProperty();

        topRightX.addListener((observable, oldValue, newValue) ->
        {
            this.setWidth(this.getWidth() + (newValue.doubleValue() - oldValue.doubleValue()));
        });

        topRightY.addListener((observable, oldValue, newValue) ->
        {
            this.setY(newValue.doubleValue());
            this.setHeight(this.getHeight() - (newValue.doubleValue() - oldValue.doubleValue()));
        });

        btmLeftX.addListener((observable, oldValue, newValue) ->
        {
            this.setX(newValue.doubleValue());
            this.setWidth(this.getWidth() - (newValue.doubleValue() - oldValue.doubleValue()));
        });

        btmLeftY.addListener((observable, oldValue, newValue) ->
        {
            this.setY(newValue.doubleValue());
            this.setHeight(this.getHeight() + (newValue.doubleValue() - oldValue.doubleValue()));
        });

        btmRightX.addListener((observable, oldValue, newValue) ->
        {
            this.setWidth(this.getWidth() + (newValue.doubleValue() - oldValue.doubleValue()));
        });

        btmRightY.addListener((observable, oldValue, newValue) ->
        {
            this.setHeight(this.getHeight() + (newValue.doubleValue() - oldValue.doubleValue()));
        });

        this.xProperty().addListener((observable, oldValue, newValue) ->
        {
            btmLeftX.set(newValue.doubleValue());
            topRightX.set(newValue.doubleValue() + this.getWidth());
            btmRightX.set(newValue.doubleValue() + this.getWidth());
        });

        this.yProperty().addListener((observable, oldValue, newValue) ->
        {
            btmLeftY.set(newValue.doubleValue() + this.getHeight());
            topRightY.set(newValue.doubleValue());
            btmRightY.set(newValue.doubleValue() + this.getHeight());
        });

        this.widthProperty().addListener((observable, oldValue, newValue) ->
        {
            topRightX.set(this.getX() + (newValue.doubleValue() - oldValue.doubleValue()));
            btmRightX.set(this.getX() + (newValue.doubleValue() - oldValue.doubleValue()));
        });

        this.heightProperty().addListener((observable, oldValue, newValue) ->
        {
            btmLeftY.set(this.getY() + (newValue.doubleValue() - oldValue.doubleValue()));
            btmRightY.set(this.getY() + (newValue.doubleValue() - oldValue.doubleValue()));
        });

    }
    //JavaFx Accessor and Mutator
}

public class FeatureHelper
{
    private static double orgSceneX;
    private static double orgSceneY;

    private static double orgTranslateX;
    private static double orgTranslateY;

    public static CustomRectangle createDraggableRectangle(double x, double y, double width, double height,
            boolean resizeImage)
    {
        CustomRectangle rect = new CustomRectangle(x, y, width, height);

        // top left resize handle:
        Handler topLeftHandle = new Handler(rect.topLeftXProperty(), rect.topLeftYProperty());

        // top right resize handle:
        Handler topRightHandle = new Handler(rect.topRightXProperty(), rect.topRightYProperty());

        // bottom left resize handle:
        Handler btmLeftHandle = new Handler(rect.btmLeftXProperty(), rect.btmLeftYProperty());

        // bottom right resize handle:
        Handler btmRightHandle = new Handler(rect.btmRightXProperty(), rect.btmRightYProperty());

        // force circles to live in same parent as rectangle:
        rect.parentProperty().addListener((obs, oldParent, newParent) ->
        {
            for (Circle c : Arrays.asList(topLeftHandle, topRightHandle, btmLeftHandle, btmRightHandle))
            {
                if (newParent != null)
                {
                    ((Pane) newParent).getChildren().add(c);
                }
            }
        });

        rect.setOnMousePressed(event ->
        {
            event.consume();

            orgSceneX = event.getSceneX();
            orgSceneY = event.getSceneY();

            Node p = ((Node) (event.getSource()));

            orgTranslateX = p.getTranslateX();
            orgTranslateY = p.getTranslateY();
        });

        rect.setOnMouseDragged(event ->
        {
            double offsetX = event.getSceneX() - orgSceneX;
            double offsetY = event.getSceneY() - orgSceneY;

            double newTranslateX = orgTranslateX + offsetX;
            double newTranslateY = orgTranslateY + offsetY;

            Node p = ((Node) (event.getSource()));
            p.setTranslateX(newTranslateX);
            p.setTranslateY(newTranslateY);

            for(Circle circle : Arrays.asList(topLeftHandle, topRightHandle, btmLeftHandle, btmRightHandle))
            {
                circle.setTranslateX(newTranslateX);
                circle.setTranslateY(newTranslateY);
            }
        });

        return rect;
    }
}


来源: stackexchange

问:
how to parsing multiple json based on its index
i have a script like this

```<code>$scope.asd = angular.fromJson($scope.asd[0].jfk);
</code>```

but it only parse the object only on index 0,i want to parse all object based on the index on only at index 0 .

my pseucode

```<code>var i = get index;
for(k=0;k<i){
$scope.asd = angular.fromJson($scope.asd[0].jfk);
}
</code>```

how to do it in angularjs?

答:
You can do something like

```<code>var arr=angular.fromJson($scope.asd);
$scope.abc=arr.map(function(x){
   return x.jfk;
 });
//Now You can access all the jfk properties in $scope.abc like
console.log($scope.abc[i]);//i is the index
</code>```

Or you can simply do

```<code>$scope.asd=angular.fromJson($scope.asd);
//And access properties like
console.log($scope.asd[i].jfk); //i is the index
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i have a script like this

$scope.asd = angular.fromJson($scope.asd[0].jfk);

but it only parse the object only on index 0,i want to parse all object based on the index on only at index 0 .

my pseucode

var i = get index;
for(k=0;k<i){
$scope.asd = angular.fromJson($scope.asd[0].jfk);
}

how to do it in angularjs?

Body:
You can do something like

var arr=angular.fromJson($scope.asd);
$scope.abc=arr.map(function(x){
   return x.jfk;
 });
//Now You can access all the jfk properties in $scope.abc like
console.log($scope.abc[i]);//i is the index

Or you can simply do

$scope.asd=angular.fromJson($scope.asd);
//And access properties like
console.log($scope.asd[i].jfk); //i is the index


问:
UITableView content size not getting proper
I have UITableView for display for chat message list. I am using 5 type of different with dynamic height. Minimum cell height from 20 to maxHeight( approx 1000 px). UITable view cell dynamic height is set by "self.messageTableView.rowHeight = UITableViewAutomaticDimension".

What Should be common estimate row height.

After reload UITableView content size not getting properly. If user scroll then content size increased.

答:
To use UITableViewAutomaticDimension for dynamic height calculation, ensure

1 - Leading, Trailing, Top and Bottom constraints to cell are added correctly and not creating any conflicts

2 - Add cell.layoutIfNeeded() in cellForRowAt method of UITableViewDelegate

3 - You can give any height as estimatedRowHeight, 44 is the default value, but you can give 20(your minimum) as well.


问:
ngIf not working with ng-template
I want to show or hide a template based on the boolean value in Angular 4. Below are the HTML and code

--- This is inside Home.Component.HTML

```<code><ng-template [ngIf]="isSummaryViewVisbile" #pricebookView ></ng-template>
</code>```

---- This is inside HomeComponent

```<code>   isSummaryViewVisbile: boolean = true;
</code>```

Above code doesn't work, it always hides template although I'm assigning true.

Thanks in advance.

答:
The ng-template is an Angular element for rendering HTML. It is never displayed directly. In fact, before rendering the view, Angular replaces the  and its contents with a comment.If there is no structural directive and you merely wrap some elements in a ng-template, those elements disappear.

```<code><p>Hip!</p>
<ng-template>
  <p>Hip!</p> //would disappear
</ng-template>
<p>Hooray!</p>
</code>```

So the following code would work fine

```<code>isSummaryViewVisbile = true;

<ng-template [ngIf]="isSummaryViewVisbile" #pricebookView >
       Hello world.
</ng-template>
</code>```

But if you replace [ngIf] with *ngIf, same code would not work.

Because Internally, Angular translates the *ngIf attribute into a ng-template element, wrapped around the host element. For example

```<code><ng-template *ngIf="isSummaryViewVisbile" #pricebookView >
       Hello world.
</ng-template>
</code>```

Would be converted to-

```<code><ng-template [ngIf]="isSummaryViewVisbile">
      <ng-template #pricebookView >
           Hello world.
    </ng-template>
</ng-template>
</code>```

Now as we can see inner ng-template will always hide it's content.I hope this makes clear.

Demo: https://plnkr.co/edit/yB7PKx?p=preview

Title: ngIf not working with ng-template

Body:
I want to show or hide a template based on the boolean value in Angular 4. Below are the HTML and code

--- This is inside Home.Component.HTML

<ng-template [ngIf]="isSummaryViewVisbile" #pricebookView ></ng-template>

---- This is inside HomeComponent

   isSummaryViewVisbile: boolean = true;

Above code doesn't work, it always hides template although I'm assigning true.

Thanks in advance.

Body:
The ng-template is an Angular element for rendering HTML. It is never displayed directly. In fact, before rendering the view, Angular replaces the  and its contents with a comment.If there is no structural directive and you merely wrap some elements in a ng-template, those elements disappear.

<p>Hip!</p>
<ng-template>
  <p>Hip!</p> //would disappear
</ng-template>
<p>Hooray!</p>

So the following code would work fine

isSummaryViewVisbile = true;

<ng-template [ngIf]="isSummaryViewVisbile" #pricebookView >
       Hello world.
</ng-template>

But if you replace [ngIf] with *ngIf, same code would not work.

Because Internally, Angular translates the *ngIf attribute into a ng-template element, wrapped around the host element. For example

<ng-template *ngIf="isSummaryViewVisbile" #pricebookView >
       Hello world.
</ng-template>

Would be converted to-

<ng-template [ngIf]="isSummaryViewVisbile">
      <ng-template #pricebookView >
           Hello world.
    </ng-template>
</ng-template>

Now as we can see inner ng-template will always hide it's content.I hope this makes clear.

Demo: https://plnkr.co/edit/yB7PKx?p=preview


问:
Add cross browser for multiple packages using TestNG and Java
I am using xml file to run all my packages of a project parallel, how to add cross browser to this xml file:

<suite name="Web Smoke Tests" verbose="1" preserve-order="true"
parallel="tests" thread-count="4">
<test name="Test2">
    <classes>
        <class name="package.class2"></class>
    </classes>
</test>
<test name="Test1">
    <classes>
        <class name="package.class1"></class>
    </classes>
</test>
<test name="Test">
    <classes>
        <class name="package.class"></class>
    </classes>
</test>
```

答:
You can refer the following sample for achieving this:
Modify your xml file based on the below sample:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Parallel" thread-count="4" parallel="tests">
    <test name="SingleTestChrome">
        <parameter name="config" value="parallel.conf.json"/>
        <parameter name="environment" value="chrome"/>
        <classes>
            <class name="com.browserstack.SingleTest"/>
        </classes>
    </test>
    <test name="SingleTestFirefox">
        <parameter name="config" value="parallel.conf.json"/>
        <parameter name="environment" value="firefox"/>
        <classes>
            <class name="com.browserstack.SingleTest"/>
        </classes>
    </test>
    <test name="SingleTestSafari">
        <parameter name="config" value="parallel.conf.json"/>
        <parameter name="environment" value="safari"/>
        <classes>
            <class name="com.browserstack.SingleTest"/>
        </classes>
    </test>
    <test name="SingleTestIE">
        <parameter name="config" value="parallel.conf.json"/>
        <parameter name="environment" value="ie"/>
        <classes>
            <class name="com.browserstack.SingleTest"/>
        </classes>
    </test>
</suite>
```

<p>Sample Configuration file:</p>

```{
    "server": "hub-cloud.browserstack.com",
    "user": "BROWSERSTACK_USERNAME",
    "key": "BROWSERSTACK_ACCESS_KEY",
    "capabilities": {
        "build": "testng-browserstack",
        "name": "parallel_test",
        "browserstack.debug": true
    },
    "environments": {
        "chrome": {
            "browser": "chrome"
        },
        "firefox": {
            "browser": "firefox"
        },
        "safari": {
            "browser": "safari"
        },
        "ie": {
            "browser": "internet explorer"
        }
    }
}
```

Reference: https://github.com/browserstack/testng-browserstack

Body:
You can refer the following sample for achieving this:
Modify your xml file based on the below sample:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Parallel" thread-count="4" parallel="tests">
    <test name="SingleTestChrome">
        <parameter name="config" value="parallel.conf.json"/>
        <parameter name="environment" value="chrome"/>
        <classes>
            <class name="com.browserstack.SingleTest"/>
        </classes>
    </test>
    <test name="SingleTestFirefox">
        <parameter name="config" value="parallel.conf.json"/>
        <parameter name="environment" value="firefox"/>
        <classes>
            <class name="com.browserstack.SingleTest"/>
        </classes>
    </test>
    <test name="SingleTestSafari">
        <parameter name="config" value="parallel.conf.json"/>
        <parameter name="environment" value="safari"/>
        <classes>
            <class name="com.browserstack.SingleTest"/>
        </classes>
    </test>
    <test name="SingleTestIE">
        <parameter name="config" value="parallel.conf.json"/>
        <parameter name="environment" value="ie"/>
        <classes>
            <class name="com.browserstack.SingleTest"/>
        </classes>
    </test>
</suite>

Sample Configuration file:

{
    "server": "hub-cloud.browserstack.com",
    "user": "BROWSERSTACK_USERNAME",
    "key": "BROWSERSTACK_ACCESS_KEY",
    "capabilities": {
        "build": "testng-browserstack",
        "name": "parallel_test",
        "browserstack.debug": true
    },
    "environments": {
        "chrome": {
            "browser": "chrome"
        },
        "firefox": {
            "browser": "firefox"
        },
        "safari": {
            "browser": "safari"
        },
        "ie": {
            "browser": "internet explorer"
        }
    }
}

Reference: https://github.com/browserstack/testng-browserstack


问:
Remove script filename from url in silex
I'm trying to remove from the URL bar the index.php script name with htaccess. This is my htaccess file:

```<code><IfModule mod_rewrite.c>
Options -MultiViews

RewriteEngine On
RewriteRule ^ index.php [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^website\.com [NC]
RewriteRule ^(.*)$ https://website.com/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^www.website.com$
RewriteRule (.*) https://website.com/$1 [R=301,L]
</IfModule>
</code>```

But still the index.php in the URL like this:
https://website.com/index.php/url and need to be moved to https://website.com/url

答:
Ok solved using this code:</p>

```<code><IfModule mod_rewrite.c>
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s(.*)/index\.php [NC]
RewriteRule ^ %1 [R=301,L]
</IfModule>
</code>```

Body:
I'm trying to remove from the URL bar the index.php script name with htaccess. This is my htaccess file:

<IfModule mod_rewrite.c>
Options -MultiViews

RewriteEngine On
RewriteRule ^ index.php [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^website\.com [NC]
RewriteRule ^(.*)$ https://website.com/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^www.website.com$
RewriteRule (.*) https://website.com/$1 [R=301,L]
</IfModule>

But still the index.php in the URL like this:
https://website.com/index.php/url and need to be moved to https://website.com/url

Body:
Ok solved using this code:

<IfModule mod_rewrite.c>
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s(.*)/index\.php [NC]
RewriteRule ^ %1 [R=301,L]
</IfModule>


问:
Order of request.getParameterNames()
How do I get all the parameterNames in an HTML form in
the same sequence?

Example:

If the form contains FirstName, LastNameand Age

The output should appear exatcly in the same sequence

I have tried using the following but this shifts the
order of the output:

```<code>Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
    String paramName = (String) paramNames.nextElement();
    out.print(paramName);
}
</code>```

答:
I don't think there's nothing in the HTTP spec that forces browsers to send parameters in the order they appear in the form. You can work it around by prefixing a number to the name of the parameter like:

```<code>FirstName --> 0_FirstName
LastName --> 1_LastName
...
</code>```

After that you could basically order the elements by the prefix. It is an ugly solution but it is the only way to do it. Something like:

```<code>// Assuming you fill listOfParameters with all the parameters
Collections.sort(listOfParameters, new Comparator<String>() {
    int compare(String a,String b) {
        return Integer.getInt(a.substring(0,a.indexOf("_"))) -
               Integer.getInt(a.substring(0,b.indexOf("_")))
    }
});
for (String param : listOfParameters) {
    // traverse in order of the prefix
}
</code>```

By the way - does it really matters the order in which you receive the parameters ?

ContentLicense: CC BY-SA 4.0

Title: Order of request.getParameterNames()

Body:
How do I get all the parameterNames in an HTML form in
the same sequence?

Example:

If the form contains FirstName, LastNameand Age

The output should appear exatcly in the same sequence

I have tried using the following but this shifts the
order of the output:

Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
    String paramName = (String) paramNames.nextElement();
    out.print(paramName);
}

Body:
I don't think there's nothing in the HTTP spec that forces browsers to send parameters in the order they appear in the form. You can work it around by prefixing a number to the name of the parameter like:

FirstName --> 0_FirstName
LastName --> 1_LastName
...

After that you could basically order the elements by the prefix. It is an ugly solution but it is the only way to do it. Something like:

// Assuming you fill listOfParameters with all the parameters
Collections.sort(listOfParameters, new Comparator<String>() {
    int compare(String a,String b) {
        return Integer.getInt(a.substring(0,a.indexOf("_"))) -
               Integer.getInt(a.substring(0,b.indexOf("_")))
    }
});
for (String param : listOfParameters) {
    // traverse in order of the prefix
}

By the way - does it really matters the order in which you receive the parameters ?


问:
remove element of custom type from array in swift
I am using a collection view to add objects to an array called collectiveSelection

When a collection view cell is selected (currentSelection), I want to test whether this object exists in the array (collectiveSelection) or not. If it does, I want to remove it (to achieve a toggle on/off effect). If it isn't in the array, I want to add it.

The items I am adding to the array are of a custom class, so this is causing me issues when trying to use .index(of:) in my check.

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    currentSelection = itMachine.selection[indexPath.row]  // returns some selection of type 'Attractions'

    if collectiveSelection.contains(where: { $0 == currentSelection}){ // if selection exists in array, remove it, if it doesn't, add it

        let itemIndex = collectiveSelection.index(of: currentSelection) // error message about .index not being available for custom class Attractions

        collectiveSelection.remove(at: itemIndex)

        updateCell(having: indexPath, selected: false)

    } else { // deselect

        collectiveSelection.append(currentSelection!)

        updateCell(having: indexPath, selected: true)
    }
}
</code>```

I have tried making my custom class conform to Equatable, but this hasn't helped as I still get an error. Any ideas of how I can obtain the index of my custom element currentSelection within the array collectiveSelection?

答:
You may find it much easier to track the selected indexes rather than tracking your custom objects. After all, you have your objects in an array to begin with.

Look at this:

```<code>//
//  TrackSelectedViewController.swift
//
//  Created by Don Mag on 11/16/17.
//

import UIKit

private let reuseIdentifier = "TrackingCell"

class TrackSelectedViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    @IBOutlet weak var theCV: UICollectionView!

    // this will maintain a list of IndexPath for selected cells
    var collectiveSelection = [IndexPath]()

    override func viewDidLoad() {
        super.viewDidLoad()

        theCV.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    // MARK: UICollectionViewDataSource

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 30
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)

        // does collectiveSelection contain this indexPath?
        let idx = collectiveSelection.index(of: indexPath) ?? -1

        if idx > -1 {
            // indexPath IS in collectiveSelection
            cell.backgroundColor = .red
        } else {
            // indexPath IS NOT in collectiveSelection
            cell.backgroundColor = .lightGray
        }

        // of course, you'll configure your cell other than just setting the background color

        return cell
    }

    // MARK: UICollectionViewDelegate

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        // get a reference to the cell
        let cell = collectionView.cellForItem(at: indexPath)

        // does collectiveSelection contain this indexPath?
        let idx = collectiveSelection.index(of: indexPath) ?? -1

        if idx > -1 {

            // indexPath IS in collectiveSelection
            // so remove it and set the cell to Gray
            collectiveSelection.remove(at: idx)

            cell?.backgroundColor = .lightGray

            // your code:
            // updateCell(having: indexPath, selected: true)

        } else {

            // indexPath IS NOt in collectiveSelection
            // so add it and set the cell to Red
            collectiveSelection.append(indexPath)

            cell?.backgroundColor = .red

            // your code:
            // updateCell(having: indexPath, selected: true)

        }

    }

}
</code>```

If you create a fresh UIViewController and add a UICollectionView (and connect it to the IBOutlet and DataSource and Delegate), you can run that code as-is... it will toggle the cells between Gray and Red, depending on if they are in collectiveSelection

Body:
I am using a collection view to add objects to an array called collectiveSelection

When a collection view cell is selected (currentSelection), I want to test whether this object exists in the array (collectiveSelection) or not. If it does, I want to remove it (to achieve a toggle on/off effect). If it isn't in the array, I want to add it.

The items I am adding to the array are of a custom class, so this is causing me issues when trying to use .index(of:) in my check.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    currentSelection = itMachine.selection[indexPath.row]  // returns some selection of type 'Attractions'

    if collectiveSelection.contains(where: { $0 == currentSelection}){ // if selection exists in array, remove it, if it doesn't, add it

        let itemIndex = collectiveSelection.index(of: currentSelection) // error message about .index not being available for custom class Attractions

        collectiveSelection.remove(at: itemIndex)

        updateCell(having: indexPath, selected: false)

    } else { // deselect

        collectiveSelection.append(currentSelection!)

        updateCell(having: indexPath, selected: true)
    }
}

I have tried making my custom class conform to Equatable, but this hasn't helped as I still get an error. Any ideas of how I can obtain the index of my custom element currentSelection within the array collectiveSelection?

Body:
You may find it much easier to track the selected indexes rather than tracking your custom objects. After all, you have your objects in an array to begin with.

Look at this:

//
//  TrackSelectedViewController.swift
//
//  Created by Don Mag on 11/16/17.
//

import UIKit

private let reuseIdentifier = "TrackingCell"

class TrackSelectedViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    @IBOutlet weak var theCV: UICollectionView!

    // this will maintain a list of IndexPath for selected cells
    var collectiveSelection = [IndexPath]()

    override func viewDidLoad() {
        super.viewDidLoad()

        theCV.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    // MARK: UICollectionViewDataSource

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 30
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)

        // does collectiveSelection contain this indexPath?
        let idx = collectiveSelection.index(of: indexPath) ?? -1

        if idx > -1 {
            // indexPath IS in collectiveSelection
            cell.backgroundColor = .red
        } else {
            // indexPath IS NOT in collectiveSelection
            cell.backgroundColor = .lightGray
        }

        // of course, you'll configure your cell other than just setting the background color

        return cell
    }

    // MARK: UICollectionViewDelegate

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        // get a reference to the cell
        let cell = collectionView.cellForItem(at: indexPath)

        // does collectiveSelection contain this indexPath?
        let idx = collectiveSelection.index(of: indexPath) ?? -1

        if idx > -1 {

            // indexPath IS in collectiveSelection
            // so remove it and set the cell to Gray
            collectiveSelection.remove(at: idx)

            cell?.backgroundColor = .lightGray

            // your code:
            // updateCell(having: indexPath, selected: true)

        } else {

            // indexPath IS NOt in collectiveSelection
            // so add it and set the cell to Red
            collectiveSelection.append(indexPath)

            cell?.backgroundColor = .red

            // your code:
            // updateCell(having: indexPath, selected: true)

        }

    }

}

If you create a fresh UIViewController and add a UICollectionView (and connect it to the IBOutlet and DataSource and Delegate), you can run that code as-is... it will toggle the cells between Gray and Red, depending on if they are in collectiveSelection


问:
my JavaScript seems to be ignoring the first element in my array
I am working with the grading table in Moodle and I want to add a flag that says "student has added comments, please review" wherever they have added a comment. Unfortunately the comments get loaded with Ajax (or something similar) when you click the comment link. After the student has submitted an assignment, Moodle adds the text "Comments (0)" to the student's row in the grading table. (Before the assignment is submitted, the cell is blank.)

So I have tried to find the cells which contain the text 'Comments', and then check if there is a zero in the comments span.

I have tidied up the HTML a bit, but I left cell c10 as it actually is on Moodle.

if (!document.getElementsByClassName('gradingtable')[0]) {
   /* do nothing */
} else {
    var table = document.getElementsByClassName('gradingtable')[0];
    var comments = table.getElementsByClassName('c10');

    for (var i=0, len=comments.length; i<len; i++){
        var commentText = comments[i].innerText;

        if (commentText.search('Comments') > -1){
            var enumerator = comments[i].getElementsByTagName('span')[0];

            if (enumerator.innerText.search('0') > -1){
                       // do nothing
            } else {
                var container = comments[i].getElementsByClassName('commentscontainer')[0];
                container.insertAdjacentHTML('afterend', '
Student has added comments, please review.
');
            }
        }
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bluemsg {
  background-color: #99ccff;
}

/* border and shading added for ease of viewing */
td { border: 1px solid #666 }

tr:nth-child(even) {background: #cecece}
tr:nth-child(odd) {background: #ffffff}</code>```

 Moodle grading table (sample HTML)

    Col 0
    Col 1
    Col 2
    Col 3
    Col 4
    Col 5
    Col 6
    Col 7
    Col 8
    Col 9
    Col 10
    Col 11
    Col 12
    Col 13
    Col 14
    Col 15

      some text
      some text
      some text
      some text
      some text

No submission

          Assignment overdue

      some text

          some text
      some text

        some text

___picture______name___ - ___time___

___content___

Show comments
            Comments (0)

<textarea name="content" rows="2" id="dlg-content-59bfbd687894d" cols="20" style="color: grey;"></textarea>

Save comment | Cancel

      -

      some text
      some text
      some text

      some text
      some text
      some text
      some text
      some text

No submission

          Assignment overdue

      some text

          some text
      some text

        some text

___picture______name___ - ___time___

___content___

Show comments
            Comments (1)

<textarea name="content" rows="2" id="dlg-content-59bfbd687894d" cols="20" style="color: grey;"></textarea>

Save comment | Cancel

      -
      -
      some text
      some text
      some text

```

答:
It looks like you are checking for zero in a different string, one of the span tags, rather than the comment/number string.
You can replace:
if (enumerator.innerText.search('0') > -1){
With:
if (commentText.search('0') > -1){

You may not need the enumerator variable at all.

Body:
I am working with the grading table in Moodle and I want to add a flag that says "student has added comments, please review" wherever they have added a comment. Unfortunately the comments get loaded with Ajax (or something similar) when you click the comment link. After the student has submitted an assignment, Moodle adds the text "Comments (0)" to the student's row in the grading table. (Before the assignment is submitted, the cell is blank.)

So I have tried to find the cells which contain the text 'Comments', and then check if there is a zero in the comments span.

I have tidied up the HTML a bit, but I left cell c10 as it actually is on Moodle.

if (!document.getElementsByClassName('gradingtable')[0]) {
   /* do nothing */
} else {
    var table = document.getElementsByClassName('gradingtable')[0];
    var comments = table.getElementsByClassName('c10');

    for (var i=0, len=comments.length; i<len; i++){
        var commentText = comments[i].innerText;

        if (commentText.search('Comments') > -1){
            var enumerator = comments[i].getElementsByTagName('span')[0];

            if (enumerator.innerText.search('0') > -1){
                       // do nothing
            } else {
                var container = comments[i].getElementsByClassName('commentscontainer')[0];
                container.insertAdjacentHTML('afterend', '
Student has added comments, please review.
');
            }
        }
    }
}

.bluemsg {
  background-color: #99ccff;
}

/* border and shading added for ease of viewing */
td { border: 1px solid #666 }

tr:nth-child(even) {background: #cecece}
tr:nth-child(odd) {background: #ffffff}

 Moodle grading table (sample HTML)

    Col 0
    Col 1
    Col 2
    Col 3
    Col 4
    Col 5
    Col 6
    Col 7
    Col 8
    Col 9
    Col 10
    Col 11
    Col 12
    Col 13
    Col 14
    Col 15

      some text
      some text
      some text
      some text
      some text

No submission

          Assignment overdue

      some text

          some text
      some text

        some text

___picture______name___ - ___time___

___content___

Show comments
            Comments (0)

<textarea name="content" rows="2" id="dlg-content-59bfbd687894d" cols="20" style="color: grey;"></textarea>

Save comment | Cancel

      -

      some text
      some text
      some text

      some text
      some text
      some text
      some text
      some text

No submission

          Assignment overdue

      some text

          some text
      some text

        some text

___picture______name___ - ___time___

___content___

Show comments
            Comments (1)

<textarea name="content" rows="2" id="dlg-content-59bfbd687894d" cols="20" style="color: grey;"></textarea>

Save comment | Cancel

      -
      -
      some text
      some text
      some text


问:
WPF - ScrollViewer content overflowing
I have a WPF control with this basic structure:

```<code><Grid>
    <ScrollViewer x:Name="_Scroll" Grid.Row="4" Grid.RowSpan="20" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" CanContentScroll="True" >
        <StackPanel x:Name="_Panel" />
    </ScrollViewer>
</Grid>
</code>```

Some Grid items are added to _Panel later, during execution, thus generating a list of items vertically aligned. It all works properly when the scrollbar isn't visible, but when I actually need to scroll the content, the StackPanel overflows and I end up seeing part of the StackPanel's content above the ScrollViewer. Any idea as to what could be causing this issue? If you need more details, let me know and I'll edit the question appropriately.

EDIT: Added an image explaining the issue better: above is what the control looks like before beginning to scroll, below is the issue with the items overflowing over the ScrollViewer. As for the code, there's nothing particular about the insertion of items in the panel, it's basically among the lines of:

```<code>Dim nRow As New Grid
' Insertion of subcontrols within nRow
_Panel.Children.Add(nRow)
</code>```

答:
this is because the amount of items added later in your stackpanel does not update the height of the scroll bar, which is external to it, and refers only to the original size of the stackpanel
you can solve as folowing:

[Edit] give your stackpanel a relative or absolute size for the scroll to be displayed.

something like that:

```<code><Grid Name="GridContent" Height="XXX" >
    <StackPanel Height="{Binding ActualHeight, ElementName=GridContent}"
                Orientation="Vertical"
                ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                ScrollViewer.VerticalScrollBarVisibility="Auto"
                ScrollViewer.CanContentScroll="True">

    </StackPanel>
</Grid>
</code>```

Title: WPF - ScrollViewer content overflowing

Body:
I have a WPF control with this basic structure:

<Grid>
    <ScrollViewer x:Name="_Scroll" Grid.Row="4" Grid.RowSpan="20" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" CanContentScroll="True" >
        <StackPanel x:Name="_Panel" />
    </ScrollViewer>
</Grid>

Some Grid items are added to _Panel later, during execution, thus generating a list of items vertically aligned. It all works properly when the scrollbar isn't visible, but when I actually need to scroll the content, the StackPanel overflows and I end up seeing part of the StackPanel's content above the ScrollViewer. Any idea as to what could be causing this issue? If you need more details, let me know and I'll edit the question appropriately.

EDIT: Added an image explaining the issue better: above is what the control looks like before beginning to scroll, below is the issue with the items overflowing over the ScrollViewer. As for the code, there's nothing particular about the insertion of items in the panel, it's basically among the lines of:

Dim nRow As New Grid
' Insertion of subcontrols within nRow
_Panel.Children.Add(nRow)

Body:
this is because the amount of items added later in your stackpanel does not update the height of the scroll bar, which is external to it, and refers only to the original size of the stackpanel
you can solve as folowing:

[Edit] give your stackpanel a relative or absolute size for the scroll to be displayed.

something like that:

<Grid Name="GridContent" Height="XXX" >
    <StackPanel Height="{Binding ActualHeight, ElementName=GridContent}"
                Orientation="Vertical"
                ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                ScrollViewer.VerticalScrollBarVisibility="Auto"
                ScrollViewer.CanContentScroll="True">

    </StackPanel>
</Grid>


问:
CSS FlexBox and image resize
I'm actually playing with flexbox, and I can't archive to resize an image in a container that have an adapative width.

Also here is a plunker for this code : https://plnkr.co/edit/QaPzOVXSx5iYQXOsit9V?p=preview

Also a direct preview :

<!doctype html>

        <meta charset="utf-8">

```

And a image of what I want to do :

So i want that my image resize in the green container when the screen get smaller.

How can I do that ?

Thanks ! =)

答:
You need to add width: 100%; to the img

Stack snippet

```

Title: CSS FlexBox and image resize

Body:
I'm actually playing with flexbox, and I can't archive to resize an image in a container that have an adapative width.

Also here is a plunker for this code : https://plnkr.co/edit/QaPzOVXSx5iYQXOsit9V?p=preview

Also a direct preview :

<!doctype html>

        <meta charset="utf-8">

And a image of what I want to do :

So i want that my image resize in the green container when the screen get smaller.

How can I do that ?

Thanks ! =)

Body:
You need to add width: 100%; to the img

Stack snippet

        <div style="display: flex; flex-direction: row; height: 800px">
            <div style="width: 1000px; background-color: lightpink;"></div>
            <div style="flex: auto;
                        background-color: lightgreen; padding: 10px;
                        display: flex; flex-direction: column; justify-content: center;
                        min-width: 100px; max-width: 200px;">
                <div style="max-width: 200px; opacity: 0.5">
                    <img src="https://www.adrln.com/wp-content/uploads/2017/05/img.png" style="width: 100%; max-width: 200px; height: auto">
                </div>

                <div style="max-width: 200px; opacity: 0.5">
                    <img src="https://www.adrln.com/wp-content/uploads/2017/05/img.png" style="width: 100%; max-width: 200px; height: auto">
                </div>

                <div style="max-width: 200px; opacity: 0.5">
                    <img src="https://www.adrln.com/wp-content/uploads/2017/05/img.png" style="width: 100%; max-width: 200px; height: auto">
                </div>
            </div>
        </div>


问:
C#,Multiple condition for if statement
I am a matlab user. How can I use the following if statment in c#

```<code>    double angle;
    //angle=45.00;// just for idea
        if (0.0<=angle<90.0)||(170.0<=angle<181.0)
        {
// do something
        }
</code>```

// It is just demo code what I want to do.......

答:
The syntax you used can't work in C#. The easiest solution is:

```<code>if (((angle >= 0) && (angle < 90)) || ((angle >= 170) && (angle < 181)))
{
    // your code here
}
</code>```

Using literals on your condition constants, you can achieve the same result without implicit casting from Int32 to Double (a little bit better performance-wise, but almost unnoticeable):

```<code>if (((angle >= 0.0d) && (angle < 90.0d)) || ((angle >= 170.0d) && (angle < 181.0d)))
{
    // your code here
}
</code>```

An alternative approach:

```<code>public static Boolean Between(this Double num, Double lower, Double upper, Boolean inclusive = false)
{
    return inclusive
        ? lower <= num && num <= upper
        : lower < num && num < upper;
}
</code>```

Then:

```<code>if (angle.Between(0.0d, 90.0d) || angle.Between(170.0d, 181.0d))
{
    // your code here
}
</code>```

Title: C#,Multiple condition for if statement

Body:
I am a matlab user. How can I use the following if statment in c#

    double angle;
    //angle=45.00;// just for idea
        if (0.0<=angle<90.0)||(170.0<=angle<181.0)
        {
// do something
        }

// It is just demo code what I want to do.......

Body:
The syntax you used can't work in C#. The easiest solution is:

if (((angle >= 0) && (angle < 90)) || ((angle >= 170) && (angle < 181)))
{
    // your code here
}

Using literals on your condition constants, you can achieve the same result without implicit casting from Int32 to Double (a little bit better performance-wise, but almost unnoticeable):

if (((angle >= 0.0d) && (angle < 90.0d)) || ((angle >= 170.0d) && (angle < 181.0d)))
{
    // your code here
}

An alternative approach:

public static Boolean Between(this Double num, Double lower, Double upper, Boolean inclusive = false)
{
    return inclusive
        ? lower <= num && num <= upper
        : lower < num && num < upper;
}

Then:

if (angle.Between(0.0d, 90.0d) || angle.Between(170.0d, 181.0d))
{
    // your code here
}


问:
How to convert MM/YY to MM/DD/YYYY in Excel (missing day)
The day is missing so it just needs to be first of the month so:

11/17 would be 11/01/2017

Is there a formula that can do this?

答:
There is two approaches:

Set the Category type of the cell (in Format Cell) as Custom and define this format in Type field: mm/dd/yyyy

In case of the format cell is text (working with string)

Assuming the validate entered in cell A1, use below formula:

```<code>=LEFT(A1,2)&"/01/"&IF(LEN(A1)=8,2,20)&RIGHT(A1,2)
</code>```

Body:
There is two approaches:

Set the Category type of the cell (in Format Cell) as Custom and define this format in Type field: mm/dd/yyyy

In case of the format cell is text (working with string)

Assuming the validate entered in cell A1, use below formula:

=LEFT(A1,2)&"/01/"&IF(LEN(A1)=8,2,20)&RIGHT(A1,2)


问:
GPS disabling feature
I am developing a app.. When i start the app my GPS is enabled but on exit it should disable the GPS. how to do it? please help</p>

答:
You need not disable anything ,  just remove gpsupdate using Location Manager..
Here  the code for that

(LocationManager)getSystemService(Context.LOCATION_SERVICE).removeUpdates(mLocListener);

ContentLicense: CC BY-SA 2.5

Title: GPS disabling feature


问:
Cakephp app inconsistent behavior
I have a cake php app, with a function that uploads and processes a file.
The app and file upload works well if I connect to the live site from my development machine (it works the same as it does on my local development server). However, if I try the upload feather from other computers, nothing happens after I click upload/submit button. The page just refreshes and nothing else happens. I can't figure out the error because there are no errors.

Can anyone help with this?
Not that all other features work, except file uploads.

The same behavior is seen on all browsers.

答:
I'd look into a couple of things:

Is the app somehow bound to your dev IP address? Try changing it and see what happens (make a note of the current one first).

It has a bit of a smell of ACL access denial about it, or perhaps Auth?

Title: Cakephp app inconsistent behavior


问:
syntaxerror: 'return' outside function in python code
There is something wrong with my python code. I am a beginner in python.

```<code>def gen_qr_text(acc_id,amount):
    pp_acc_id = ""
    pp_amount = ""
    pp_chksum = ""

if len(acc_id) == 15:
    pp_acc_id = "0315" + acc_id
elif acc_id.length() == 13:
    pp_acc_id = "0213" + acc_id
elif acc_id.length() == 10:
    pp_acc_id = "01130066" + acc_id.substring(1)
else:
    return "null"

if not amount:
    pp_amount = format("54%02d%s", amount.length(), amount)

    pp_str = "00020101021129370016A000000677010111"
    + pp_acc_id
    + "5303764"
    + pp_amount
    + "5802TH"
    + "6304"
    pp_chksum = crc16.checksum(pp_str);
    pp_str += pp_chksum;
    return pp_str
</code>```

Error says it's SyntaxError: 'return' outside function. What's the problem with this code. By the way i convert the code from java to python. Is that everything okey in my code? I edit my code here but still there are some error

答:
Python is what is called "whitespace-sensitive": it matters how stuff is indented. For example, it expects the contents inside an if-clause to be indented below that statement:

```<code>if True or False:
    execute_this_function()
</code>```

This will not work:

```<code>if True or False:
execute_this_function()
</code>```

The same applies to return statements: they should be inside the function they apply to, i.e. that you are returning from:

```<code>def my_method():
    return True
</code>```

Again, this will not work and raise the error you are getting:

```<code>def my_method():
return True
</code>```

Thus, the solution is to make sure your returns are indented correctly. Of course, the same applies to the rest of the code!

Edit Based on the modification of your OP, this is the indentation you require; I also fixed the .length() you copied over from Java, it seems:

```<code>def gen_qr_text(acc_id,amount):
    pp_acc_id = ""
    pp_amount = ""
    pp_chksum = ""

    if len(acc_id) == 15:
        pp_acc_id = "0315" + acc_id
    elif len(acc_id) == 13:
        pp_acc_id = "0213" + acc_id
    elif len(acc_id) == 10:
        pp_acc_id = "01130066" + acc_id.substring(1)
    else:
        return "null"

    if not amount:
        pp_amount = format("54%02d%s", len(amount), amount)

        pp_str = "00020101021129370016A000000677010111"
        + pp_acc_id
        + "5303764"
        + pp_amount
        + "5802TH"
        + "6304"
        pp_chksum = crc16.checksum(pp_str);
        pp_str += pp_chksum;
        return pp_str
</code>```

Body:
There is something wrong with my python code. I am a beginner in python.

def gen_qr_text(acc_id,amount):
    pp_acc_id = ""
    pp_amount = ""
    pp_chksum = ""

if len(acc_id) == 15:
    pp_acc_id = "0315" + acc_id
elif acc_id.length() == 13:
    pp_acc_id = "0213" + acc_id
elif acc_id.length() == 10:
    pp_acc_id = "01130066" + acc_id.substring(1)
else:
    return "null"

if not amount:
    pp_amount = format("54%02d%s", amount.length(), amount)

    pp_str = "00020101021129370016A000000677010111"
    + pp_acc_id
    + "5303764"
    + pp_amount
    + "5802TH"
    + "6304"
    pp_chksum = crc16.checksum(pp_str);
    pp_str += pp_chksum;
    return pp_str

Error says it's SyntaxError: 'return' outside function. What's the problem with this code. By the way i convert the code from java to python. Is that everything okey in my code? I edit my code here but still there are some error

Body:
Python is what is called "whitespace-sensitive": it matters how stuff is indented. For example, it expects the contents inside an if-clause to be indented below that statement:

if True or False:
    execute_this_function()

This will not work:

if True or False:
execute_this_function()

The same applies to return statements: they should be inside the function they apply to, i.e. that you are returning from:

def my_method():
    return True

Again, this will not work and raise the error you are getting:

def my_method():
return True

Thus, the solution is to make sure your returns are indented correctly. Of course, the same applies to the rest of the code!

Edit Based on the modification of your OP, this is the indentation you require; I also fixed the .length() you copied over from Java, it seems:

def gen_qr_text(acc_id,amount):
    pp_acc_id = ""
    pp_amount = ""
    pp_chksum = ""

    if len(acc_id) == 15:
        pp_acc_id = "0315" + acc_id
    elif len(acc_id) == 13:
        pp_acc_id = "0213" + acc_id
    elif len(acc_id) == 10:
        pp_acc_id = "01130066" + acc_id.substring(1)
    else:
        return "null"

    if not amount:
        pp_amount = format("54%02d%s", len(amount), amount)

        pp_str = "00020101021129370016A000000677010111"
        + pp_acc_id
        + "5303764"
        + pp_amount
        + "5802TH"
        + "6304"
        pp_chksum = crc16.checksum(pp_str);
        pp_str += pp_chksum;
        return pp_str


问:
How to use Xamarin Android.Hardware.Camera2;
I can't really understand the usage of Android.Hardware.Camera2 in Xamarin can anyone explain me how to use OpenCamera method and how do i define the AvailabilityCallback?

Here is my code

```<code>if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
{
    CameraManager cameraManager = ((CameraManager)Context.GetSystemService(Context.CameraService));
    //AvailabilityCallback stateCallback = ;

    Control.Preview = cameraManager.OpenCamera(cameraManager.GetCameraIdList()[0], WHAT_HERE?, null);
 }
 else
 {
    Control.Preview = Camera.Open((int)e.NewElement.Camera);
 }
</code>```

Many thanks in advance.

答:
WHAT_HERE?

CameraDevice.StateCallback

There is a Camera2 demo app in mono samples repository
https://github.com/xamarin/monodroid-samples/tree/master/android5.0/Camera2Basic

here is the callback implementation class  https://github.com/xamarin/monodroid-samples/blob/master/android5.0/Camera2Basic/Camera2Basic/Listeners/CameraStateListener.cs

Body:
I can't really understand the usage of Android.Hardware.Camera2 in Xamarin can anyone explain me how to use OpenCamera method and how do i define the AvailabilityCallback?

Here is my code

if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
{
    CameraManager cameraManager = ((CameraManager)Context.GetSystemService(Context.CameraService));
    //AvailabilityCallback stateCallback = ;

    Control.Preview = cameraManager.OpenCamera(cameraManager.GetCameraIdList()[0], WHAT_HERE?, null);
 }
 else
 {
    Control.Preview = Camera.Open((int)e.NewElement.Camera);
 }

Many thanks in advance.


问:
Pass value on styled-component within usage
I want to make Header (own component) to be a styled-component. However I get

Uncaught TypeError:
  WEBPACK_IMPORTED_MODULE_4_styled_components.a.Header is not a function

```<code>class Header extends Component {
    render() {
        return (
            <div className={this.props.className}>
                <NavBar>
                    <Nav>
                        <NavItem>Item1</NavItem>
                        <NavItem>Item2</NavItem>
                    </Nav>
                </NavBar>
            </div>
        );
    }
}
export default Header;
</code>```

Desired Usage:

```<code>const StyledHeader = styled.Header`
  background: ${props => props.background ||  'goldenrod'};
`;
class HomePage extends Component {
    render() {
        return(
            <StyledHeader background={"#d3d9df"}/>
            <Content />
        );
    }
}
export default HomePage;
</code>```

am I doing the right approach? I just want different background colors for Header every page.

答:
Header.js

```<code>class HeaderUnstyled extends Component {
    render() {
        return (
            <div className={this.props.className}>
               ...
            </div>
        );
    }
}

const Header = styled(HeaderUnstyled)`
  background: ${props => props.background || '#aab' };
  font-size: large;
  font-family: Beirut;
  padding: 5px;
`;

 export default Header;
</code>```

HomePage.js

```<code>import Header from '..header/Header.js';

class HomePage extends Component {
    render() {
        return(
            <Header />
            <Content />
        );
    }
}
export default HomePage;
</code>```

AboutPage.js

```<code>import Header from '..header/Header.js';

class AboutPage extends Component {
    render() {
        return(
            <Header background={'#fff'}/>
            <Content />
        );
    }
}
export default AboutPage;
</code>```

this is my chosen approach for now.

Body:
I want to make Header (own component) to be a styled-component. However I get

Uncaught TypeError:
  WEBPACK_IMPORTED_MODULE_4_styled_components.a.Header is not a function

class Header extends Component {
    render() {
        return (

                <NavBar>

                        <NavItem>Item1</NavItem>
                        <NavItem>Item2</NavItem>

                </NavBar>

        );
    }
}
export default Header;

Desired Usage:

const StyledHeader = styled.Header`
  background: ${props => props.background ||  'goldenrod'};
`;
class HomePage extends Component {
    render() {
        return(

Body:
Header.js

class HeaderUnstyled extends Component {
    render() {
        return (
            <div className={this.props.className}>
               ...
            </div>
        );
    }
}

const Header = styled(HeaderUnstyled)`
  background: ${props => props.background || '#aab' };
  font-size: large;
  font-family: Beirut;
  padding: 5px;
`;

 export default Header;

HomePage.js

import Header from '..header/Header.js';

class HomePage extends Component {
    render() {
        return(
            <Header />
            <Content />
        );
    }
}
export default HomePage;

AboutPage.js

import Header from '..header/Header.js';

class AboutPage extends Component {
    render() {
        return(
            <Header background={'#fff'}/>
            <Content />
        );
    }
}
export default AboutPage;

this is my chosen approach for now.


问:
Override the overflow: hidden style
Is it possible to override the overflow: hidden style in a table?  I would like to have a button on each row that opens a dropdown.  However, the dropdown is currently hidden because it overflows the row.

In the Chrome developer tools, I can see the dropdown if I manually remove overflow:hidden from .ReactVirtualized__Table__row and .ReactVirtualized__Table__rowColumn.  However, I have not found a way to do this with either javascript or css.

So far I've tried:

Adding overflow: visible to the ReactVirtualized classes. I tried this in both the original styles.css file and in a separate included css file.

```<code>.ReactVirtualized__Grid{
    overflow: visible;
}
.ReactVirtualized__Table__Grid {
    overflow: visible;
}
.ReactVirtualized__Table__row {
    overflow: visible;
}
.ReactVirtualized__Table__rowColumn {
    overflow: visible;
}
</code>```

Adding the rowStyle and Style props to Reactvirtualized.Table:

```<code><ReactVirtualized.AutoSizer>
  {({height, width}) => (
    <ReactVirtualized.Table
      width={width}
      height={height}
      headerHeight={35}
      rowHeight={(height - 35) / 5}
      rowCount={content.length}
      rowGetter={({index}) => content[index]}
      rowClassName="al-table-view__row"
      headerClassName="al-table-view__header"
      rowStyle={{overflowY: 'visible'}}
      style={{overflowY: 'visible'}}
    >
      {this.getColumns(width)}
    </ReactVirtualized.Table>
  )}
</ReactVirtualized.AutoSizer>
</code>```

I've been able to add my own classes and style them, but I have not been able to override the overflow style there either.  Any suggestions would be greatly appreciated.

答:
Modifying the overflow style isn't the right answer. Even if you overflow a single row, your dropdown wouldn't overflow the boundaries of the Table itself and so the lower rows would have the same problem.

For this sort of thing- I suggest you check out react-portal. Portals lift content out of the z-index stack (and so avoid clipping problems) while maintaining the visual position of it (top/left), allowing it to render outside of the clipping rect/box of its parent. They're perfect for things like drop-down menus within List or Table.

Title: Override the overflow: hidden style

Body:
Is it possible to override the overflow: hidden style in a table?  I would like to have a button on each row that opens a dropdown.  However, the dropdown is currently hidden because it overflows the row.

In the Chrome developer tools, I can see the dropdown if I manually remove overflow:hidden from .ReactVirtualized__Table__row and .ReactVirtualized__Table__rowColumn.  However, I have not found a way to do this with either javascript or css.

So far I've tried:

Adding overflow: visible to the ReactVirtualized classes. I tried this in both the original styles.css file and in a separate included css file.

.ReactVirtualized__Grid{
    overflow: visible;
}
.ReactVirtualized__Table__Grid {
    overflow: visible;
}
.ReactVirtualized__Table__row {
    overflow: visible;
}
.ReactVirtualized__Table__rowColumn {
    overflow: visible;
}

Adding the rowStyle and Style props to Reactvirtualized.Table:

<ReactVirtualized.AutoSizer>
  {({height, width}) => (
    <ReactVirtualized.Table
      width={width}
      height={height}
      headerHeight={35}
      rowHeight={(height - 35) / 5}
      rowCount={content.length}
      rowGetter={({index}) => content[index]}
      rowClassName="al-table-view__row"
      headerClassName="al-table-view__header"
      rowStyle={{overflowY: 'visible'}}
      style={{overflowY: 'visible'}}
    >
      {this.getColumns(width)}
    </ReactVirtualized.Table>
  )}
</ReactVirtualized.AutoSizer>

I've been able to add my own classes and style them, but I have not been able to override the overflow style there either.  Any suggestions would be greatly appreciated.


问:
How to setUp UiTableViewController below the battery bar
newBie here. I have added an UItableViewController into storyBoard. I use this as a setting page.

HomeVC ---->  Setting VC

In code : I use the below code to bring the tableView below the battery Bar:

```<code> self.tableView.contentInset = UIEdgeInsets(top: 20,left: 0,bottom: 0,right: 0)
</code>```

Problem:

How to move the TableView down below the battery bar so that I can add a button above the table in StoryBoard

Please help.

答:
For this you should use a normal view controller and drag a table on the view controller this way you can make the table size whatever you like. This will also allow you to place buttons wherever you like.

Don't forget to assign the TableViewDataSource and TableViewDelegate to your view controller.

Good luck!

Body:
newBie here. I have added an UItableViewController into storyBoard. I use this as a setting page.

HomeVC ---->  Setting VC

In code : I use the below code to bring the tableView below the battery Bar:

 self.tableView.contentInset = UIEdgeInsets(top: 20,left: 0,bottom: 0,right: 0)

Problem:

How to move the TableView down below the battery bar so that I can add a button above the table in StoryBoard

Please help.


问:
Why is validate() method accessible via request()?
Quoting the Laravel documentation:

By default, Laravel's base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules

It's true, reading the code, App\Http\Controllers\Controller actually uses ValidatesRequests trait. And ValidatesRequests has a validate method.

What is really strange for me is that everywhere else in the documentation, the validate method is called on $request object. And it works this way. I can validate a form with this code:

```<code>public function store()
{
    $attributes = request()->validate([
        'name' => 'required|string|max:255',
    ]);
    // ...
}
</code>```

But I don't see any presence of a validate method on the Request class. Just a strange comment line at the beginning of the file:

```<code>/**
 * @method array validate(array $rules, array $messages = [], array $customAttributes = [])
 */
</code>```

So there are two things:

I don't know what to trust in Laravel documentation.

And I don't understand how the validation works on the $request object.

And my actual question is:

Is the initial quote I pasted from the documentation still true if I use the validate method through $request object? If so, how does it works?

答:
Well, validate method is there, but it's not in FormRequest directly but in ValidatesWhenResolvedTrait trait so it's usable without any problem in FormRequest so documentation is fine.

Let's look at the beginning of this trait:

```<code>trait ValidatesWhenResolvedTrait
{
    /**
     * Validate the class instance.
     *
     * @return void
     */
    public function validate()
    {
        $this->prepareForValidation();

        $instance = $this->getValidatorInstance();

        if (! $this->passesAuthorization()) {
            $this->failedAuthorization();
        } elseif (! $instance->passes()) {
            $this->failedValidation($instance);
        }
    }
</code>```

so when you are running in controller:

```<code>request()->validate
</code>```

you are running the method from trait and ValidatesRequests has nothing in common with this.

Alternatively if you would like to use "Controller way" validation you could do:

```<code>$this->validate(request(), [
        'name' => 'required|string|max:255',
    ]);
</code>```

and now you would be using validate method from ValidatesRequests requests.

As you see there are multiple ways of running validation in Laravel. I personally use only Form Request validation instead.

Body:
Quoting the Laravel documentation:

By default, Laravel's base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules

It's true, reading the code, App\Http\Controllers\Controller actually uses ValidatesRequests trait. And ValidatesRequests has a validate method.

What is really strange for me is that everywhere else in the documentation, the validate method is called on $request object. And it works this way. I can validate a form with this code:

public function store()
{
    $attributes = request()->validate([
        'name' => 'required|string|max:255',
    ]);
    // ...
}

But I don't see any presence of a validate method on the Request class. Just a strange comment line at the beginning of the file:

/**
 * @method array validate(array $rules, array $messages = [], array $customAttributes = [])
 */

So there are two things:

I don't know what to trust in Laravel documentation.

And I don't understand how the validation works on the $request object.

And my actual question is:

Is the initial quote I pasted from the documentation still true if I use the validate method through $request object? If so, how does it works?

Body:
Well, validate method is there, but it's not in FormRequest directly but in ValidatesWhenResolvedTrait trait so it's usable without any problem in FormRequest so documentation is fine.

Let's look at the beginning of this trait:

trait ValidatesWhenResolvedTrait
{
    /**
     * Validate the class instance.
     *
     * @return void
     */
    public function validate()
    {
        $this->prepareForValidation();

        $instance = $this->getValidatorInstance();

        if (! $this->passesAuthorization()) {
            $this->failedAuthorization();
        } elseif (! $instance->passes()) {
            $this->failedValidation($instance);
        }
    }

so when you are running in controller:

request()->validate

you are running the method from trait and ValidatesRequests has nothing in common with this.

Alternatively if you would like to use "Controller way" validation you could do:

$this->validate(request(), [
        'name' => 'required|string|max:255',
    ]);

and now you would be using validate method from ValidatesRequests requests.

As you see there are multiple ways of running validation in Laravel. I personally use only Form Request validation instead.


问:
Add rows to DataGridView without freezing GUI
I want to display a table. Data for table must to be precalculated and it is heavy calculation. Also result table is long.
I want to provide acces to part of data while another part is calculated in the background.

I wrote background worker for calculation and DataGridView for display. Sometimes worker submit new rows via ProgressChangedEvent. I am tried to add this rows at bottom.
My problem starts when I tried add new rows at bottom. My UI is freezes.

Here is how I initialize DataGridView:

```<code>private void InitDataGridView()
{
    BindingList<TableRow> tableRows = new BindingList<TableRow>();
    dataGridView.DataSource = tableRows;
}
</code>```

and here is how I adding new rows at bottom in ProgressChangedEvent

```<code>private void UpdateDataGridView (List<Items> newItems)
{
    BindingList<TableRow> dataSource = (BindingList<TableRow>)this.dataGridView.DataSource;
    foreach (var item in newItems)
        dataSource.Add(new TableRow(item));
}
</code>```

I think that problem is because adding one row initiate redrawing of the table.
But I don't found AddRange for BindingList or mechanism to stop rendering temporary.

Any suggestions?

答:
Try setting the AutoSizeColumnsMode property to None or DisplayedCells, as well as set on the AutoSizeMode on each column:

```<code>foreach (DataGridViewColumn c in thisGrid.Columns)
{
    c.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
}
</code>```

Try toggling this before and after binding, and when updating.

Also, you can try what is suggested on this answer and enable double buffering:

```<code>if (!System.Windows.Forms.SystemInformation.TerminalServerSession)
{
  Type dgvType = dataGridView1.GetType();
  PropertyInfo pi = dgvType.GetProperty("DoubleBuffered",
    BindingFlags.Instance | BindingFlags.NonPublic);
  pi.SetValue(dataGridView1, value, null);
}
</code>```

Body:
I want to display a table. Data for table must to be precalculated and it is heavy calculation. Also result table is long.
I want to provide acces to part of data while another part is calculated in the background.

I wrote background worker for calculation and DataGridView for display. Sometimes worker submit new rows via ProgressChangedEvent. I am tried to add this rows at bottom.
My problem starts when I tried add new rows at bottom. My UI is freezes.

Here is how I initialize DataGridView:

private void InitDataGridView()
{
    BindingList<TableRow> tableRows = new BindingList<TableRow>();
    dataGridView.DataSource = tableRows;
}

and here is how I adding new rows at bottom in ProgressChangedEvent

private void UpdateDataGridView (List<Items> newItems)
{
    BindingList<TableRow> dataSource = (BindingList<TableRow>)this.dataGridView.DataSource;
    foreach (var item in newItems)
        dataSource.Add(new TableRow(item));
}

I think that problem is because adding one row initiate redrawing of the table.
But I don't found AddRange for BindingList or mechanism to stop rendering temporary.

Any suggestions?

Body:
Try setting the AutoSizeColumnsMode property to None or DisplayedCells, as well as set on the AutoSizeMode on each column:

foreach (DataGridViewColumn c in thisGrid.Columns)
{
    c.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
}

Try toggling this before and after binding, and when updating.

Also, you can try what is suggested on this answer and enable double buffering:

if (!System.Windows.Forms.SystemInformation.TerminalServerSession)
{
  Type dgvType = dataGridView1.GetType();
  PropertyInfo pi = dgvType.GetProperty("DoubleBuffered",
    BindingFlags.Instance | BindingFlags.NonPublic);
  pi.SetValue(dataGridView1, value, null);
}


问:
WooCommerce set_height() Not Working as Expected
I've got a WooCommerce site with existing products. Currently, the products have no dimensions, and I'm looking to update each product's dimensions by ID programmatically. I thought I could use set_height() to do this, but it's not working as I expected.

Here's my code in functions.php for quick testing:

```<code>$_product = new WC_Product(1234);
var_dump($_product);
$_product->set_height('2');
echo $_product->get_height();
</code>```

This appears to be working based on the var_dump and the get_height() echo statement. The var_dump is the correct product info and the number that is output from the echo statement is "2". However, this doesn't seem to actually save the product data. After running this code and then viewing the product, it does not have a height value of 2 as it should, instead it's just blank as it was before.

I'm pretty lost here, any ideas on how to get it to actually update the product's height?

Thanks.

答:
There is 2 ways to update product dimensions like height in your case:

1) Using the WC_Product setter methods + save() method:

```<code>$_product = wc_get_product(1234); // Get an instance of the WC_Product object

$_product->set_height('2'); // Set your new height

$_product->save(); //  <==  <==  Save the new data set in your product
</code>```

2) Using update_post_meta() from the product ID:

```<code> update_post_meta( 1234, '_height', 2 );
</code>```

Body:
I've got a WooCommerce site with existing products. Currently, the products have no dimensions, and I'm looking to update each product's dimensions by ID programmatically. I thought I could use set_height() to do this, but it's not working as I expected.

Here's my code in functions.php for quick testing:

$_product = new WC_Product(1234);
var_dump($_product);
$_product->set_height('2');
echo $_product->get_height();

This appears to be working based on the var_dump and the get_height() echo statement. The var_dump is the correct product info and the number that is output from the echo statement is "2". However, this doesn't seem to actually save the product data. After running this code and then viewing the product, it does not have a height value of 2 as it should, instead it's just blank as it was before.

I'm pretty lost here, any ideas on how to get it to actually update the product's height?

Thanks.

Body:
There is 2 ways to update product dimensions like height in your case:

1) Using the WC_Product setter methods + save() method:

$_product = wc_get_product(1234); // Get an instance of the WC_Product object

$_product->set_height('2'); // Set your new height

$_product->save(); //  <==  <==  Save the new data set in your product

2) Using update_post_meta() from the product ID:

 update_post_meta( 1234, '_height', 2 );


问:
Empty DataFrame doesn't admit its empty
I must not understand something about emptiness when it comes to pandas DataFrames. I have a DF with empty rows but when I isolate one of these rows its not empty.

Here I've made a dataframe:

```<code>>>> df = pandas.DataFrame(columns=[1,2,3], data=[[1,2,3],[1,None,3],[None, None, None],[3,2,1],[4,5,6],[None,None,None],[None,None,None]])
>>> df
     1    2    3
0  1.0  2.0  3.0
1  1.0  NaN  3.0
2  NaN  NaN  NaN
3  3.0  2.0  1.0
4  4.0  5.0  6.0
5  NaN  NaN  NaN
6  NaN  NaN  NaN
</code>```

Then I know row '2' is full of  nothing so I check for that...

```<code>>>> df[2:3].empty
    False
</code>```

Odd. So I split it out into its own dataframe:

```<code>>>> df1 = df[2:3]
>>> df1
    1   2   3
2 NaN NaN NaN

>>> df1.empty
False
</code>```

How do I check for emptiness (all the elements in a row being None or NaN?)

http://pandas.pydata.org/pandas-docs/version/0.18/generated/pandas.DataFrame.empty.html

答:
If you are do not want to count NaN value as real number , this will equal to </p>

```<code>df.dropna().iloc[5:]
</code>```

<p>You select the line did not exist in your dataframe </p>

```<code>df.dropna().iloc[5:].empty
Out[921]: True
</code>```

Title: Empty DataFrame doesn't admit its empty

Body:
I must not understand something about emptiness when it comes to pandas DataFrames. I have a DF with empty rows but when I isolate one of these rows its not empty.

Here I've made a dataframe:

>>> df = pandas.DataFrame(columns=[1,2,3], data=[[1,2,3],[1,None,3],[None, None, None],[3,2,1],[4,5,6],[None,None,None],[None,None,None]])
>>> df
     1    2    3
0  1.0  2.0  3.0
1  1.0  NaN  3.0
2  NaN  NaN  NaN
3  3.0  2.0  1.0
4  4.0  5.0  6.0
5  NaN  NaN  NaN
6  NaN  NaN  NaN

Then I know row '2' is full of  nothing so I check for that...

>>> df[2:3].empty
    False

Odd. So I split it out into its own dataframe:

>>> df1 = df[2:3]
>>> df1
    1   2   3
2 NaN NaN NaN

>>> df1.empty
False

How do I check for emptiness (all the elements in a row being None or NaN?)

http://pandas.pydata.org/pandas-docs/version/0.18/generated/pandas.DataFrame.empty.html

Body:
If you are do not want to count NaN value as real number , this will equal to

df.dropna().iloc[5:]

You select the line did not exist in your dataframe

df.dropna().iloc[5:].empty
Out[921]: True


问:
ReferenceError: coroutine is not defined
I'm trying to create a coroutine using nodejs version 7.2.1.
When I'm writing this code

```<code>var runfn = coroutine(function * () {

  //... Multiple lines of code

});
</code>```

It generates following error

```<code>ReferenceError: coroutine is not defined
    at Object.<anonymous>
</code>```

I've seen this code in multiple places in google, so I know this code must be correct. Here is 1 link https://x.st/javascript-coroutines/#demo . I didn't found any additional library being used or mentioned here

I wasn't able to find any answer to this in google or with existing stackoverflow question. One thread I found which states that some co library needs to be used.

Can anyone point me to the correct one?

答: In the linked article, scroll down to The Convenient coroutine Wrapper. They provided their own definition...

Body:
I'm trying to create a coroutine using nodejs version 7.2.1.
When I'm writing this code

var runfn = coroutine(function * () {

  //... Multiple lines of code

});

It generates following error

ReferenceError: coroutine is not defined
    at Object.<anonymous>

I've seen this code in multiple places in google, so I know this code must be correct. Here is 1 link https://x.st/javascript-coroutines/#demo . I didn't found any additional library being used or mentioned here

I wasn't able to find any answer to this in google or with existing stackoverflow question. One thread I found which states that some co library needs to be used.

Can anyone point me to the correct one?


问:
How do I add a variable for the textbox ID inside a function?
```<code>public partial class _Default : System.Web.UI.Page
{
    double[] array = new double[5];
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        for(int i=0;i<5;i++)
        {
            array[i] = Convert.ToDouble(TextBox(i+1).Text);
        }
    }
}
</code>```

This is my code, I have 5 textboxes, I'd like to refer to them with the int (i) inside the loop.

```<code>array[i] = Convert.ToDouble(TextBox(i+1).Text);
</code>```

the text boxes are named 'TextBox1' , 'TextBox2', 'TextBox3, etc.

Is it possible in C#?

答:
You could if you use Control.FindControl</p>

```<code>protected void Button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < 5; i++)
        {
            TextBox currenTextBox = (TextBox) FindControl("TextBox" + i);
            if (!string.IsNullOrEmpty(currenTextBox?.Text))
            {
                if (double.TryParse(currenTextBox.Text, out var result))
                {
                    array[i] = result;
                }
            }
        }
    }
</code>```

Body:
public partial class _Default : System.Web.UI.Page
{
    double[] array = new double[5];
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        for(int i=0;i<5;i++)
        {
            array[i] = Convert.ToDouble(TextBox(i+1).Text);
        }
    }
}

This is my code, I have 5 textboxes, I'd like to refer to them with the int (i) inside the loop.

array[i] = Convert.ToDouble(TextBox(i+1).Text);

the text boxes are named 'TextBox1' , 'TextBox2', 'TextBox3, etc.

Is it possible in C#?

Body:
You could if you use Control.FindControl

protected void Button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < 5; i++)
        {
            TextBox currenTextBox = (TextBox) FindControl("TextBox" + i);
            if (!string.IsNullOrEmpty(currenTextBox?.Text))
            {
                if (double.TryParse(currenTextBox.Text, out var result))
                {
                    array[i] = result;
                }
            }
        }
    }


问:
awk include column value in pattern
I am looking for a way to pattern match against another column in awk. For example, I wish to find rows for which the value in column 4 is nested in column 5.

Performing awk '$4 ~ /$5/' doesn't work, as the dollar sign is interpreted as part of the regular expression. How do I get the column 5 value into this pattern match!

Many thanks!

答:
if you're looking for literal match, not regex; you can use

```<code>awk 'index($5,$4)' file
</code>```

will print the lines where $4 is a substring of $5.

Title: awk include column value in pattern

Body:
if you're looking for literal match, not regex; you can use

awk 'index($5,$4)' file

will print the lines where $4 is a substring of $5.


问:
Kafka console producer skipping messages
I'm trying to send a file to a topic using:

```<code>cat myfile | kafka-console-producer.sh --broker-list $BROKER_URL --topic mytopic
</code>```

When I check the count of messages on the topic I see few hundred messages less than actual.

During the write I see a message:

```<code>[2017-11-15 14:05:26,864] WARN Error while fetching metadata with correlation id 0 : {abc123=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)
</code>```

I have correctly set the advertised hostname and listeners.

What confuses me is that if leader is not available how does it manage to put any messages into the topic? Furthermore, the message appears randomly, sometimes it doesn't.

How can I debug this?

答:
As pointed out by vahid in comments this is a know issue.

The workaround is to specify --request-required-acks 1 to the console producer.

The random occurence of LEADER_NOT_AVAILABLE happens when I write to a new topic without explicitly creating it first. (Thanks to amethystic)

Body:
I'm trying to send a file to a topic using:

cat myfile | kafka-console-producer.sh --broker-list $BROKER_URL --topic mytopic

When I check the count of messages on the topic I see few hundred messages less than actual.

During the write I see a message:

[2017-11-15 14:05:26,864] WARN Error while fetching metadata with correlation id 0 : {abc123=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)

I have correctly set the advertised hostname and listeners.

What confuses me is that if leader is not available how does it manage to put any messages into the topic? Furthermore, the message appears randomly, sometimes it doesn't.

How can I debug this?


问:
List distinct names Big Query
I have the following table in Big Query:

```<code>|event  |count
|event1 |1
|event2 |2
|event1 |2
|event2 |1
|event3 |4
|event1 |3
|event3 |5
|event4 |5
|event5 |4
|event1 |3
|event6 |5
|event4 |5
</code>```

That contains 6 different events:

```<code>COUNT(DISTINCT event) AS Dist_event_Count = 6
</code>```

Now I want to list the different events. What query should I do to obtain the following output?

```<code>|event1
|event2
|event3
|event4
|event5
|event6
</code>```

答:
Below is for BigQuery Standard SQL   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH `project.dataset.yourTable` AS (
  SELECT 'event1' event, 1 cnt UNION ALL
  SELECT 'event2', 2 UNION ALL
  SELECT 'event1', 2 UNION ALL
  SELECT 'event2', 1 UNION ALL
  SELECT 'event3', 4 UNION ALL
  SELECT 'event1', 3 UNION ALL
  SELECT 'event3', 5 UNION ALL
  SELECT 'event4', 5 UNION ALL
  SELECT 'event5', 4 UNION ALL
  SELECT 'event1', 3 UNION ALL
  SELECT 'event6', 5 UNION ALL
  SELECT 'event4', 5
)
SELECT DISTINCT event
FROM `project.dataset.yourTable`
</code>```

<p>Or  - yo can use <code>GROUP BY</code> so in this case you can also aggregate respective counts as below  </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH `project.dataset.yourTable` AS (
  SELECT 'event1' event, 1 cnt UNION ALL
  SELECT 'event2', 2 UNION ALL
  SELECT 'event1', 2 UNION ALL
  SELECT 'event2', 1 UNION ALL
  SELECT 'event3', 4 UNION ALL
  SELECT 'event1', 3 UNION ALL
  SELECT 'event3', 5 UNION ALL
  SELECT 'event4', 5 UNION ALL
  SELECT 'event5', 4 UNION ALL
  SELECT 'event1', 3 UNION ALL
  SELECT 'event6', 5 UNION ALL
  SELECT 'event4', 5
)
SELECT event, SUM(cnt) cnt
FROM `project.dataset.yourTable`
GROUP BY event
</code>```

Title: List distinct names Big Query

Body:
I have the following table in Big Query:

|event  |count
|event1 |1
|event2 |2
|event1 |2
|event2 |1
|event3 |4
|event1 |3
|event3 |5
|event4 |5
|event5 |4
|event1 |3
|event6 |5
|event4 |5

That contains 6 different events:

COUNT(DISTINCT event) AS Dist_event_Count = 6

Now I want to list the different events. What query should I do to obtain the following output?

|event1
|event2
|event3
|event4
|event5
|event6

Body:
Below is for BigQuery Standard SQL

#standardSQL
WITH `project.dataset.yourTable` AS (
  SELECT 'event1' event, 1 cnt UNION ALL
  SELECT 'event2', 2 UNION ALL
  SELECT 'event1', 2 UNION ALL
  SELECT 'event2', 1 UNION ALL
  SELECT 'event3', 4 UNION ALL
  SELECT 'event1', 3 UNION ALL
  SELECT 'event3', 5 UNION ALL
  SELECT 'event4', 5 UNION ALL
  SELECT 'event5', 4 UNION ALL
  SELECT 'event1', 3 UNION ALL
  SELECT 'event6', 5 UNION ALL
  SELECT 'event4', 5
)
SELECT DISTINCT event
FROM `project.dataset.yourTable`

Or  - yo can use GROUP BY so in this case you can also aggregate respective counts as below

#standardSQL
WITH `project.dataset.yourTable` AS (
  SELECT 'event1' event, 1 cnt UNION ALL
  SELECT 'event2', 2 UNION ALL
  SELECT 'event1', 2 UNION ALL
  SELECT 'event2', 1 UNION ALL
  SELECT 'event3', 4 UNION ALL
  SELECT 'event1', 3 UNION ALL
  SELECT 'event3', 5 UNION ALL
  SELECT 'event4', 5 UNION ALL
  SELECT 'event5', 4 UNION ALL
  SELECT 'event1', 3 UNION ALL
  SELECT 'event6', 5 UNION ALL
  SELECT 'event4', 5
)
SELECT event, SUM(cnt) cnt
FROM `project.dataset.yourTable`
GROUP BY event