问:
Bitmap explosion animation spinning in one place, not moving outward
I have a short game using a SurfaceView. My "ship" is just a white rectangle, and the obstacles are bitmaps of asteroids. When an asteroid collides with the ship, an explosion animation is supposed to take place where 20 pieces of debris (just a 10 x 10 white dot) fly out in all directions.

The problem is that when the collision occurs, all the debris just sits in one place spinning in a circle, as shown here:

The explosion does indeed start at the exact position of my ship. The particles  just don't move outward. Have I placed the code in the wrong place? Does anyone know where I have gone wrong with this?

Here is the class:

```<code>import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.Random;

public class GameView extends SurfaceView implements Runnable, SurfaceHolder.Callback {

    private Thread gameViewThread = null;
    SurfaceHolder surfaceHolder;
    boolean okToRun;

    /*
    SHIP AND ASTEROID STUFF
     */
    private Ship ship;
    private Point shipPoint;
    private Rect textRect = new Rect();
    private float oldX;
    private float oldY;
    private AsteroidController asteroidController;
    /*
    END SHIP AND ASTEROID STUFF
     */

    /*
    GAME OVER STUFF
     */
    private boolean isMoving = false;
    private boolean isGameOver = false;
    private long waitTime;
    /*
    END GAME OVER STUFF
     */

    /*
    EXPLOSION STUFF
     */
    Bitmap explosionBMP;
    private Matrix[] explosion = new Matrix[20];
    boolean isDestroyed = false;
    boolean explosionStarted = false;
    float[] explosionXPosition = new float[20];
    float[] explosionYPosition = new float[20];
    float explosionSpeed = 20.0f;
    float[] explosionRotation = new float[20];
    /*
    END EXPLOSION STUFF
     */

     /*
    SCREEN DIMENSIONS
     */
    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    int gameWidth = displayMetrics.widthPixels;
    int gameHeight = displayMetrics.heightPixels;
    /*
    END SCREEN DIMENSIONS
     */

    public GameView(Context context) {
        super(context);

        surfaceHolder = this.getHolder();
        okToRun = true;

        ship = new Ship(new Rect(100, 100, 200, 200), Color.WHITE);
        shipPoint = new Point(gameWidth / 2, 3 * gameHeight / 4);
        ship.update(shipPoint);

        asteroidController = new AsteroidController(context);

        //JUST SPAWNING ONE ASTEROID FOR NOW
        asteroidController.createAsteroid(1);

        //JUST A 10 x 10 WHITE DOT
        explosionBMP = BitmapFactory.decodeResource(getResources(), R.drawable.explosion_debris);

        //DON'T WANT A NULL POINTER RIGHT OFF THE BAT
        for(int i = 0; i < explosion.length; i++) {
            explosion[i] = new Matrix();
        }

        setFocusable(true);
    }

    @Override
    public void run() {
        while(okToRun) {
            if(!surfaceHolder.getSurface().isValid()) {
                continue;
            }
            Canvas gameCanvas = surfaceHolder.lockCanvas();

            this.update();
            this.draw(gameCanvas);
            surfaceHolder.unlockCanvasAndPost(gameCanvas);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:

                isMoving = true;
                oldX = event.getX();
                oldY = event.getY();
                if (isGameOver && System.currentTimeMillis() - waitTime >= 3000) {
                    isGameOver = false;
                    resetGame();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (!isGameOver && isMoving) {

                    /*
                    THIS CODE ALLOWS TOUCH EVENT TO BE ANYWHERE ON SCREEN WHILE
                    SHIP MOVES ACCORDINGLY
                     */
                    float newX = event.getX();
                    float newY = event.getY();
                    float deltaX = getOffsetCoords(oldX, newX, shipPoint.x);
                    float deltaY = getOffsetCoords(oldY, newY, shipPoint.y);
                    shipPoint.set((int) deltaX, (int) deltaY);
                    oldX = newX;
                    oldY = newY;
                }
                return false;
        }
        return true;
    }

    /*
    GET THE DIFFERENCE IN SHIP COORDS AND TOUCH COORDS
     */
    private float getOffsetCoords(float oldVal, float newVal, float current) {
        return current + (newVal - oldVal);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        //RANDOMS FOR STARS
        Random random0 = new Random();
        Random random1 = new Random();

        //BACKGROUND
        canvas.drawColor(Color.BLACK);
        Bitmap single_pixel_star = BitmapFactory.decodeResource(getResources(), R.drawable.single_pixel_star);
        Bitmap three_pixel_star = BitmapFactory.decodeResource(getResources(), R.drawable.three_pixel_star);

        //Draw random stars on the canvas
        canvas.drawBitmap(single_pixel_star, random0.nextInt(canvas.getWidth() - single_pixel_star.getWidth()), random0.nextInt(canvas.getHeight() - three_pixel_star.getHeight()), null);
        canvas.drawBitmap(three_pixel_star, random1.nextInt(canvas.getWidth() - three_pixel_star.getWidth()), random1.nextInt(canvas.getHeight() - three_pixel_star.getHeight()), null);

        //DRAW ASTEROID(s)
        asteroidController.render(canvas);
        //DRAW SHIP
        ship.draw(canvas);

        if (isGameOver) {

            ship.removeShip();

            isDestroyed = true;
            explosionStarted = true;

            Paint gameOverPaint = new Paint();
            gameOverPaint.setTextSize(200);
            gameOverPaint.setColor(Color.RED);
            showGameOver(canvas, gameOverPaint, "YOU LOSE!");

            /*
            SHIP GOES KABOOM!
             */
            for(int i = 0; i < explosion.length; i++) {
                canvas.drawBitmap(explosionBMP, explosion[i], null);
            }

        }
    }
    public void update() {
        if (!isGameOver) {
            ship.update(shipPoint);
            asteroidController.update();

            if (asteroidController.isCollision(ship)) {
                isGameOver = true;
                waitTime = System.currentTimeMillis();
            }
        }
        Matrix[] localExplosionDebris = new Matrix[20];
        if(explosionStarted) {
            for(int i = 0; i < explosionXPosition.length; i++) {
                explosionXPosition[i] = getShipPointX();
                explosionYPosition[i] = getShipPointY();
                Random rand = new Random();
                explosionRotation[i] = (float) rand.nextInt(360);
            }
            explosionStarted = false;
        }
        for(int i = 0; i < localExplosionDebris.length; i++) {
            localExplosionDebris[i] = new Matrix();
        }
        if(isDestroyed) {
            for(int i = 0; i < localExplosionDebris.length; i++) {
                float debrisXSpeed = (float) Math.sin(explosionRotation[i]*(Math.PI/180)) * explosionSpeed - .2f;
                float debrisYSpeed = (float) Math.cos(explosionRotation[i]*(Math.PI/180)) * explosionSpeed - .2f;

                explosionXPosition[i] += debrisXSpeed;
                explosionYPosition[i] -= debrisYSpeed;

                localExplosionDebris[i].postRotate(0, explosionBMP.getWidth()/2, explosionBMP.getHeight()/2);
                localExplosionDebris[i].postTranslate(explosionXPosition[i], explosionYPosition[i]);

                explosion[i].set(localExplosionDebris[i]);
            }
        }
    }

    /*
    SHOW GAME OVER TEXT ON THE CENTER OF THE SCREEN UNTIL 3 SECONDS HAVE PASSED AND TOUCH EVENT OCCURS
     */
    private void showGameOver(Canvas canvas, Paint paint, String gameOverString) {
        paint.setTextAlign(Paint.Align.LEFT);
        canvas.getClipBounds(textRect);
        int canvasH = textRect.height();
        int canvasW = textRect.width();
        paint.getTextBounds(gameOverString, 0, gameOverString.length(), textRect);
        float textX = canvasW / 2f - textRect.width() / 2f - textRect.left;
        float textY = canvasH / 2f - textRect.height() / 2f - textRect.bottom;
        canvas.drawText(gameOverString, textX, textY, paint);
    }

    /*
    RESET SHIP TO ORIGINAL LOCATION AND COLOR
     */
    public void resetGame() {
        ship = new Ship(new Rect(100, 100, 200, 200), Color.WHITE);
        shipPoint = new Point(gameWidth / 2, 3 * gameHeight / 4);

        //TODO STOP BG MUSIC ONCE FILE IS ADDED
        //TODO RESET SCORE ONCE ADDED
    }

    public void pause() {
        okToRun = false;
        while(true) {
            try {
                gameViewThread.join();
            } catch(InterruptedException e) {
                Log.d("ERROR", e.getMessage());
            }
            break;
        }
        gameViewThread = null;
    }

    public void resume() {
        okToRun = true;
        gameViewThread = new Thread(this);
        gameViewThread.start();

    }

    /*
    SELF EXPLANATORY
     */
    public int getShipPointX() {
        return shipPoint.x;
    }

    public int getShipPointY() {
        return shipPoint.y;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }
}
</code>```

答:
I rearranged some boolean variables and I now have an explosion. In the following if statement, you can see what I commented out:

```<code>if (isGameOver) {

        ship.removeShip();

        //isDestroyed = true;
        //explosionStarted = true;
        Paint gameOverPaint = new Paint();
        gameOverPaint.setTextSize(200);
        gameOverPaint.setColor(Color.RED);
        showGameOver(canvas, gameOverPaint, "YOU LOSE!");

        /*
        SHIP GOES KABOOM!
         */
        for(int i = 0; i < explosion.length; i++) {
            canvas.drawBitmap(explosionBMP, explosion[i], null);
        }

    }
</code>```

And in another if statement, I added a condition, placed the commented out booleans (shown above) to that statement, then reset them in an else:

```<code>if (!isGameOver) {
        ship.update(shipPoint);
        asteroidController.update();

        if (asteroidController.isCollision(ship) && !isDestroyed) { //<--added the && !isDestroyed
            isGameOver = true;
            isDestroyed = true; //<-- added this
            explosionStarted = true; //<-- and this
            waitTime = System.currentTimeMillis();
        } else {
            isGameOver = false; //<-- then reset here
            isDestroyed = false; //<-- and here
            explosionStarted = false; //<-- and here
        }
    }
</code>```

All done. :-)

Body:
I have a short game using a SurfaceView. My "ship" is just a white rectangle, and the obstacles are bitmaps of asteroids. When an asteroid collides with the ship, an explosion animation is supposed to take place where 20 pieces of debris (just a 10 x 10 white dot) fly out in all directions.

The problem is that when the collision occurs, all the debris just sits in one place spinning in a circle, as shown here:

The explosion does indeed start at the exact position of my ship. The particles  just don't move outward. Have I placed the code in the wrong place? Does anyone know where I have gone wrong with this?

Here is the class:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.Random;

public class GameView extends SurfaceView implements Runnable, SurfaceHolder.Callback {

    private Thread gameViewThread = null;
    SurfaceHolder surfaceHolder;
    boolean okToRun;

    /*
    SHIP AND ASTEROID STUFF
     */
    private Ship ship;
    private Point shipPoint;
    private Rect textRect = new Rect();
    private float oldX;
    private float oldY;
    private AsteroidController asteroidController;
    /*
    END SHIP AND ASTEROID STUFF
     */

    /*
    GAME OVER STUFF
     */
    private boolean isMoving = false;
    private boolean isGameOver = false;
    private long waitTime;
    /*
    END GAME OVER STUFF
     */

    /*
    EXPLOSION STUFF
     */
    Bitmap explosionBMP;
    private Matrix[] explosion = new Matrix[20];
    boolean isDestroyed = false;
    boolean explosionStarted = false;
    float[] explosionXPosition = new float[20];
    float[] explosionYPosition = new float[20];
    float explosionSpeed = 20.0f;
    float[] explosionRotation = new float[20];
    /*
    END EXPLOSION STUFF
     */

     /*
    SCREEN DIMENSIONS
     */
    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    int gameWidth = displayMetrics.widthPixels;
    int gameHeight = displayMetrics.heightPixels;
    /*
    END SCREEN DIMENSIONS
     */

    public GameView(Context context) {
        super(context);

        surfaceHolder = this.getHolder();
        okToRun = true;

        ship = new Ship(new Rect(100, 100, 200, 200), Color.WHITE);
        shipPoint = new Point(gameWidth / 2, 3 * gameHeight / 4);
        ship.update(shipPoint);

        asteroidController = new AsteroidController(context);

        //JUST SPAWNING ONE ASTEROID FOR NOW
        asteroidController.createAsteroid(1);

        //JUST A 10 x 10 WHITE DOT
        explosionBMP = BitmapFactory.decodeResource(getResources(), R.drawable.explosion_debris);

        //DON'T WANT A NULL POINTER RIGHT OFF THE BAT
        for(int i = 0; i < explosion.length; i++) {
            explosion[i] = new Matrix();
        }

        setFocusable(true);
    }

    @Override
    public void run() {
        while(okToRun) {
            if(!surfaceHolder.getSurface().isValid()) {
                continue;
            }
            Canvas gameCanvas = surfaceHolder.lockCanvas();

            this.update();
            this.draw(gameCanvas);
            surfaceHolder.unlockCanvasAndPost(gameCanvas);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:

                isMoving = true;
                oldX = event.getX();
                oldY = event.getY();
                if (isGameOver && System.currentTimeMillis() - waitTime >= 3000) {
                    isGameOver = false;
                    resetGame();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (!isGameOver && isMoving) {

                    /*
                    THIS CODE ALLOWS TOUCH EVENT TO BE ANYWHERE ON SCREEN WHILE
                    SHIP MOVES ACCORDINGLY
                     */
                    float newX = event.getX();
                    float newY = event.getY();
                    float deltaX = getOffsetCoords(oldX, newX, shipPoint.x);
                    float deltaY = getOffsetCoords(oldY, newY, shipPoint.y);
                    shipPoint.set((int) deltaX, (int) deltaY);
                    oldX = newX;
                    oldY = newY;
                }
                return false;
        }
        return true;
    }

    /*
    GET THE DIFFERENCE IN SHIP COORDS AND TOUCH COORDS
     */
    private float getOffsetCoords(float oldVal, float newVal, float current) {
        return current + (newVal - oldVal);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        //RANDOMS FOR STARS
        Random random0 = new Random();
        Random random1 = new Random();

        //BACKGROUND
        canvas.drawColor(Color.BLACK);
        Bitmap single_pixel_star = BitmapFactory.decodeResource(getResources(), R.drawable.single_pixel_star);
        Bitmap three_pixel_star = BitmapFactory.decodeResource(getResources(), R.drawable.three_pixel_star);

        //Draw random stars on the canvas
        canvas.drawBitmap(single_pixel_star, random0.nextInt(canvas.getWidth() - single_pixel_star.getWidth()), random0.nextInt(canvas.getHeight() - three_pixel_star.getHeight()), null);
        canvas.drawBitmap(three_pixel_star, random1.nextInt(canvas.getWidth() - three_pixel_star.getWidth()), random1.nextInt(canvas.getHeight() - three_pixel_star.getHeight()), null);

        //DRAW ASTEROID(s)
        asteroidController.render(canvas);
        //DRAW SHIP
        ship.draw(canvas);

        if (isGameOver) {

            ship.removeShip();

            isDestroyed = true;
            explosionStarted = true;

            Paint gameOverPaint = new Paint();
            gameOverPaint.setTextSize(200);
            gameOverPaint.setColor(Color.RED);
            showGameOver(canvas, gameOverPaint, "YOU LOSE!");

            /*
            SHIP GOES KABOOM!
             */
            for(int i = 0; i < explosion.length; i++) {
                canvas.drawBitmap(explosionBMP, explosion[i], null);
            }

        }
    }
    public void update() {
        if (!isGameOver) {
            ship.update(shipPoint);
            asteroidController.update();

            if (asteroidController.isCollision(ship)) {
                isGameOver = true;
                waitTime = System.currentTimeMillis();
            }
        }
        Matrix[] localExplosionDebris = new Matrix[20];
        if(explosionStarted) {
            for(int i = 0; i < explosionXPosition.length; i++) {
                explosionXPosition[i] = getShipPointX();
                explosionYPosition[i] = getShipPointY();
                Random rand = new Random();
                explosionRotation[i] = (float) rand.nextInt(360);
            }
            explosionStarted = false;
        }
        for(int i = 0; i < localExplosionDebris.length; i++) {
            localExplosionDebris[i] = new Matrix();
        }
        if(isDestroyed) {
            for(int i = 0; i < localExplosionDebris.length; i++) {
                float debrisXSpeed = (float) Math.sin(explosionRotation[i]*(Math.PI/180)) * explosionSpeed - .2f;
                float debrisYSpeed = (float) Math.cos(explosionRotation[i]*(Math.PI/180)) * explosionSpeed - .2f;

                explosionXPosition[i] += debrisXSpeed;
                explosionYPosition[i] -= debrisYSpeed;

                localExplosionDebris[i].postRotate(0, explosionBMP.getWidth()/2, explosionBMP.getHeight()/2);
                localExplosionDebris[i].postTranslate(explosionXPosition[i], explosionYPosition[i]);

                explosion[i].set(localExplosionDebris[i]);
            }
        }
    }

    /*
    SHOW GAME OVER TEXT ON THE CENTER OF THE SCREEN UNTIL 3 SECONDS HAVE PASSED AND TOUCH EVENT OCCURS
     */
    private void showGameOver(Canvas canvas, Paint paint, String gameOverString) {
        paint.setTextAlign(Paint.Align.LEFT);
        canvas.getClipBounds(textRect);
        int canvasH = textRect.height();
        int canvasW = textRect.width();
        paint.getTextBounds(gameOverString, 0, gameOverString.length(), textRect);
        float textX = canvasW / 2f - textRect.width() / 2f - textRect.left;
        float textY = canvasH / 2f - textRect.height() / 2f - textRect.bottom;
        canvas.drawText(gameOverString, textX, textY, paint);
    }

    /*
    RESET SHIP TO ORIGINAL LOCATION AND COLOR
     */
    public void resetGame() {
        ship = new Ship(new Rect(100, 100, 200, 200), Color.WHITE);
        shipPoint = new Point(gameWidth / 2, 3 * gameHeight / 4);

        //TODO STOP BG MUSIC ONCE FILE IS ADDED
        //TODO RESET SCORE ONCE ADDED
    }

    public void pause() {
        okToRun = false;
        while(true) {
            try {
                gameViewThread.join();
            } catch(InterruptedException e) {
                Log.d("ERROR", e.getMessage());
            }
            break;
        }
        gameViewThread = null;
    }

    public void resume() {
        okToRun = true;
        gameViewThread = new Thread(this);
        gameViewThread.start();

    }

    /*
    SELF EXPLANATORY
     */
    public int getShipPointX() {
        return shipPoint.x;
    }

    public int getShipPointY() {
        return shipPoint.y;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }
}

Body:
I rearranged some boolean variables and I now have an explosion. In the following if statement, you can see what I commented out:

if (isGameOver) {

        ship.removeShip();

        //isDestroyed = true;
        //explosionStarted = true;
        Paint gameOverPaint = new Paint();
        gameOverPaint.setTextSize(200);
        gameOverPaint.setColor(Color.RED);
        showGameOver(canvas, gameOverPaint, "YOU LOSE!");

        /*
        SHIP GOES KABOOM!
         */
        for(int i = 0; i < explosion.length; i++) {
            canvas.drawBitmap(explosionBMP, explosion[i], null);
        }

    }

And in another if statement, I added a condition, placed the commented out booleans (shown above) to that statement, then reset them in an else:

if (!isGameOver) {
        ship.update(shipPoint);
        asteroidController.update();

        if (asteroidController.isCollision(ship) && !isDestroyed) { //<--added the && !isDestroyed
            isGameOver = true;
            isDestroyed = true; //<-- added this
            explosionStarted = true; //<-- and this
            waitTime = System.currentTimeMillis();
        } else {
            isGameOver = false; //<-- then reset here
            isDestroyed = false; //<-- and here
            explosionStarted = false; //<-- and here
        }
    }

All done. :-)


来源: stackexchange

问:
unable to type in field using send keys protractor code
By using below code can any one suggest me how to send keys in text area

```<code><div  *ngIf="showJournalsEditor">
  <form *ngIf="showJournalsEditor" [formGroup]="ToolsJournalsForm" Class="toolsJournalsFormClass" >
    <div [froalaEditor]="options" formControlName="journalsDescription" [style]="{'height':'320px'}">
    </div>
</code>```

I have tried but getting below error

Failed: unknown error: cannot focus element
(Session info: chrome=62.0.3202.94)
(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10
.0.15063 x86_64)

答:
You tried to select the element using
element(by.css('div[formControlName="journalsDescription"]'));

However journalsDescription element is not an input and you cannot focus on this element (as the error tells you: cannot focus element)

You need to select editable element and use it to sendKeys.

Example:
element(by.css('div[formControlName="journalsDescription"] input')); }

ContentLicense: CC BY-SA 3.0

Body:
By using below code can any one suggest me how to send keys in text area

  <form *ngIf="showJournalsEditor" [formGroup]="ToolsJournalsForm" Class="toolsJournalsFormClass" >

I have tried but getting below error

Failed: unknown error: cannot focus element
(Session info: chrome=62.0.3202.94)
(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10
.0.15063 x86_64)


问:
Angular 1.5 - Insert custom element after last element with certain property
Let's assume I'm having following code:

```<code><li ng-repeat="task in todoList">
    {{task.name}}
</li>
</code>```

And let's assume this is my dataset ( Assuming it's ordered by when, from now to future ) :

```<code>var todoList = [ { name : 'Work hard', when : 'Today'}, { name : 'Play hard', when : 'Today'}, { name : 'Relax hard', when : 'This week'}, ]
</code>```

How can I detect in the ng-repeat when the current repeated item is the last item with the property when set to Today ?

So I'll end up something with something like this

```<code><li ng-repeat="task in todoList">
    {{task.name}}
</li>
<!-- If last of current period, then show this -->
<li>
    <h3>Next period</h3>
</li>
</code>```

答:
```<code><li ng-repeat="task in todoList" ng-show="!$last">
    {{task.name}}
</li>
  <li ng-repeat="task in todoList" ng-show="$last">
   <h3>Next period</h3>
</li>
</code>```

$last will help on this

Body:
Let's assume I'm having following code:

    {{task.name}}

And let's assume this is my dataset ( Assuming it's ordered by when, from now to future ) :

var todoList = [ { name : 'Work hard', when : 'Today'}, { name : 'Play hard', when : 'Today'}, { name : 'Relax hard', when : 'This week'}, ]

How can I detect in the ng-repeat when the current repeated item is the last item with the property when set to Today ?

So I'll end up something with something like this

    {{task.name}}

Next period

Body:
<li ng-repeat="task in todoList" ng-show="!$last">
    {{task.name}}
</li>
  <li ng-repeat="task in todoList" ng-show="$last">
   <h3>Next period</h3>
</li>

$last will help on this


问:
How will JDK9 modules help for 'package-scoped sub-packages'?
I am wondering about JDK9 modules. Say you have the following 3 packages:

```<code>com.company.product
com.company.product.impl_a
com.company.product.impl_b
</code>```

Classes in package product.impl_a and product.impl_b can only be accessed by classes in package product. The user should only use classes from product package. You can imagine that passing certain flags or properties will decide whether impl_a or impl_b will be used, internally.

In JDK8-, you have to make these classes inside impl_a and impl_b public. This kinda sucks, because users can be tricked that they can use these classes. It's perfectly valid and allowed.

How can JDK9 help here? Will we declare a module for product.impl_a and another one for product.impl_b and declare that the exported classes are only to be accessed by a third module product, which will depend on the two modules product.impl_a and product.impl_b? In addition, it will be effectively impossible to declare a new module which will depend on product.impl_a or product.impl_b? Can other modules only depend on module product?

答:
Nothing in your question seems to indicate that these three packages need to end up in different JARs/modules. If they don't, simply put them into the same JAR, use the visibility modifiers as described, and use the following module declaration:

```<code>module com.company.product {
    export com.company.product;
}
</code>```

Then within module com.company.product you can use code from all packages as you normally would, but from outside only com.company.product is accessible.

Body:
I am wondering about JDK9 modules. Say you have the following 3 packages:

com.company.product
com.company.product.impl_a
com.company.product.impl_b

Classes in package product.impl_a and product.impl_b can only be accessed by classes in package product. The user should only use classes from product package. You can imagine that passing certain flags or properties will decide whether impl_a or impl_b will be used, internally.

In JDK8-, you have to make these classes inside impl_a and impl_b public. This kinda sucks, because users can be tricked that they can use these classes. It's perfectly valid and allowed.

How can JDK9 help here? Will we declare a module for product.impl_a and another one for product.impl_b and declare that the exported classes are only to be accessed by a third module product, which will depend on the two modules product.impl_a and product.impl_b? In addition, it will be effectively impossible to declare a new module which will depend on product.impl_a or product.impl_b? Can other modules only depend on module product?

Body:
Nothing in your question seems to indicate that these three packages need to end up in different JARs/modules. If they don't, simply put them into the same JAR, use the visibility modifiers as described, and use the following module declaration:

module com.company.product {
    export com.company.product;
}

Then within module com.company.product you can use code from all packages as you normally would, but from outside only com.company.product is accessible.


问:
Login with facebook error: ERR_TOO_MANY_REDIRECTS
I am trying to login with facebook but i am getting too many redirect error. Please help me how to fix it.

I have tried Browser cookie clear does not work.

```<code><?php
require 'facebook/facebook.php';
require 'config/fbconfig.php';
require 'config/functions.php';

$facebook = new Facebook(array(
            'appId' => APP_ID,
            'secret' => APP_SECRET,
            ));

$user = $facebook->getUser();

// I think i am not getting user. So i get 0 in user.
if ($user) {

  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }

    if (!empty($user_profile )) {
        # User info ok? Let's print it (Here we will be adding the login and registering routines)
        $username = $user_profile['name'];
        $uid = $user_profile['id'];
        $email = $user_profile['email'];
        $user = new User();

                $img = file_get_contents('https://graph.facebook.com/'.$user_profile['id'].'/picture?type=large');
                $file = $_SESSION['SITE_IMG_PATH'].'userimage/'.$user_profile['id'].'.jpg';
                file_put_contents($file, $img);
                $userimage=$user_profile['id'].'.jpg';
        $userdata = $user->checkUser($uid, 'facebook', $username,$email,$twitter_otoken,$twitter_otoken_secret,$userimage);

        if(!empty($userdata)){
            session_start();
            $_SESSION['frontuser_info'] = $userdata;

            $Qparam=$fid.''.$sid.''.$tid;

            header("Location: ".$_SESSION['APP_PATH']."".$Qparam);

        }
    } else {
        # For testing purposes, if there was an error, let's kill the script
        die("There was an error.");
    }
} else {

    # There's no active session, let's generate one

    $login_url = $facebook->getLoginUrl(array( 'scope' => 'email'));

    # i think it is always coming here thats error.
    header("Location: " . $login_url);
}

?>
</code>```

Please see code and help me to fix this redirection error i am always going in else part thats error.

答:
There seems to be some issue with your Facebook Plugin, that's why $user coming as 0. There can be many other reason behind it too. You need to re-check your APP_ID and APP_SECRET as well.

Most importantly, you need to follow below links and update accordingly.

https://github.com/facebook/php-graph-sdk

Or

https://developers.facebook.com/docs/facebook-login/web/login-button/

Body:
I am trying to login with facebook but i am getting too many redirect error. Please help me how to fix it.

I have tried Browser cookie clear does not work.

<?php
require 'facebook/facebook.php';
require 'config/fbconfig.php';
require 'config/functions.php';

$facebook = new Facebook(array(
            'appId' => APP_ID,
            'secret' => APP_SECRET,
            ));

$user = $facebook->getUser();

// I think i am not getting user. So i get 0 in user.
if ($user) {

  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }

    if (!empty($user_profile )) {
        # User info ok? Let's print it (Here we will be adding the login and registering routines)
        $username = $user_profile['name'];
        $uid = $user_profile['id'];
        $email = $user_profile['email'];
        $user = new User();

                $img = file_get_contents('https://graph.facebook.com/'.$user_profile['id'].'/picture?type=large');
                $file = $_SESSION['SITE_IMG_PATH'].'userimage/'.$user_profile['id'].'.jpg';
                file_put_contents($file, $img);
                $userimage=$user_profile['id'].'.jpg';
        $userdata = $user->checkUser($uid, 'facebook', $username,$email,$twitter_otoken,$twitter_otoken_secret,$userimage);

        if(!empty($userdata)){
            session_start();
            $_SESSION['frontuser_info'] = $userdata;

            $Qparam=$fid.''.$sid.''.$tid;

            header("Location: ".$_SESSION['APP_PATH']."".$Qparam);

        }
    } else {
        # For testing purposes, if there was an error, let's kill the script
        die("There was an error.");
    }
} else {

    # There's no active session, let's generate one

    $login_url = $facebook->getLoginUrl(array( 'scope' => 'email'));

    # i think it is always coming here thats error.
    header("Location: " . $login_url);
}

?>

Please see code and help me to fix this redirection error i am always going in else part thats error.


问:
remove array object from nested array if element is undefined using javascript
Raw array

```<code>myArr = [
{name:'abcd',values:[undefined,{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129},undefined]},
{name:'abcd',values:[undefined,undefined,{quarter: "Q4-2016", koordinaten: 19},undefined]}
]
</code>```

Expected array,

```<code> myArr = [
        {name:'abcd',values:[{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129}},
        {name:'abcd',values:[{quarter: "Q4-2016", koordinaten: 19}]}
        ]
</code>```

i want to remove undefined element with index  in result array,

答:
You could filter falsy values (like undefined) with Array#filter and Boolean as callback.

var array = [{ name: 'abcd', values: [undefined, { quarter: "Q2-2016", koordinaten: 119 }, { quarter: "Q3-2016", koordinaten: 129 }, undefined] }, { name: 'abcd', values: [undefined, undefined, { quarter: "Q4-2016", koordinaten: 19 }, undefined] }];

array.forEach(function (o) {
    o.values = o.values.filter(Boolean);
});

console.log(array);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
Raw array

myArr = [
{name:'abcd',values:[undefined,{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129},undefined]},
{name:'abcd',values:[undefined,undefined,{quarter: "Q4-2016", koordinaten: 19},undefined]}
]

Expected array,

 myArr = [
        {name:'abcd',values:[{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129}},
        {name:'abcd',values:[{quarter: "Q4-2016", koordinaten: 19}]}
        ]

i want to remove undefined element with index  in result array,

Body:
You could filter falsy values (like undefined) with Array#filter and Boolean as callback.

var array = [{ name: 'abcd', values: [undefined, { quarter: "Q2-2016", koordinaten: 119 }, { quarter: "Q3-2016", koordinaten: 129 }, undefined] }, { name: 'abcd', values: [undefined, undefined, { quarter: "Q4-2016", koordinaten: 19 }, undefined] }];

array.forEach(function (o) {
    o.values = o.values.filter(Boolean);
});

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
iOS Push Notification Settings - Denied Permission vs Permission Never Requested
Is it possible to differentiate between the cases where

an iOS user has explicitly denied user notification permissions, and

an iOS user has never been prompted for permission?

My situation: In the past, I've prompted for user notification permission, but never kept track of requests myself. Later, I stopped attempting to register any notification settings. Now, I'd like to re-introduce user notifications.

After a significant event in the App, my plan is to display some sort of UI that explains the benefit of opting in to user notifications. However, if the user has already declined, I'd prefer to show a separate UI that can take them into Settings.app.

Currently, I'm using -[UIApplication currentUserNotificationSettings] to grab the current settings, but it appears that this returns UIUserNotificationTypeNone for both of the above described cases.

答:
If you support iOS 10 and above the UNUserNotifications framework allows more granularity.</p>

```<code>let current = UNUserNotificationCenter.current()
current.getNotificationSettings(completionHandler: { (settings) in
    if settings.authorizationStatus == .notDetermined {
        // Not requested
    }

    if settings.authorizationStatus == .denied {
        // User said Don't allow
    }
})
</code>```

Body:
If you support iOS 10 and above the UNUserNotifications framework allows more granularity.

let current = UNUserNotificationCenter.current()
current.getNotificationSettings(completionHandler: { (settings) in
    if settings.authorizationStatus == .notDetermined {
        // Not requested
    }

    if settings.authorizationStatus == .denied {
        // User said Don't allow
    }
})


问:
Xsl transformation of large xmls
I am aware of ways of applying XSL transformation to XMLs in java using

javax.xml.transform.Transformer

This approach works well for small XML data. But when it comes to large XML data where DOM based approach is difficult to use because of memory constraints, this becomes a nightmare.

I want to know what is the best approach to apply XSL transformation to large XMLs. Is there any transformer which operates on SAX and not DOM?

答:
There are different implementations of XSLT processors in Java that implement JAXP. Saxon 9.3 is an XSLT 2.0 processor that also implements some streaming features of the XSLT 3.0 working draft, see http://www.saxonica.com/documentation/sourcedocs/streaming.xml.
And even if you don't use the latest experimental Saxon 9.3 features it is usually a good idea not to feed a DOMSource to your processor but let the processor use its own tree implementation by feeding a StreamSource. </p>

ContentLicense: CC BY-SA 2.5

Title: Xsl transformation of large xmls


问:
C - division doesnt work
I'm actually totally stuck I don't understand the behavior of this function:

```<code>#include <stdio.h>

typedef struct s_resolution
{
   int x;
   int y;
   float fx;
   float fy;
} t_resolution;

typedef struct s_pixel_info
{
    int tablen;
    t_resolution resolution;
    char name;
    int line;
    int pos_suite[6];
    int suite[6];
} t_pixel_info;

void get_proportion_ratio(t_pixel_info DataB, t_pixel_info pix_info,
                           t_resolution *proportion)
{
    proportion->fx = (float)(DataB.resolution.x / pix_info.resolution.x);
    //I also tried without the cast
    proportion->y = (int)(DataB.resolution.y / pix_info.resolution.y * 100);
    //if (proportion->y != 100)
    printf("%d | %d | %d\n",proportion->y, DataB.resolution.y, pix_info.resolution.y);
}

int main()
{
  t_pixel_info DataB;
  t_pixel_info pix_info;
  t_resolution proportion;

  DataB.resolution.x = 5;
  pix_info.resolution.x = 10;
  DataB.resolution.y = 5;
  pix_info.resolution.y = 10;
  get_proportion_ratio(DataB, pix_info, &proportion);

}
</code>```

DataB.resolution.y, pix_info.resolution.y and proportion->y are all Int type.

My problem is that I have this result:

```<code>0 | 5 | 10
</code>```

The operation only works when the result is 100... I must be missing something obvious but I've no idea what.

答:
Since resolution.x and resolution.y are ints, the division between them will done as integer division, which keeps only the "whole" part of the division. If you want to perform a floating point ("regular") division, you should cast to a floating point type before performing the division. E.g.:

```<code>proportion->fx = ((float) DataB.resolution.x) / ((float) pix_info.resolution.x);
</code>```

Title: C - division doesnt work

Body:
I'm actually totally stuck I don't understand the behavior of this function:

#include <stdio.h>

typedef struct s_resolution
{
   int x;
   int y;
   float fx;
   float fy;
} t_resolution;

typedef struct s_pixel_info
{
    int tablen;
    t_resolution resolution;
    char name;
    int line;
    int pos_suite[6];
    int suite[6];
} t_pixel_info;

void get_proportion_ratio(t_pixel_info DataB, t_pixel_info pix_info,
                           t_resolution *proportion)
{
    proportion->fx = (float)(DataB.resolution.x / pix_info.resolution.x);
    //I also tried without the cast
    proportion->y = (int)(DataB.resolution.y / pix_info.resolution.y * 100);
    //if (proportion->y != 100)
    printf("%d | %d | %d\n",proportion->y, DataB.resolution.y, pix_info.resolution.y);
}

int main()
{
  t_pixel_info DataB;
  t_pixel_info pix_info;
  t_resolution proportion;

  DataB.resolution.x = 5;
  pix_info.resolution.x = 10;
  DataB.resolution.y = 5;
  pix_info.resolution.y = 10;
  get_proportion_ratio(DataB, pix_info, &proportion);

}

DataB.resolution.y, pix_info.resolution.y and proportion->y are all Int type.

My problem is that I have this result:

0 | 5 | 10

The operation only works when the result is 100... I must be missing something obvious but I've no idea what.

Body:
Since resolution.x and resolution.y are ints, the division between them will done as integer division, which keeps only the "whole" part of the division. If you want to perform a floating point ("regular") division, you should cast to a floating point type before performing the division. E.g.:

proportion->fx = ((float) DataB.resolution.x) / ((float) pix_info.resolution.x);


问:
how to change WordPress URL on all pages?
how to change WordPress URL on all pages? suppose we have a xyz.com. Now I want something like xyz.com/test when customer visiting to xyz.com. and for all newly created pages must be something like xyz.com/test/Newpage.</p>

答:
For example, if your new directory is called application, you would visit www.your-site.com/application/wp-admin or www.your-site.com/application/wp-login.php.

Update /wp-blog-header.php to include your new directory. For example, if your new folder is called application, you would change the file path to this: /application/wp-blog-header.php.

Change this line in the index.php int the root folder.

```<code>/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp-blog-header.php' );
</code>```

Body:
For example, if your new directory is called application, you would visit www.your-site.com/application/wp-admin or www.your-site.com/application/wp-login.php.

Update /wp-blog-header.php to include your new directory. For example, if your new folder is called application, you would change the file path to this: /application/wp-blog-header.php.

Change this line in the index.php int the root folder.

/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp-blog-header.php' );


问:
iOS 11 safe area layout guide backwards compatibility
Is enabling Safe Area Layout Guides compatible to iOS below 11?

答:
"safe area layout guide" is backward compatible. Well, unless you use it in xib. With storyboard it seems ok.

I solved my problem by accessing the "Top layout constraint" from the first object at the top of my view.

```<code>@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayoutConstraint;
</code>```

then, I changed the Constant value to that constraint and refresh the view. For example, if you use a navigation bar (44 height) plus the status bar (20 height) :

```<code>if (SYSTEM_VERSION_LESS_THAN(@"11.0")) {
    _topLayoutConstraint.constant = 64;
    [self.view layoutIfNeeded];
}
</code>```

With SYSTEM_VERSION_LESS_THAN which is defined like that :

```<code>#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
</code>```

Body:
"safe area layout guide" is backward compatible. Well, unless you use it in xib. With storyboard it seems ok.

I solved my problem by accessing the "Top layout constraint" from the first object at the top of my view.

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayoutConstraint;

then, I changed the Constant value to that constraint and refresh the view. For example, if you use a navigation bar (44 height) plus the status bar (20 height) :

if (SYSTEM_VERSION_LESS_THAN(@"11.0")) {
    _topLayoutConstraint.constant = 64;
    [self.view layoutIfNeeded];
}

With SYSTEM_VERSION_LESS_THAN which is defined like that :

#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)


问:
Splitting a string into an array then splitting the array again
I have this string:

```<code>   fname lname, GTA V: 120 : 00000, Minecraft : 20 : 10, Assassin’s Creed IV : 90 : 800, Payday 2 : 190 : 2001 ,Wolfenstein TNO : 25 : 80, FarCry 4 : 55 : 862
</code>```

I want to use a loop to split this string into an array at the comma [,] example:

```<code>[0]fname lname
[1]GTA V: 120 : 00000
[2]Minecraft : 20 : 10
[3]Assassin’s Creed IV : 90 : 800
[4]Payday 2 : 190 : 2001
[5]Wolfenstein TNO : 25 : 80
[6]FarCry 4 : 55 : 862
</code>```

Then I want to use another loop to split this further at : into another array example

```<code>[0]fname lname
[1]GTA V
[2]120
[3]00000
[4]Minecraft
[5]20
[6]10
....
</code>```

Is there a better way of doing this?

currently I have:

```<code>    List<String> lines = new ArrayList<String>();
    while (scan.hasNextLine())
    {
      lines.add(scan.nextLine());
    }

    //converts the list array to string array

    String[] scanarray = lines.toArray(new String[0]);

    //converts the string array into one large string

    String str_array = Arrays.toString(scanarray);

    String[] arraysplit;

    arraysplit = str_array.split("\\s*:\\s*");

    for (int i=0; i<arraysplit.length; i++)
    {
        arraysplit[i] = arraysplit[i].trim();
        //              ^^^^^^^^^^^^ has values with spaces
        System.out.println(scanarray[i]);
    }
</code>```

EDIT:

Currently my program creates 3 identical arrays, containing the example you can see in the second block of code above.

答:
You can achieve it what you are looking for with REGEX, just put what all thing you get separated with string split method.

I tried below code locally and it is pretty much same what you are looking for.

```<code>public class StackSol1 {

    public static void main(String[] args) {

        String str = "fname lname, GTA V: 120 : 00000, Minecraft : 20 : 10, Assassin’s Creed IV : 90 : 800, Payday 2 : 190 : 2001 ,Wolfenstein TNO : 25 :80, FarCry 4 : 55 : 862";
        String delimiters = "\\s+|,\\s*|\\:\\s*";

        // analyzing the string
        String[] tokensVal = str.split(delimiters);

        // prints the number of tokens
        System.out.println("Count of tokens = " + tokensVal.length);

        String finalStr="";

        for (String token : tokensVal) {

            finalStr = finalStr+"\n"+token;
        }

        System.out.println(finalStr);
    }

}
</code>```

Body:
I have this string:

   fname lname, GTA V: 120 : 00000, Minecraft : 20 : 10, Assassin’s Creed IV : 90 : 800, Payday 2 : 190 : 2001 ,Wolfenstein TNO : 25 : 80, FarCry 4 : 55 : 862

I want to use a loop to split this string into an array at the comma [,] example:

[0]fname lname
[1]GTA V: 120 : 00000
[2]Minecraft : 20 : 10
[3]Assassin’s Creed IV : 90 : 800
[4]Payday 2 : 190 : 2001
[5]Wolfenstein TNO : 25 : 80
[6]FarCry 4 : 55 : 862

Then I want to use another loop to split this further at : into another array example

[0]fname lname
[1]GTA V
[2]120
[3]00000
[4]Minecraft
[5]20
[6]10
....

Is there a better way of doing this?

currently I have:

    List<String> lines = new ArrayList<String>();
    while (scan.hasNextLine())
    {
      lines.add(scan.nextLine());
    }

    //converts the list array to string array

    String[] scanarray = lines.toArray(new String[0]);

    //converts the string array into one large string

    String str_array = Arrays.toString(scanarray);

    String[] arraysplit;

    arraysplit = str_array.split("\\s*:\\s*");

    for (int i=0; i<arraysplit.length; i++)
    {
        arraysplit[i] = arraysplit[i].trim();
        //              ^^^^^^^^^^^^ has values with spaces
        System.out.println(scanarray[i]);
    }

EDIT:

Currently my program creates 3 identical arrays, containing the example you can see in the second block of code above.

Body:
You can achieve it what you are looking for with REGEX, just put what all thing you get separated with string split method.

I tried below code locally and it is pretty much same what you are looking for.

public class StackSol1 {

    public static void main(String[] args) {

        String str = "fname lname, GTA V: 120 : 00000, Minecraft : 20 : 10, Assassin’s Creed IV : 90 : 800, Payday 2 : 190 : 2001 ,Wolfenstein TNO : 25 :80, FarCry 4 : 55 : 862";
        String delimiters = "\\s+|,\\s*|\\:\\s*";

        // analyzing the string
        String[] tokensVal = str.split(delimiters);

        // prints the number of tokens
        System.out.println("Count of tokens = " + tokensVal.length);

        String finalStr="";

        for (String token : tokensVal) {

            finalStr = finalStr+"\n"+token;
        }

        System.out.println(finalStr);
    }

}


问:
Custom Dialog Layout Issue
I have implemented a Custom Dialog with Relative layout as Parent.. The issue is that the layout height goes match_parent size even i use wrap_content on Relative Layout...................................................................................................................................

```<code><RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:id="@+id/layoutPopup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="2dp"
        android:text="Standered Delvery"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="18dp"
        />

    <TextView
        android:id="@+id/item_count_popup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="6 Items"
        android:textAlignment="center" />
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="@color/bg_ash"
        >
    </View>
    <ListView
        android:id="@+id/listview_popup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="12dp">

    </ListView>
</LinearLayout>
<TextView
    android:id="@+id/popup_dismiss_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="10dp"
    android:layout_marginRight="10dp"
    android:text="DISMISS"
    android:textColor="@color/orange"
    />
</code>```

This is the java code

```<code>totalCountTxt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            customDialog = new Dialog(mContext);
            customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            customDialog.setContentView(R.layout.popup_item_details_delvery_options);
            customDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            ListView listView=(ListView)customDialog.findViewById(R.id.listview_popup) ;

            TextView count=(TextView)customDialog.findViewById(R.id.item_count_popup);
            count.setText(String.valueOf(arrayListCartModel.get(0).getItemCount())+" Items");

            PopupDelveryOptionsAdapter adapter=new PopupDelveryOptionsAdapter(mContext,arrayListCartModel);
            listView.setAdapter(adapter);
            customDialog.show();
        }
    });
</code>```

Screenshot for a reference

Does Anyone have the answer

答:
Try using AlertBuilder</p>

```<code>final AlertDialog.Builder alertDialog = new AlertDialog.Builder(new ContextThemeWrapper(context, style_to_be_use));

        view = inflater.inflate(your_layoutID,null);
        alertDialog.setView(view);
        alertDialog.setTitle("your title");

alertDialog.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                  //function body
           });
 alertDialog.create();
 alertDialog.show();
</code>```

Title: Custom Dialog Layout Issue

Body:
I have implemented a Custom Dialog with Relative layout as Parent.. The issue is that the layout height goes match_parent size even i use wrap_content on Relative Layout...................................................................................................................................

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:id="@+id/layoutPopup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="2dp"
        android:text="Standered Delvery"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="18dp"
        />

    <TextView
        android:id="@+id/item_count_popup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="6 Items"
        android:textAlignment="center" />
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="@color/bg_ash"
        >
    </View>
    <ListView
        android:id="@+id/listview_popup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="12dp">

    </ListView>
</LinearLayout>
<TextView
    android:id="@+id/popup_dismiss_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="10dp"
    android:layout_marginRight="10dp"
    android:text="DISMISS"
    android:textColor="@color/orange"
    />

This is the java code

totalCountTxt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            customDialog = new Dialog(mContext);
            customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            customDialog.setContentView(R.layout.popup_item_details_delvery_options);
            customDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            ListView listView=(ListView)customDialog.findViewById(R.id.listview_popup) ;

            TextView count=(TextView)customDialog.findViewById(R.id.item_count_popup);
            count.setText(String.valueOf(arrayListCartModel.get(0).getItemCount())+" Items");

            PopupDelveryOptionsAdapter adapter=new PopupDelveryOptionsAdapter(mContext,arrayListCartModel);
            listView.setAdapter(adapter);
            customDialog.show();
        }
    });

Screenshot for a reference

Does Anyone have the answer

Body:
Try using AlertBuilder

final AlertDialog.Builder alertDialog = new AlertDialog.Builder(new ContextThemeWrapper(context, style_to_be_use));

        view = inflater.inflate(your_layoutID,null);
        alertDialog.setView(view);
        alertDialog.setTitle("your title");

alertDialog.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                  //function body
           });
 alertDialog.create();
 alertDialog.show();


问:
C++ modulus small program issue
I'm trying to write a very simple program in C++ that finds the modulus of two numbers as follows:

```<code>#include <iostream>
using namespace std;
int n;
int d;
int modulus;
int main()
{
cout<<"***Welcome to the MODULUS calculator***";
cout<<"Enter the numerator, then press ENTER: ";
cin>>n;
cout<<"Enter the denominator, then press ENTER: ";
cin>>d;
modulus=n%d;
cout<<"The modulus is ---> "<<modulus;
return 0;
}
</code>```

But, when I try to compile it, I get the following:

How can this be solved?

Thanks.

答:
Because you have using namespace std; it clashes with std::modulus

Corrected version:

```<code>#include <iostream>
using std::cout;
using std::cin;

int main()
{
    cout<<"***Welcome to the MODULUS calculator***";

    cout<<"Enter the numerator, then press ENTER: ";
    int n;
    cin>>n;

    cout<<"Enter the denominator, then press ENTER: ";
    int d;
    cin>>d;

    int modulus=n%d;

    cout<<"The modulus is ---> "<<modulus;
    return 0;
}
</code>```

Title: C++ modulus small program issue

Body:
I'm trying to write a very simple program in C++ that finds the modulus of two numbers as follows:

#include <iostream>
using namespace std;
int n;
int d;
int modulus;
int main()
{
cout<<"***Welcome to the MODULUS calculator***";
cout<<"Enter the numerator, then press ENTER: ";
cin>>n;
cout<<"Enter the denominator, then press ENTER: ";
cin>>d;
modulus=n%d;
cout<<"The modulus is ---> "<<modulus;
return 0;
}

But, when I try to compile it, I get the following:

How can this be solved?

Thanks.

Body:
Because you have using namespace std; it clashes with std::modulus

Corrected version:

#include <iostream>
using std::cout;
using std::cin;

int main()
{
    cout<<"***Welcome to the MODULUS calculator***";

    cout<<"Enter the numerator, then press ENTER: ";
    int n;
    cin>>n;

    cout<<"Enter the denominator, then press ENTER: ";
    int d;
    cin>>d;

    int modulus=n%d;

    cout<<"The modulus is ---> "<<modulus;
    return 0;
}


问:
what happened when using the same variable in two layer loops in python?
I test the following code:

```<code>for i in range(3):
    for i in range(3,5):
        print "inner i: %d"%(i)
    print "outer i: %d"%(i)
</code>```

and the output is:

```<code>inner i: 3
inner i: 4
outer i: 4
inner i: 3
inner i: 4
outer i: 4
inner i: 3
inner i: 4
outer i: 4
</code>```

I don't understand why in the outer loop the i is 4 but the outer loop still runs for 3 times. It seems that the  the variable i in the print "outer i: %d"%(i) line is the i in the inner loop , but when goes to the for i in range(3) it uses the i in the outer loop.

Anyone can explain this? It's a little confusing to me now.

答:
It's the same i, Python doesn't have block scope. At the beginning of each for-loop iteration, you assign the the next value in the iterator to i. Python for-loops aren't like C/Java for-loops, they are foreach loops. The continue until the iterator is exhausted (or you break out somehow). A for-loop is equivalent to the following while-loop:

```<code>iterator = iter(my_iterable)
while True:
    try:
        x = next(iterator)
    except StopIteration:
        break
    do_stuff(x)
</code>```

So, your nested loop is the equivalent of this:

```<code>it1 = iter(range(3))
while True:
    try:
        i = next(it1)
    except StopIteration:
        break

    it2 = iter(range(3, 5))
    while True:
        try:
            i = next(it2)
        except StopIteration:
            break
        print "inner i: %d"%(i)

    print "outer i after: %d"%(i)
</code>```

Note, a C/Java for-loop, e.g.:

```<code>for (int i = 0; i < stop; i++){
    do_stuff(i);
}
</code>```

Would be in Python:

```<code>i = 0
while i < stop:
   do_stuff(i)
   i += 1
</code>```

In other words, the classic-for-loop depends on i, that is, the termination condition depends on the value of i. But in a for-each loop, the termination condition depends on the iterator. And it doesn't matter what you do to the variable inside the body, at the beginning of each iteration, it is assigned the next value of the iterator.

Body:
I test the following code:

for i in range(3):
    for i in range(3,5):
        print "inner i: %d"%(i)
    print "outer i: %d"%(i)

and the output is:

inner i: 3
inner i: 4
outer i: 4
inner i: 3
inner i: 4
outer i: 4
inner i: 3
inner i: 4
outer i: 4

I don't understand why in the outer loop the i is 4 but the outer loop still runs for 3 times. It seems that the  the variable i in the print "outer i: %d"%(i) line is the i in the inner loop , but when goes to the for i in range(3) it uses the i in the outer loop.

Anyone can explain this? It's a little confusing to me now.

Body:
It's the same i, Python doesn't have block scope. At the beginning of each for-loop iteration, you assign the the next value in the iterator to i. Python for-loops aren't like C/Java for-loops, they are foreach loops. The continue until the iterator is exhausted (or you break out somehow). A for-loop is equivalent to the following while-loop:

iterator = iter(my_iterable)
while True:
    try:
        x = next(iterator)
    except StopIteration:
        break
    do_stuff(x)

So, your nested loop is the equivalent of this:

it1 = iter(range(3))
while True:
    try:
        i = next(it1)
    except StopIteration:
        break

    it2 = iter(range(3, 5))
    while True:
        try:
            i = next(it2)
        except StopIteration:
            break
        print "inner i: %d"%(i)

    print "outer i after: %d"%(i)

Note, a C/Java for-loop, e.g.:

for (int i = 0; i < stop; i++){
    do_stuff(i);
}

Would be in Python:

i = 0
while i < stop:
   do_stuff(i)
   i += 1

In other words, the classic-for-loop depends on i, that is, the termination condition depends on the value of i. But in a for-each loop, the termination condition depends on the iterator. And it doesn't matter what you do to the variable inside the body, at the beginning of each iteration, it is assigned the next value of the iterator.


答: As say Willem Van Onsem i was searching a Bresenham line algorithm.

Title: 2D positions: Find which positions are on a vector and calculate

Body:
I have a two dimensional grid, with a float value for each of positions:

p = [
  [0  ,0  ,0  ,0  ,0  ,0  ],
  [0  ,0  ,0  ,0  ,1.0,0  ],
  [0  ,0.5,0  ,0  ,0  ,0  ],
  [0  ,0  ,0  ,0  ,0  ,0  ],
  [0  ,0  ,0  ,0  ,0  ,0  ],
  [0  ,0  ,0  ,0  ,0  ,0  ],
]

I would like to know what are poitions under a vector. For example, what are positions under vector (p[5][0], p[0][2]) (A->C) and vector (p[5][0], p[0][5]) (A->B):

Result should be colored cases:

So, for:

(p[5][0], p[0][2]) (A->C) => (p[5][0], p[4][0], p[4][3], p[3][3], p[2][3], p[1][3], p[1][3], p[0][3]) and final values (0, 0, 0, 0, 0, 0.5, 0, 0)

(p[5][0], p[0][5]) (A->B) => (p[5][0], p[4][1], p[3][2], p[2][3], p[1][4], p[0][5]) and final values (0, 0, 0, 0, 1.0, 0)

How to compute that ?


问:
Update Mediawiki user password using database
How to modify MediaWiki(v 1.15) user password without using the maintenance script, direct to database.</p>

答:
I did it... manually inserting in database</p>

```<code>"UPDATE wikiuser SET user_password=md5(CONCAT('67','-',MD5('pass'))) WHERE user_id = 15"
</code>```

Body:
I did it... manually inserting in database

"UPDATE wikiuser SET user_password=md5(CONCAT('67','-',MD5('pass'))) WHERE user_id = 15"


问:
event dispatcher assertion fails to find assertDispatched event
I get the error

Error: Call to undefined method Illuminate\Events\Dispatcher::assertDispatched()

for the test

```<code><?php

namespace Tests\Unit;

use Tests\TestCase;
use App\Entities\Requester;
use App\Observers\RequesterObserver;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;

class RequesterObserverTest extends TestCase {

  use RefreshDatabase;

  public function setUp()
  {
    parent::setUp();
    Mail::fake();
  }

  public function testRequesterCreationTriggersObserver(){

    $expected = factory(Requester::class)->create();

    //assert the creation event observer is fired
    Event::assertDispatched(RequesterObserver::class, function($event) use ($expected){
      return $event->requester->email_id === $expected->email_id;
    });

  }
}
</code>```

the method has been used as referred in the Laravel 5.5 documentation, when I run on a debug mode, I do see the actual event being fired, however the test gives an error on this line

```<code>Event::assertDispatched(RequesterObserver::class, function($event) use ($expected)
</code>```

答: You are missing the Event::fake() call in your testRequesterCreationTriggersObserver() function.

Body:
I get the error

Error: Call to undefined method Illuminate\Events\Dispatcher::assertDispatched()

for the test

<?php

namespace Tests\Unit;

use Tests\TestCase;
use App\Entities\Requester;
use App\Observers\RequesterObserver;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;

class RequesterObserverTest extends TestCase {

  use RefreshDatabase;

  public function setUp()
  {
    parent::setUp();
    Mail::fake();
  }

  public function testRequesterCreationTriggersObserver(){

    $expected = factory(Requester::class)->create();

    //assert the creation event observer is fired
    Event::assertDispatched(RequesterObserver::class, function($event) use ($expected){
      return $event->requester->email_id === $expected->email_id;
    });

  }
}

the method has been used as referred in the Laravel 5.5 documentation, when I run on a debug mode, I do see the actual event being fired, however the test gives an error on this line

Event::assertDispatched(RequesterObserver::class, function($event) use ($expected)


答:
Replace  your TextView with this

```<code><TextView
android:id="@+id/popup_dismiss_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
 android:layout_below="@+id/layout_popup"
android:layout_alignParentRight="true"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:text="DISMISS"
android:textColor="@color/orange"
/>
</code>```

Title: Custom Dialog Layout Issue

Body:
Replace  your TextView with this

<TextView
android:id="@+id/popup_dismiss_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
 android:layout_below="@+id/layout_popup"
android:layout_alignParentRight="true"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:text="DISMISS"
android:textColor="@color/orange"
/>


问:
client (fetch) and server (nodejs http) don't understand each other?
I try to wrap my mind around nodejs at the moment.

So I've created a client:

```<code>let myHeaders = {
 'Content-Type': 'application/json',
 'Accept': 'application/json'
};

let myBody = {
  aString: "Test"
};

fetch("http://localhost:8099/", {
  method: 'post',
  mode: 'no-cors',
  headers: myHeaders,
  body: JSON.stringify(myBody)
})
.then(result => {
  return result.text();
})
.then(text => {
  // do stuff with text from server
});
</code>```

And I have created a server:

```<code>// request needed modules
const http = require('http');

// init server
let server = http.createServer(logic);
server.listen(8099);

// server logic
function logic (req, res) {
  var body = req.body;
  res.end("Hello");
}
</code>```

Two problems:

1) The sever does not get the body (req.body is undefined).

UPDATE

See my answer below.

--

2) The client does not receive "Hello" (result.text() returns "").

UPDATE
2 is solved by:

Changing this on the client

```<code>fetch("http://localhost:8099/", {
  method: 'post',
  mode: 'no-cors', <-- CHANGE to: mode: 'cors'
...
</code>```

Adding this on server

```<code>res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
</code>```

--

I don't get what I do wrong here...

答:
To not completely mess up my question, I post my solution for problem number one as separate answer:

SOLUTION 1) The sever does not get the body (req.body is undefined)

As request is a stream, I need to treat it like one (notice "req.on('data'...)

This is how the server works as expected:

```<code>// request needed modules
const http = require('http');

// init server
let server = http.createServer(handler);
server.listen(8099);

// server logic
function handler (req, res) {

  // Set CORS headers
  let headers = {
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Methods' : 'POST, OPTIONS',
    'Access-Control-Allow-Headers' : 'Content-Type, Accept'
  };
  res.writeHead(200, headers);

  if(req.method == 'POST'){

    var body = '';

    req.on('data', data => {
      body += JSON.parse(data).aString;
    });

    req.on('end', () => {

      res.end(body.toString().toUpperCase());
    });

  } else if (req.method == 'OPTIONS'){

    res.end();
  }

}
</code>```

Body:
I try to wrap my mind around nodejs at the moment.

So I've created a client:

let myHeaders = {
 'Content-Type': 'application/json',
 'Accept': 'application/json'
};

let myBody = {
  aString: "Test"
};

fetch("http://localhost:8099/", {
  method: 'post',
  mode: 'no-cors',
  headers: myHeaders,
  body: JSON.stringify(myBody)
})
.then(result => {
  return result.text();
})
.then(text => {
  // do stuff with text from server
});

And I have created a server:

// request needed modules
const http = require('http');

// init server
let server = http.createServer(logic);
server.listen(8099);

// server logic
function logic (req, res) {
  var body = req.body;
  res.end("Hello");
}

Two problems:

1) The sever does not get the body (req.body is undefined).

UPDATE

See my answer below.

--

2) The client does not receive "Hello" (result.text() returns "").

UPDATE
2 is solved by:

Changing this on the client

fetch("http://localhost:8099/", {
  method: 'post',
  mode: 'no-cors', <-- CHANGE to: mode: 'cors'
...

Adding this on server

res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

--

I don't get what I do wrong here...

Body:
To not completely mess up my question, I post my solution for problem number one as separate answer:

SOLUTION 1) The sever does not get the body (req.body is undefined)

As request is a stream, I need to treat it like one (notice "req.on('data'...)

This is how the server works as expected:

// request needed modules
const http = require('http');

// init server
let server = http.createServer(handler);
server.listen(8099);

// server logic
function handler (req, res) {

  // Set CORS headers
  let headers = {
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Methods' : 'POST, OPTIONS',
    'Access-Control-Allow-Headers' : 'Content-Type, Accept'
  };
  res.writeHead(200, headers);

  if(req.method == 'POST'){

    var body = '';

    req.on('data', data => {
      body += JSON.parse(data).aString;
    });

    req.on('end', () => {

      res.end(body.toString().toUpperCase());
    });

  } else if (req.method == 'OPTIONS'){

    res.end();
  }

}


问:
combine three tables with keyword with in laravel
I want to join three tables. Here is the DB model in server:

```<code>lecturers
    id - integer (PK)
    ......

examination
    id - integer (PK)
   .....

exam_supervision
    lecturer_id - integer (FK)
    exam_id- integer (FK)
</code>```

Model relation as I implemented in laravel.

```</p>

```<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Examsupervision extends Model {

    public $timestamps = false;

    protected $table = 'exam_supervision';

    protected $fillable = ['lecturer_id', 'exam_id'];
}

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Examination extends Model {

    public $timestamps = false;

    protected $table = 'examination';

    protected $fillable = ['name', 'module_id', 'startdate', 'enddate', 'duration', 'type', 'code', 'status'];

}

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Lecturers extends Model {

    public $timestamps = false;

    protected $table = 'lecturers';

    protected $fillable = ['user_id', 'address', 'phone'];

}
```

<p>```

lecturers, examinations and exam_supervision which is M:M. What I want is find all the examinations of a lecturer.

My code

```<code> public function lecturerViewExaminations($id)
  {

what code to get all exam for a lecturer..say ID 129

  }
</code>```

Returning me empty set. WHat am I doing wrong? It is easy in SQL syntax but in laravel I am finding it very confusing

答:
What i understand from your question is:

You have one model (Examsupervision) and want the relations examinations and lectures

You can use Eloquent: Relationships

First create a model. In this case your model name would be something like Examsupervision.
In your model(Examsupervision) you can define your relations. In this case examinations and lextures

Create for every relation a new model. So you will have 3 models (Examsupervision, Examinations, Lectures).

Now in your model Examsupervision create a new relation function.

```<code>public function lectures()
{
    return $this->hasMany('App\Lectures');
}
public function examinations(){
   return $this->hasMany('App\Examinations');
}
</code>```

In your database table "lectures" and "examinations" create a new key with the name examsupervision_id. This key will be the id of the Examsupervision row.

Now in your code when you want the get all the lectures of a given Examsupervision you can do this.

```<code>$examsupervision = Examsupervision::find($id); //$id = the Examsupervision you want to retrieve
$lectures = $examsupervision->lectures; //This will return all the lectures connected to examsupervision
</code>```

And for examinations you can do the same with:

```<code>$examsupervision = Examsupervision::find($id); //$id = the Examsupervision you want to retrieve
$examinations = $examsupervision->examinations;
</code>```

Hope this helps

Body:
I want to join three tables. Here is the DB model in server:

lecturers
    id - integer (PK)
    ......

examination
    id - integer (PK)
   .....

exam_supervision
    lecturer_id - integer (FK)
    exam_id- integer (FK)

Model relation as I implemented in laravel.

```</p>

<pre><code><?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Examsupervision extends Model {

    public $timestamps = false;

    protected $table = 'exam_supervision';

    protected $fillable = ['lecturer_id', 'exam_id'];
}

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Examination extends Model {

    public $timestamps = false;

    protected $table = 'examination';

    protected $fillable = ['name', 'module_id', 'startdate', 'enddate', 'duration', 'type', 'code', 'status'];

}

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Lecturers extends Model {

    public $timestamps = false;

    protected $table = 'lecturers';

    protected $fillable = ['user_id', 'address', 'phone'];

}
</code></pre>

<p>```

lecturers, examinations and exam_supervision which is M:M. What I want is find all the examinations of a lecturer.

My code

 public function lecturerViewExaminations($id)
  {

what code to get all exam for a lecturer..say ID 129

  }

Returning me empty set. WHat am I doing wrong? It is easy in SQL syntax but in laravel I am finding it very confusing

Body:
What i understand from your question is:

You have one model (Examsupervision) and want the relations examinations and lectures

You can use Eloquent: Relationships

First create a model. In this case your model name would be something like Examsupervision.
In your model(Examsupervision) you can define your relations. In this case examinations and lextures

Create for every relation a new model. So you will have 3 models (Examsupervision, Examinations, Lectures).

Now in your model Examsupervision create a new relation function.

public function lectures()
{
    return $this->hasMany('App\Lectures');
}
public function examinations(){
   return $this->hasMany('App\Examinations');
}

In your database table "lectures" and "examinations" create a new key with the name examsupervision_id. This key will be the id of the Examsupervision row.

Now in your code when you want the get all the lectures of a given Examsupervision you can do this.

$examsupervision = Examsupervision::find($id); //$id = the Examsupervision you want to retrieve
$lectures = $examsupervision->lectures; //This will return all the lectures connected to examsupervision

And for examinations you can do the same with:

$examsupervision = Examsupervision::find($id); //$id = the Examsupervision you want to retrieve
$examinations = $examsupervision->examinations;

Hope this helps


问:
Perl command not giving expected output
Command:

```<code>perl -lpe '1 while (s/(^|\s)(0\d*)(\s|$)/$1"$2"$3/)' test5
</code>```

Input:

1234      012345               0

0.000             01234     0

01/02/03          5467        0abc

01234           0123

0000           000054

0asdf           0we23-1

Current Output:

```<code>perl -lpe '1 while (s/(^|\s)(0\d*)(\s|$)/$1"$2"$3/)' test5
</code>```

1234      "012345"            "0"

0.000             "01234"     "0"

01/02/03          5467       "0abc"

"01234"           "0123"

"0000"           "000054"

0asdf           0we23-1

Excepted Output:

1234      "012345"              0

0.000             "01234"       0

01/02/03          5467        "0abc"

"01234"           "0123"

"0000"           "000054"

"0asdf"           "0we23-1"

Conditions to follow in output:

All strings starting with 0 having alphanumeric character except / and . should be double quoted.

if string starting with 0 have only 0 character should not be quoted.

Spacing between strings should be preserved.

答:
This appears to do what you want:

```<code>#!/usr/bin/env perl

use strict;
use warnings;

while ( <DATA> ) {
   my @fields = split;
   s/^(0[^\.\/]+)$/"$1"/ for @fields;
   print join " ", @fields, "\n";
}

__DATA__
1234 012345 0
0.000 01234 0
01/02/03 5467 0abc
01234 0123
0000 000054
0asdf 0we23-1
</code>```

Note - it doesn't strictly preserve whitespace like you asked though - it just removes it and reinserts a single space. That seems to meet your spec, but you could instead:

```<code>my @fields = split /(\s+)/;
</code>```

as this would capture the spaces too.

```<code>join "", @fields;
</code>```

This is reducible to a one liner using -a for autosplitting:

```<code>perl -lane 's/^(0[^\.\/]+)$/"$1"/ for @F; print join " ", @F'
</code>```

If you wanted to do the second bit (preserving whitespace strictly) then you'd need to drop the -a and use split yourself.

Title: Perl command not giving expected output

Body:
Command:

perl -lpe '1 while (s/(^|\s)(0\d*)(\s|$)/$1"$2"$3/)' test5

Input:

1234      012345               0

0.000             01234     0

01/02/03          5467        0abc

01234           0123

0000           000054

0asdf           0we23-1

Current Output:

perl -lpe '1 while (s/(^|\s)(0\d*)(\s|$)/$1"$2"$3/)' test5

1234      "012345"            "0"

0.000             "01234"     "0"

01/02/03          5467       "0abc"

"01234"           "0123"

"0000"           "000054"

0asdf           0we23-1

Excepted Output:

1234      "012345"              0

0.000             "01234"       0

01/02/03          5467        "0abc"

"01234"           "0123"

"0000"           "000054"

"0asdf"           "0we23-1"

Conditions to follow in output:

All strings starting with 0 having alphanumeric character except / and . should be double quoted.

if string starting with 0 have only 0 character should not be quoted.

Spacing between strings should be preserved.

Body:
This appears to do what you want:

#!/usr/bin/env perl

use strict;
use warnings;

while ( <DATA> ) {
   my @fields = split;
   s/^(0[^\.\/]+)$/"$1"/ for @fields;
   print join " ", @fields, "\n";
}

__DATA__
1234 012345 0
0.000 01234 0
01/02/03 5467 0abc
01234 0123
0000 000054
0asdf 0we23-1

Note - it doesn't strictly preserve whitespace like you asked though - it just removes it and reinserts a single space. That seems to meet your spec, but you could instead:

my @fields = split /(\s+)/;

as this would capture the spaces too.

join "", @fields;

This is reducible to a one liner using -a for autosplitting:

perl -lane 's/^(0[^\.\/]+)$/"$1"/ for @F; print join " ", @F'

If you wanted to do the second bit (preserving whitespace strictly) then you'd need to drop the -a and use split yourself.


问:
How do you become an expert in a programming language?
Assuming you have basic to intermediate knowledge of a particular language, how can you become an expert in that language in a short amount of time?</p>

答:
The obvious reply would be: Practice makes perfect.
Try to work with the language on daily basis and push yourself out of your comfort zone in using it. Joining a user group is also a good option.
But at the end of the day, I must agree with Rozuur and concede that becoming an expert in something usually requires experience and experience requires time.</p>


问:
Type stability for a function involving case distinctions
I am writing a function which computes the weights for the barycentric interpolation formula. Ignoring type stability, that's easy enough:

```<code>function baryweights(x)
    n = length(x)
    if n == 1; return [1.0]; end # This is obviously not type stable

    xmin,xmax = extrema(x)
    x *= 4/(xmax-xmin)
    # ^ Multiply by capacity of interval to avoid overflow
    return [
        1/prod(x[i]-x[j] for j in 1:n if j != i)
        for i = 1:n
    ]
end
</code>```

The problem for type stability is to work out the return type of the n > 1 case so I can return an array of the correct type in the n == 1 case. Is there an easy trick to achieve this?

答:
I am not sure if I understand your plans. But maybe something like this could help? ->

```<code>baryone(t::T) where T<:Real = [1.]
baryone(t::T) where T<:Complex = [1im]  # or whatever you like here

function baryweights(x::Array{T,1}) where T<:Number
    n = length(x)
    n == 1 && return baryone(x[1])
    xmin,xmax = extrema(x)  # don't forget fix extrema for complex! :)
    x *= 4/(xmax-xmin)
    # ^ Multiply by capacity of interval to avoid overflow
    return [
        1/prod(x[i]-x[j] for j in 1:n if j != i)
        for i = 1:n
    ]
end
</code>```

Warning: I am still newbie! If I try @code_warntype baryweights([1]) I just see plenty of warnings. (Also if I avoid calling baryone). For example n is Any !!

Edit:
I asked on discourse and now see that @code_warn return much better result if we use another variable (y):

```<code>function baryweights(x::Array{T,1}) where T<:Number
    n = length(x)
    n == 1 && return baryone(x[1])
    xmin,xmax = extrema(x)  # don't forget fix extrema for complex! :)
    let y = x * 4/(xmax-xmin)
        # ^ Multiply by capacity of interval to avoid overflow
        return [
            1/prod(y[i]-y[j] for j in 1:n if j != i)
            for i = 1:n
        ]
    end
end
</code>```

Edit2: I added let to avoid y to be Core.Boxed

Body:
I am writing a function which computes the weights for the barycentric interpolation formula. Ignoring type stability, that's easy enough:

function baryweights(x)
    n = length(x)
    if n == 1; return [1.0]; end # This is obviously not type stable

    xmin,xmax = extrema(x)
    x *= 4/(xmax-xmin)
    # ^ Multiply by capacity of interval to avoid overflow
    return [
        1/prod(x[i]-x[j] for j in 1:n if j != i)
        for i = 1:n
    ]
end

The problem for type stability is to work out the return type of the n > 1 case so I can return an array of the correct type in the n == 1 case. Is there an easy trick to achieve this?

Body:
I am not sure if I understand your plans. But maybe something like this could help? ->

baryone(t::T) where T<:Real = [1.]
baryone(t::T) where T<:Complex = [1im]  # or whatever you like here

function baryweights(x::Array{T,1}) where T<:Number
    n = length(x)
    n == 1 && return baryone(x[1])
    xmin,xmax = extrema(x)  # don't forget fix extrema for complex! :)
    x *= 4/(xmax-xmin)
    # ^ Multiply by capacity of interval to avoid overflow
    return [
        1/prod(x[i]-x[j] for j in 1:n if j != i)
        for i = 1:n
    ]
end

Warning: I am still newbie! If I try @code_warntype baryweights([1]) I just see plenty of warnings. (Also if I avoid calling baryone). For example n is Any !!

Edit:
I asked on discourse and now see that @code_warn return much better result if we use another variable (y):

function baryweights(x::Array{T,1}) where T<:Number
    n = length(x)
    n == 1 && return baryone(x[1])
    xmin,xmax = extrema(x)  # don't forget fix extrema for complex! :)
    let y = x * 4/(xmax-xmin)
        # ^ Multiply by capacity of interval to avoid overflow
        return [
            1/prod(y[i]-y[j] for j in 1:n if j != i)
            for i = 1:n
        ]
    end
end

Edit2: I added let to avoid y to be Core.Boxed


问:
How can I find node within XAML with SelectNodes?
I'd like to find Button node within XAML in following PowerShell script. But I can't find it.

```<code>[xml]$xaml1 = @'
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="400" Width="640">
    <Button Content="Button" HorizontalAlignment="Left" Margin="99,20,0,0" VerticalAlignment="Top" Width="60" Height="30"/>
</Window>
'@
$xaml1.SelectNodes("//Button")  | ForEach {
    $_.Name
}
# No OUTOUT from above code!
</code>```

When I delete line 3 and 4, it works.

```<code>[xml]$xaml2 = @'
<Window
        Title="MainWindow" Height="400" Width="640">
        <Button Content="Button" HorizontalAlignment="Left" Margin="99,20,0,0" VerticalAlignment="Top" Width="60" Height="30"/>
</Window>
'@
$xaml2.SelectNodes("//Button")  | ForEach {
    $_.Name
}
# OUTPUT of above code:
Button
</code>```

How can I find node within XAML with SelectNodes?

答:
$xaml.SelectNodes("//*[@Name]") | ForEach-Object {Set-Variable -Name ($.Name) -Value $Form.FindName($.Name)}

Now you have the Controls as Variable...

if the Name of a Button is "button" you have a variable $button in Powershell.
add a click like this then...
$button.add_click({write-host "clicked!!"})

Body:
I'd like to find Button node within XAML in following PowerShell script. But I can't find it.

[xml]$xaml1 = @'
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="400" Width="640">
    <Button Content="Button" HorizontalAlignment="Left" Margin="99,20,0,0" VerticalAlignment="Top" Width="60" Height="30"/>
</Window>
'@
$xaml1.SelectNodes("//Button")  | ForEach {
    $_.Name
}
# No OUTOUT from above code!

When I delete line 3 and 4, it works.

[xml]$xaml2 = @'
<Window
        Title="MainWindow" Height="400" Width="640">
        <Button Content="Button" HorizontalAlignment="Left" Margin="99,20,0,0" VerticalAlignment="Top" Width="60" Height="30"/>
</Window>
'@
$xaml2.SelectNodes("//Button")  | ForEach {
    $_.Name
}
# OUTPUT of above code:
Button

How can I find node within XAML with SelectNodes?


答:
How about using split with regex? e.g.</p>

```<code>String aa = "fname lname, GTA V: 120 : 00000, Minecraft : 20 : 10, Assassin’s Creed IV : 90 : 800, Payday 2 : 190 : 2001 ,Wolfenstein TNO : 25 : 80, FarCry 4 : 55 : 862";
String [] a = aa.split("[,:]");
</code>```

Title: Splitting a string into an array then splitting the array again

Body:
I have this string:

   fname lname, GTA V: 120 : 00000, Minecraft : 20 : 10, Assassin’s Creed IV : 90 : 800, Payday 2 : 190 : 2001 ,Wolfenstein TNO : 25 : 80, FarCry 4 : 55 : 862

I want to use a loop to split this string into an array at the comma [,] example:

[0]fname lname
[1]GTA V: 120 : 00000
[2]Minecraft : 20 : 10
[3]Assassin’s Creed IV : 90 : 800
[4]Payday 2 : 190 : 2001
[5]Wolfenstein TNO : 25 : 80
[6]FarCry 4 : 55 : 862

Then I want to use another loop to split this further at : into another array example

[0]fname lname
[1]GTA V
[2]120
[3]00000
[4]Minecraft
[5]20
[6]10
....

Is there a better way of doing this?

currently I have:

    List<String> lines = new ArrayList<String>();
    while (scan.hasNextLine())
    {
      lines.add(scan.nextLine());
    }

    //converts the list array to string array

    String[] scanarray = lines.toArray(new String[0]);

    //converts the string array into one large string

    String str_array = Arrays.toString(scanarray);

    String[] arraysplit;

    arraysplit = str_array.split("\\s*:\\s*");

    for (int i=0; i<arraysplit.length; i++)
    {
        arraysplit[i] = arraysplit[i].trim();
        //              ^^^^^^^^^^^^ has values with spaces
        System.out.println(scanarray[i]);
    }

EDIT:

Currently my program creates 3 identical arrays, containing the example you can see in the second block of code above.

Body:
How about using split with regex? e.g.

String aa = "fname lname, GTA V: 120 : 00000, Minecraft : 20 : 10, Assassin’s Creed IV : 90 : 800, Payday 2 : 190 : 2001 ,Wolfenstein TNO : 25 : 80, FarCry 4 : 55 : 862";
String [] a = aa.split("[,:]");


问:
navigation bar color changes after new view is presented due to rootviewcontroller
i am going from menu viewControler to InboxViewConroller through segue.

As the inbox view present and from the background menuview discarded the navigation bar color on inbox view goes darker due to the root view controller.

I found the issue but what is the appropriate solution for this problem.

I tried by putting an empty view on the inbox view and it works but it is not the solution.

please help me out.

答:
You can try this:</p>

```<code>self.navigationController.navigationBar.translucent = NO;
</code>```

Body:
You can try this:

self.navigationController.navigationBar.translucent = NO;


问:
Why is [0] === [0] false
If debugging shows that a variable is 0, then I think that I should be able to catch it with either ==='0' or ===0 but that didn't work. I had to use only == instead, then it worked:

```<code>var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns == '0' || non_sortable_columns == 0) {
    offset = 1;
}
</code>```

I first tried this but it didn't work:

```<code>var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns === '0' || non_sortable_columns === 0) {
    offset = 1;
}
</code>```

The value was [0] and [0] === [0] is false. How can it be false?

答:
I just did the following test

```<code>var num = 0;

console.log("Number: ", num);

if(num === '0' || num === 0) {
    console.log("Num is 0 (===)");
}

if(num == '0' || num == 0) {
    console.log("Num is 0 (==)");
}
</code>```

and got the output

```<code>Number:  0
Num is 0 (===)
Num is 0 (==)
</code>```

Try console.log the value itself, if you alert or append strings to a number in JS it will always output as a string. This can be misleading when trying to debug code.

Title: Why is [0] === [0] false

Body:
If debugging shows that a variable is 0, then I think that I should be able to catch it with either ==='0' or ===0 but that didn't work. I had to use only == instead, then it worked:

var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns == '0' || non_sortable_columns == 0) {
    offset = 1;
}

I first tried this but it didn't work:

var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns === '0' || non_sortable_columns === 0) {
    offset = 1;
}

The value was [0] and [0] === [0] is false. How can it be false?

Body:
I just did the following test

var num = 0;

console.log("Number: ", num);

if(num === '0' || num === 0) {
    console.log("Num is 0 (===)");
}

if(num == '0' || num == 0) {
    console.log("Num is 0 (==)");
}

and got the output

Number:  0
Num is 0 (===)
Num is 0 (==)

Try console.log the value itself, if you alert or append strings to a number in JS it will always output as a string. This can be misleading when trying to debug code.