问:
How to 'Get' a Specific Point From A Shape Object Derived from AffineTransform
As a self-project, I'm trying to make the game 'Asteroids'.

Currently, I'm stuck on trying to figure out how to make it so the lasers fired from my ship appear from the tip of the ship. So far, I've tried experimenting with using the Shape object's .getBounds2D().getX() methods, but because getBounds2D() draws a rectangle around the polygon, the lasers end up appearing from the corner of the imaginary 'box' around my Polygon ship.

Here's a gif of what I have so far.

Is there a way to 'get' a specific point from a Shape object; where, in this case, that specific point is the tip of the ship.

Main Class:

```<code>public class AsteroidGame implements ActionListener, KeyListener{

    public static AsteroidGame game;
    public Renderer renderer;

    public boolean keyDown = false;
    public int playerAngle = 0;

    public boolean left = false;
    public boolean right = false;
    public boolean go = false;
    public boolean back = false;
    public boolean still = true;
    public double angle = 0;
    public int turnRight = 5;
    public int turnLeft = -5;

    public Shape transformed;

    public ArrayList<Laser> lasers;
    public ArrayList<Shape> transformedLasers;

    public final int WIDTH = 1400;
    public final int HEIGHT = 800;

    public Ship ship;
    public Rectangle shipHead;
    public Shape shipHeadTrans;
    public Point headPoint;

    public AffineTransform transform = new AffineTransform();
    public AffineTransform lasTransform = new AffineTransform();
    public AffineTransform headTransform = new AffineTransform();

    public AsteroidGame(){
        JFrame jframe = new JFrame();
        Timer timer = new Timer(20, this);
        renderer = new Renderer();

        jframe.add(renderer);
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jframe.setSize(WIDTH, HEIGHT);
        jframe.setVisible(true);
        jframe.addKeyListener(this);
        jframe.setResizable(false);

        int xPoints[] = {800, 780, 800, 820};
        int yPoints[] = {400, 460, 440, 460};

        //(800, 400) is the initial location of the 'tip' of the ship'.
        headPoint = new Point(800, 400);

        lasers = new ArrayList<Laser>();
        transformedLasers = new ArrayList<Shape>();

        ship = new Ship(xPoints, yPoints, 4, 0);
        transformed = transform.createTransformedShape(ship);

        shipHead = new Rectangle(headPoint);
        shipHeadTrans = transform.createTransformedShape(shipHead);
        //shipHeadTrans.getBounds2D().

        timer.start();

    }

    public void repaint(Graphics g){

        g.setColor(Color.BLACK);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        Graphics2D g2d = (Graphics2D)g;

        //drawing the ship
        g2d.setColor(Color.WHITE);
        g2d.draw(transformed);

        //drawing lasers
        g2d.setColor(Color.RED);
        for (int i = 0; i < transformedLasers.size(); i++){
            System.out.println(i);
            g2d.draw(transformedLasers.get(i));
        }

    }

    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub

        /*The for if and else if statements are just to send the ship
         * to the other side of the canvas if it ever leaves the screen
         */
        if (transformed.getBounds2D().getMinX() > WIDTH){
            double tempAng = ship.getAng();
            double diff = 90-tempAng;

            transform.rotate(Math.toRadians(diff), ship.getCenterX(), ship.getCenterY());
            transform.translate(0,WIDTH);
            transform.rotate(Math.toRadians(-diff), ship.getCenterX(), ship.getCenterY());

        }

        else if (transformed.getBounds2D().getX() < 0){
            double tempAng = ship.getAng();
            double diff = 90-tempAng;
            transform.rotate(Math.toRadians(diff), ship.getCenterX(), ship.getCenterY());
            transform.translate(0,-WIDTH);
            transform.rotate(Math.toRadians(-diff), ship.getCenterX(), ship.getCenterY());
        }

        else if (transformed.getBounds2D().getY() > HEIGHT){
            double tempAng = ship.getAng();
            double diff = 180-tempAng;
            transform.rotate(Math.toRadians(diff), ship.getCenterX(), ship.getCenterY());
            transform.translate(0,HEIGHT);
            transform.rotate(Math.toRadians(-diff), ship.getCenterX(), ship.getCenterY());
        }

        else if (transformed.getBounds2D().getY() < 0){
            double tempAng = ship.getAng();
            double diff = 180-tempAng;
            transform.rotate(Math.toRadians(diff), ship.getCenterX(), ship.getCenterY());
            transform.translate(0,-HEIGHT);
            transform.rotate(Math.toRadians(-diff), ship.getCenterX(), ship.getCenterY());
        }

        if (right){
            ship.right();
            //rotating the ship
            transform.rotate(Math.toRadians(turnRight), ship.getCenterX(), ship.getCenterY());
            //rotating the 'tip' of the ship.
            headTransform.rotate(Math.toRadians(turnRight), ship.getCenterX(), ship.getCenterY());
        }

        else if (left){
            ship.left();
            //rotating the ship
            transform.rotate(Math.toRadians(turnLeft), ship.getCenterX(), ship.getCenterY());
            //rotating the 'tip' of the ship
            headTransform.rotate(Math.toRadians(turnLeft), ship.getCenterX(), ship.getCenterY());
        }
        if (go){
            ship.go();
        }
        else if (back){
            ship.reverse();
        }

        //moving and shaping each individual laser that had been shot
        for (int i = 0; i < transformedLasers.size(); i++){
            lasers.get(i).move();

            lasTransform = new AffineTransform();
            lasTransform.rotate(Math.toRadians(lasers.get(i).getAng()), transformed.getBounds2D().getX(), transformed.getBounds2D().getY());
            transformedLasers.set(i, lasTransform.createTransformedShape(lasers.get(i)));

        }

        //moving the ship
        ship.move();

        //moving the 'tip'
        shipHead.y -= ship.getSpeed();

        transformed = transform.createTransformedShape(ship);
        shipHeadTrans = headTransform.createTransformedShape(shipHead);

        renderer.repaint();

    }

    //defining a new laser
    public void fireLaser(){
        Laser tempLaser = new Laser((int)transformed.getBounds2D().getX(), (int)transformed.getBounds2D().getY(), 5, 10, ship.getAng());
        lasers.add(tempLaser);

        lasTransform = new AffineTransform();
        lasTransform.rotate(Math.toRadians(ship.getAng()), transformed.getBounds2D().getX(), transformed.getBounds2D().getY());
        transformedLasers.add(lasTransform.createTransformedShape(tempLaser));

    }

    public static void main(String[] args){
        game = new AsteroidGame();
    }

    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub
        if (e.getKeyCode() == KeyEvent.VK_RIGHT){
            right = true;
            keyDown = true;
        }else if (e.getKeyCode() == KeyEvent.VK_LEFT){
            left = true;
            keyDown = true;
        }

        else if (e.getKeyCode() == KeyEvent.VK_UP){
            go = true;
        }
        else if (e.getKeyCode() == KeyEvent.VK_DOWN){
            back = true;
        }

        //fire laser
        if (e.getKeyCode() == KeyEvent.VK_SPACE){
            fireLaser();
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub
        if (e.getKeyCode() == KeyEvent.VK_RIGHT){
            right = false;
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT){
            left = false;
        }
        if (e.getKeyCode() == KeyEvent.VK_UP){
            go = false;
        }
        if (e.getKeyCode() == KeyEvent.VK_DOWN){
            back = false;
        }
        still = true;
        keyDown = false;
    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }
</code>```

Ship Class (I don't think it's relevant though)

```<code>package asteroidGame;

import java.awt.Polygon;
import java.util.Arrays;

public class Ship extends Polygon{

    /**
     *
     */
    private double currSpeed = 0;

    private static final long serialVersionUID = 1L;
    public double angle;
    public int[] midX;
    public int[] midY;

    public Ship(int[] x, int[] y, int points, double angle){
        super(x, y, points);
        midX = x;
        midY = y;

        this.angle= angle;
    }

    public void right(){
        angle += 5;
    }
    public void left(){
        angle -= 5;
    }

    public void move(){
        for (int i = 0; i < super.ypoints.length; i++){
            super.ypoints[i] -= currSpeed;
            //System.out.println(super.ypoints[i]);
            //System.out.println(super.xpoints[i]);
        }
        //System.out.println(Arrays.toString(super.ypoints));

    }
    public double getSpeed(){
        return currSpeed;
    }

    public void reverse(){
        if (currSpeed  > -15) currSpeed -= 0.2;
    }

    public void go(){
        if (currSpeed < 25) currSpeed += 0.5;

    }

    public int getCenterX(){
        return super.xpoints[2];
    }
    public int getCenterY(){
        return super.ypoints[2];
    }

    public double getAng(){
        return angle;
    }
    public void test(){
        for (int x = 0; x < super.ypoints.length; x++){
            super.ypoints[x] += 1000;
        }
    }

    /*
    public void decrement(){
        if(currSpeed == 0){}

        else if (currSpeed > 0 && currSpeed < 15){
            currSpeed -= 0.05;

        }
        else if (currSpeed < 0 && currSpeed > -15){
            currSpeed += 0.05;

        }
        System.out.println("losing speed");
    }
    */
}
</code>```

Laser Class (I don't think this is relevant either, but here ya go.)

```<code>package asteroidGame;

import java.awt.Color;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;

public class Laser extends Rectangle{

    private double angle;

    public Laser(int x, int y , int width, int height, double ang){
        super(x, y, width, height);
        angle = ang;
        Rectangle tst = new Rectangle();

    }

    public void move(){
        super.y -= 35;
    }

    public double getAng(){
        return angle;
    }

    public boolean intersects (Rectangle2D r){
        //if intersects
        if (super.intersects(r)){
            return true;
        }
        else{
            return false;
        }

    }

}
</code>```

I was thinking of maybe turning the the Shape object transformed back into a Polygon to get the point, but I'm not sure how or if that would work.

答:
You can use AffineTransform.transform(Point2D, Point2D) to transform a single point on your polygon.

Things would be a lot simpler for you if instead of trying to move the ship by using a rotation transform you kept a single (x,y) location of where the ship is. You'd move the ship's location in move() instead of trying to translate the polygon. Then when you want to paint the ship you e.g. do:

```<code>// Optionally copying the Graphics so the
// transform doesn't affect later painting.
Graphics2D temp = (Graphics2D) g2d.create();
temp.translate(ship.locX, ship.locY);
temp.rotate(ship.angle);
temp.draw(ship);
</code>```

To move a point based on speed you can do this to find the movement vector:

```<code>double velX = speed * Math.cos(angle);
double velY = speed * Math.sin(angle);
locX += timeElapsed * velX;
locY += timeElapsed * velY;
</code>```

That is essentially a conversion from polar to Cartesian coordinates. The x and y velocities are the legs of a triangle whose hypotenuse is speed and whose known angle is angle:

```<code>             /|
            / |
           /  |
          /   |
   speed /    |
        /     |
       /      |velY
      / angle |
     /)_______|
         velX
</code>```

There's an example of doing movement this way in an answer of mine here: https://stackoverflow.com/a/43692434/2891664.

For your comments:

Are you saying that, unlike my initial move function, just to make ship hold a single point, and thus I would only translate that instead?

More or less, yes. You'd still have a polygon to hold the ship's shape, but the points on the polygon would be relative to (0,0).

Suppose the following definitions:

Each (x,y) point on the polygon is pi. (In other words, one of p0, p1, p2 and p3.)

The (x,y) coordinates of the translation are T

Then, after translating the Graphics2D, each pi coordinate becomes pi+T on the panel. So if your polygon points are defined relative to (0,0) then translating to the ship's (locX,locY) will move the polygon to a location relative to (locX,locY).

It could be simplest then to define the point which is the tip of the polygon as being (0,0) so that after the translation the tip of the ship is the ship's location:

```<code>// Your original points:
int xPoints[] = {800, 780, 800, 820};
int yPoints[] = {400, 460, 440, 460};
// Become these points relative to (0,0):
int xPoints[] = {0, -20, 0, 20};
int yPoints[] = {0, 60, 40, 60};
</code>```

And to e.g. start the ship in the same place, you would initialize its location to (800,400).

I was thinking about this again and realized the rotation is a little more complicated, because you probably don't want to rotate the ship around the tip. You probably want to rotate the ship around its center.

So, here's an MCVE demonstrating how to do all of this.

```<code>package mcve.game;

import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.GraphicsConfiguration;
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;

public class MovementExample implements ActionListener {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(MovementExample::new);
    }

    final int fps    = 60;
    final int period = 1000 / fps;

    final JFrame    frame;
    final GamePanel panel;
    final Controls  controls;
    final Ship      ship;

    final List<Bullet> bullets = new ArrayList<>();

    MovementExample() {
        frame = new JFrame("Movement Example");

        Dimension size = getMaximumWindowSize(frame);
        size.width  /= 2;
        size.height /= 2;
        frame.setPreferredSize(size);

        panel = new GamePanel();
        frame.setContentPane(panel);

        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        controls = new Controls();

        ship = new Ship(panel.getWidth()  / 2,
                        panel.getHeight() / 2);

        new Timer(period, this).start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        double secondsElapsed = 1.0 / fps;
        ship.update(secondsElapsed);

        bullets.forEach(b -> b.update(secondsElapsed));
        Rectangle bounds = panel.getBounds();
        bullets.removeIf(b -> !bounds.contains(b.locX, b.locY));

        panel.repaint();
    }

    class GamePanel extends JPanel {
        GamePanel() {
            setBackground(Color.WHITE);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);

            if (ship != null) {
                ship.draw(g2);
            }
            bullets.forEach(b -> b.draw(g2));

            g2.dispose();
        }
    }

    abstract class AbstractGameObject {
        double maxSpeed;
        double rotationAngle;
        double locX;
        double locY;
        double velX;
        double velY;

        AbstractGameObject(double initialX, double initialY) {
            locX = initialX;
            locY = initialY;
        }

        abstract void update(double secondsElapsed);
        abstract void draw(Graphics2D g2);
    }

    class Ship extends AbstractGameObject {
        Polygon shape;
        double  rotationRate;

        Ship(double initialX, double initialY) {
            super(initialX, initialY);
            maxSpeed      = 128; // pixels/second
            rotationAngle = Math.PI * 3 / 2;
            rotationRate  = (2 * Math.PI) / 2; // radians/second

            int xPoints[] = {0, -20, 0, 20};
            int yPoints[] = {0, 60, 40, 60};
            shape = new Polygon(xPoints, yPoints, 4);
        }

        Point2D.Double getTip() {
            Point2D.Double center = getCenter();
            // The tip is at (0,0) and it's already centered
            // on the x-axis origin, so the distance from the
            // tip to the center is just center.y.
            double distance = center.y;
            // Then find the location of the tip, relative
            // to the center.
            double tipX = distance * Math.cos(rotationAngle);
            double tipY = distance * Math.sin(rotationAngle);
            // Now find the actual location of the center.
            center.x += locX;
            center.y += locY;
            // And return the actual location of the tip, relative
            // to the actual location of the center.
            return new Point2D.Double(tipX + center.x, tipY + center.y);
        }

        Point2D.Double getCenter() {
            // Returns the center point of the ship,
            // relative to (0,0).
            Point2D.Double center = new Point2D.Double();
            for (int i = 0; i < shape.npoints; ++i) {
                center.x += shape.xpoints[i];
                center.y += shape.ypoints[i];
            }
            center.x /= shape.npoints;
            center.y /= shape.npoints;
            return center;
        }

        @Override
        void update(double secondsElapsed) {
            // See my answer here: https://stackoverflow.com/a/43692434/2891664
            // for a discussion of why this logic is the way it is.
            double speed = 0;
            if (controls.isUpHeld()) {
                speed += maxSpeed;
            }
            if (controls.isDownHeld()) {
                speed -= maxSpeed;
            }
            velX  = speed * Math.cos(rotationAngle);
            velY  = speed * Math.sin(rotationAngle);
            locX += secondsElapsed * velX;
            locY += secondsElapsed * velY;

            double rotation = 0;
            if (controls.isLeftHeld()) {
                rotation -= rotationRate;
            }
            if (controls.isRightHeld()) {
                rotation += rotationRate;
            }
            rotationAngle += secondsElapsed * rotation;
            // Cap the angle so it can never e.g. get so
            // large that it loses precision.
            if (rotationAngle > 2 * Math.PI) {
                rotationAngle -= 2 * Math.PI;
            }

            if (controls.isFireHeld()) {
                Point2D.Double tipLoc = getTip();
                Bullet bullet = new Bullet(tipLoc.x, tipLoc.y, rotationAngle);
                bullets.add(bullet);
            }
        }

        @Override
        void draw(Graphics2D g2) {
            Graphics2D copy = (Graphics2D) g2.create();
            copy.setColor(Color.RED);

            // Translate to the ship's location.
            copy.translate(locX, locY);
            // Rotate the ship around its center.
            Point2D.Double center = getCenter();
            // The PI/2 offset is necessary because the
            // polygon points are defined with the ship
            // already vertical, i.e. at an angle of -PI/2.
            copy.rotate(rotationAngle + (Math.PI / 2), center.x, center.y);

            copy.fill(shape);
        }
    }

    class Bullet extends AbstractGameObject {
        Ellipse2D.Double shape = new Ellipse2D.Double();

        Bullet(double initialX, double initialY, double initialRotation) {
            super(initialX, initialY);
            maxSpeed      = 512;
            rotationAngle = initialRotation;
            velX          = maxSpeed * Math.cos(rotationAngle);
            velY          = maxSpeed * Math.sin(rotationAngle);

            double radius = 3;
            shape.setFrame(-radius, -radius, 2 * radius, 2 * radius);
        }

        @Override
        void update(double secondsElapsed) {
            locX += secondsElapsed * velX;
            locY += secondsElapsed * velY;
        }

        @Override
        void draw(Graphics2D g2) {
            Graphics2D copy = (Graphics2D) g2.create();
            copy.setColor(Color.BLACK);
            copy.translate(locX, locY);
            copy.fill(shape);
        }
    }

    // See https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
    class Controls {
        final Set<Integer> keysHeld = new HashSet<>();

        Controls() {
            bind(KeyEvent.VK_A, "left");
            bind(KeyEvent.VK_D, "right");
            bind(KeyEvent.VK_W, "up");
            bind(KeyEvent.VK_S, "down");
            bind(KeyEvent.VK_SPACE, "fire");
        }

        boolean isLeftHeld()  { return keysHeld.contains(KeyEvent.VK_A); }
        boolean isRightHeld() { return keysHeld.contains(KeyEvent.VK_D); }
        boolean isUpHeld()    { return keysHeld.contains(KeyEvent.VK_W); }
        boolean isDownHeld()  { return keysHeld.contains(KeyEvent.VK_S); }
        boolean isFireHeld()  { return keysHeld.contains(KeyEvent.VK_SPACE); }

        void bind(int keyCode, String name) {
            bind(keyCode, name, true);
            bind(keyCode, name, false);
        }

        void bind(int keyCode, String name, boolean isOnRelease) {
            KeyStroke stroke = KeyStroke.getKeyStroke(keyCode, 0, isOnRelease);
            name += isOnRelease ? ".released" : ".pressed";
            panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
                 .put(stroke, name);
            panel.getActionMap()
                 .put(name, new AbstractAction() {
                     @Override
                     public void actionPerformed(ActionEvent e) {
                         if (isOnRelease) {
                             keysHeld.remove(keyCode);
                         } else {
                             keysHeld.add(keyCode);
                         }
                     }
                 });
        }
    }

    // This returns the usable size of the display which
    // the JFrame resides in, as described here:
    // http://docs.oracle.com/javase/8/docs/api/java/awt/GraphicsEnvironment.html#getMaximumWindowBounds--
    static Dimension getMaximumWindowSize(JFrame frame) {
        GraphicsConfiguration config = frame.getGraphicsConfiguration();
        Dimension size   = config.getBounds().getSize();
        Insets    insets = Toolkit.getDefaultToolkit().getScreenInsets(config);
        size.width  -= insets.left + insets.right;
        size.height -= insets.top  + insets.bottom;
        return size;
    }
}
</code>```

There are other ways the tip of the ship could be calculated, but the way I did it in the MCVE is this:

Get the center point of the ship, relative to (0,0).

Get the distance from the center point to the tip. The tip is at (0,0) so this is just the y-coordinate of the center.

Then calculate the (x,y) location of the tip, relative to the center. This is done in a very similar way to the figure above for speed and velocity, but the hypotenuse is the distance between the center and the tip of the ship.

Translate the center to be relative to the ship's location.

Translate the location of the tip (which is relative to the center) to be relative to the ship's location.

It could also all be done with an AffineTransform, similar to what you are doing in the code in the question, but you'd set it on every update. Something like this:

```<code>AffineTransform transform = new AffineTransform();

@Override
void update(double secondsElapsed) {
    ...
    // Clear the previous translation and rotation.
    transform.setToIdentity();
    // Set to current.
    transform.translate(locX, locY);
    Point2D.Double center = getCenter();
    transform.rotate(rotationAngle + (Math.PI / 2), center.x, center.y);

    if (controls.isFireHeld()) {
        Point2D.Double tip = new Point2D.Double(0, 0);
        transform.transform(tip, tip);
        Bullet bullet = new Bullet(tip.x, tip.y, rotationAngle);
        bullets.add(bullet);
    }
}
</code>```

You could still use a transform to do calculations that way, but you don't end up with any strangeness from depending on the transform for movement. (In the code in the question, the ship is e.g. only ever moved along the y-axis. The apparent sideways movement is due to the series of rotation concatenations.)

Body:
As a self-project, I'm trying to make the game 'Asteroids'.

Currently, I'm stuck on trying to figure out how to make it so the lasers fired from my ship appear from the tip of the ship. So far, I've tried experimenting with using the Shape object's .getBounds2D().getX() methods, but because getBounds2D() draws a rectangle around the polygon, the lasers end up appearing from the corner of the imaginary 'box' around my Polygon ship.

Here's a gif of what I have so far.

Is there a way to 'get' a specific point from a Shape object; where, in this case, that specific point is the tip of the ship.

Main Class:

public class AsteroidGame implements ActionListener, KeyListener{

    public static AsteroidGame game;
    public Renderer renderer;

    public boolean keyDown = false;
    public int playerAngle = 0;

    public boolean left = false;
    public boolean right = false;
    public boolean go = false;
    public boolean back = false;
    public boolean still = true;
    public double angle = 0;
    public int turnRight = 5;
    public int turnLeft = -5;

    public Shape transformed;

    public ArrayList<Laser> lasers;
    public ArrayList<Shape> transformedLasers;

    public final int WIDTH = 1400;
    public final int HEIGHT = 800;

    public Ship ship;
    public Rectangle shipHead;
    public Shape shipHeadTrans;
    public Point headPoint;

    public AffineTransform transform = new AffineTransform();
    public AffineTransform lasTransform = new AffineTransform();
    public AffineTransform headTransform = new AffineTransform();

    public AsteroidGame(){
        JFrame jframe = new JFrame();
        Timer timer = new Timer(20, this);
        renderer = new Renderer();

        jframe.add(renderer);
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jframe.setSize(WIDTH, HEIGHT);
        jframe.setVisible(true);
        jframe.addKeyListener(this);
        jframe.setResizable(false);

        int xPoints[] = {800, 780, 800, 820};
        int yPoints[] = {400, 460, 440, 460};

        //(800, 400) is the initial location of the 'tip' of the ship'.
        headPoint = new Point(800, 400);

        lasers = new ArrayList<Laser>();
        transformedLasers = new ArrayList<Shape>();

        ship = new Ship(xPoints, yPoints, 4, 0);
        transformed = transform.createTransformedShape(ship);

        shipHead = new Rectangle(headPoint);
        shipHeadTrans = transform.createTransformedShape(shipHead);
        //shipHeadTrans.getBounds2D().

        timer.start();

    }

    public void repaint(Graphics g){

        g.setColor(Color.BLACK);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        Graphics2D g2d = (Graphics2D)g;

        //drawing the ship
        g2d.setColor(Color.WHITE);
        g2d.draw(transformed);

        //drawing lasers
        g2d.setColor(Color.RED);
        for (int i = 0; i < transformedLasers.size(); i++){
            System.out.println(i);
            g2d.draw(transformedLasers.get(i));
        }

    }

    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub

        /*The for if and else if statements are just to send the ship
         * to the other side of the canvas if it ever leaves the screen
         */
        if (transformed.getBounds2D().getMinX() > WIDTH){
            double tempAng = ship.getAng();
            double diff = 90-tempAng;

            transform.rotate(Math.toRadians(diff), ship.getCenterX(), ship.getCenterY());
            transform.translate(0,WIDTH);
            transform.rotate(Math.toRadians(-diff), ship.getCenterX(), ship.getCenterY());

        }

        else if (transformed.getBounds2D().getX() < 0){
            double tempAng = ship.getAng();
            double diff = 90-tempAng;
            transform.rotate(Math.toRadians(diff), ship.getCenterX(), ship.getCenterY());
            transform.translate(0,-WIDTH);
            transform.rotate(Math.toRadians(-diff), ship.getCenterX(), ship.getCenterY());
        }

        else if (transformed.getBounds2D().getY() > HEIGHT){
            double tempAng = ship.getAng();
            double diff = 180-tempAng;
            transform.rotate(Math.toRadians(diff), ship.getCenterX(), ship.getCenterY());
            transform.translate(0,HEIGHT);
            transform.rotate(Math.toRadians(-diff), ship.getCenterX(), ship.getCenterY());
        }

        else if (transformed.getBounds2D().getY() < 0){
            double tempAng = ship.getAng();
            double diff = 180-tempAng;
            transform.rotate(Math.toRadians(diff), ship.getCenterX(), ship.getCenterY());
            transform.translate(0,-HEIGHT);
            transform.rotate(Math.toRadians(-diff), ship.getCenterX(), ship.getCenterY());
        }

        if (right){
            ship.right();
            //rotating the ship
            transform.rotate(Math.toRadians(turnRight), ship.getCenterX(), ship.getCenterY());
            //rotating the 'tip' of the ship.
            headTransform.rotate(Math.toRadians(turnRight), ship.getCenterX(), ship.getCenterY());
        }

        else if (left){
            ship.left();
            //rotating the ship
            transform.rotate(Math.toRadians(turnLeft), ship.getCenterX(), ship.getCenterY());
            //rotating the 'tip' of the ship
            headTransform.rotate(Math.toRadians(turnLeft), ship.getCenterX(), ship.getCenterY());
        }
        if (go){
            ship.go();
        }
        else if (back){
            ship.reverse();
        }

        //moving and shaping each individual laser that had been shot
        for (int i = 0; i < transformedLasers.size(); i++){
            lasers.get(i).move();

            lasTransform = new AffineTransform();
            lasTransform.rotate(Math.toRadians(lasers.get(i).getAng()), transformed.getBounds2D().getX(), transformed.getBounds2D().getY());
            transformedLasers.set(i, lasTransform.createTransformedShape(lasers.get(i)));

        }

        //moving the ship
        ship.move();

        //moving the 'tip'
        shipHead.y -= ship.getSpeed();

        transformed = transform.createTransformedShape(ship);
        shipHeadTrans = headTransform.createTransformedShape(shipHead);

        renderer.repaint();

    }

    //defining a new laser
    public void fireLaser(){
        Laser tempLaser = new Laser((int)transformed.getBounds2D().getX(), (int)transformed.getBounds2D().getY(), 5, 10, ship.getAng());
        lasers.add(tempLaser);

        lasTransform = new AffineTransform();
        lasTransform.rotate(Math.toRadians(ship.getAng()), transformed.getBounds2D().getX(), transformed.getBounds2D().getY());
        transformedLasers.add(lasTransform.createTransformedShape(tempLaser));

    }

    public static void main(String[] args){
        game = new AsteroidGame();
    }

    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub
        if (e.getKeyCode() == KeyEvent.VK_RIGHT){
            right = true;
            keyDown = true;
        }else if (e.getKeyCode() == KeyEvent.VK_LEFT){
            left = true;
            keyDown = true;
        }

        else if (e.getKeyCode() == KeyEvent.VK_UP){
            go = true;
        }
        else if (e.getKeyCode() == KeyEvent.VK_DOWN){
            back = true;
        }

        //fire laser
        if (e.getKeyCode() == KeyEvent.VK_SPACE){
            fireLaser();
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub
        if (e.getKeyCode() == KeyEvent.VK_RIGHT){
            right = false;
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT){
            left = false;
        }
        if (e.getKeyCode() == KeyEvent.VK_UP){
            go = false;
        }
        if (e.getKeyCode() == KeyEvent.VK_DOWN){
            back = false;
        }
        still = true;
        keyDown = false;
    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }

Ship Class (I don't think it's relevant though)

package asteroidGame;

import java.awt.Polygon;
import java.util.Arrays;

public class Ship extends Polygon{

    /**
     *
     */
    private double currSpeed = 0;

    private static final long serialVersionUID = 1L;
    public double angle;
    public int[] midX;
    public int[] midY;

    public Ship(int[] x, int[] y, int points, double angle){
        super(x, y, points);
        midX = x;
        midY = y;

        this.angle= angle;
    }

    public void right(){
        angle += 5;
    }
    public void left(){
        angle -= 5;
    }

    public void move(){
        for (int i = 0; i < super.ypoints.length; i++){
            super.ypoints[i] -= currSpeed;
            //System.out.println(super.ypoints[i]);
            //System.out.println(super.xpoints[i]);
        }
        //System.out.println(Arrays.toString(super.ypoints));

    }
    public double getSpeed(){
        return currSpeed;
    }

    public void reverse(){
        if (currSpeed  > -15) currSpeed -= 0.2;
    }

    public void go(){
        if (currSpeed < 25) currSpeed += 0.5;

    }

    public int getCenterX(){
        return super.xpoints[2];
    }
    public int getCenterY(){
        return super.ypoints[2];
    }

    public double getAng(){
        return angle;
    }
    public void test(){
        for (int x = 0; x < super.ypoints.length; x++){
            super.ypoints[x] += 1000;
        }
    }

    /*
    public void decrement(){
        if(currSpeed == 0){}

        else if (currSpeed > 0 && currSpeed < 15){
            currSpeed -= 0.05;

        }
        else if (currSpeed < 0 && currSpeed > -15){
            currSpeed += 0.05;

        }
        System.out.println("losing speed");
    }
    */
}

Laser Class (I don't think this is relevant either, but here ya go.)

package asteroidGame;

import java.awt.Color;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;

public class Laser extends Rectangle{

    private double angle;

    public Laser(int x, int y , int width, int height, double ang){
        super(x, y, width, height);
        angle = ang;
        Rectangle tst = new Rectangle();

    }

    public void move(){
        super.y -= 35;
    }

    public double getAng(){
        return angle;
    }

    public boolean intersects (Rectangle2D r){
        //if intersects
        if (super.intersects(r)){
            return true;
        }
        else{
            return false;
        }

    }

}

I was thinking of maybe turning the the Shape object transformed back into a Polygon to get the point, but I'm not sure how or if that would work.

Body:
You can use AffineTransform.transform(Point2D, Point2D) to transform a single point on your polygon.

Things would be a lot simpler for you if instead of trying to move the ship by using a rotation transform you kept a single (x,y) location of where the ship is. You'd move the ship's location in move() instead of trying to translate the polygon. Then when you want to paint the ship you e.g. do:

// Optionally copying the Graphics so the
// transform doesn't affect later painting.
Graphics2D temp = (Graphics2D) g2d.create();
temp.translate(ship.locX, ship.locY);
temp.rotate(ship.angle);
temp.draw(ship);

To move a point based on speed you can do this to find the movement vector:

double velX = speed * Math.cos(angle);
double velY = speed * Math.sin(angle);
locX += timeElapsed * velX;
locY += timeElapsed * velY;

That is essentially a conversion from polar to Cartesian coordinates. The x and y velocities are the legs of a triangle whose hypotenuse is speed and whose known angle is angle:

             /|
            / |
           /  |
          /   |
   speed /    |
        /     |
       /      |velY
      / angle |
     /)_______|
         velX

There's an example of doing movement this way in an answer of mine here: https://stackoverflow.com/a/43692434/2891664.

For your comments:

Are you saying that, unlike my initial move function, just to make ship hold a single point, and thus I would only translate that instead?

More or less, yes. You'd still have a polygon to hold the ship's shape, but the points on the polygon would be relative to (0,0).

Suppose the following definitions:

Each (x,y) point on the polygon is pi. (In other words, one of p0, p1, p2 and p3.)

The (x,y) coordinates of the translation are T

Then, after translating the Graphics2D, each pi coordinate becomes pi+T on the panel. So if your polygon points are defined relative to (0,0) then translating to the ship's (locX,locY) will move the polygon to a location relative to (locX,locY).

It could be simplest then to define the point which is the tip of the polygon as being (0,0) so that after the translation the tip of the ship is the ship's location:

// Your original points:
int xPoints[] = {800, 780, 800, 820};
int yPoints[] = {400, 460, 440, 460};
// Become these points relative to (0,0):
int xPoints[] = {0, -20, 0, 20};
int yPoints[] = {0, 60, 40, 60};

And to e.g. start the ship in the same place, you would initialize its location to (800,400).

I was thinking about this again and realized the rotation is a little more complicated, because you probably don't want to rotate the ship around the tip. You probably want to rotate the ship around its center.

So, here's an MCVE demonstrating how to do all of this.

package mcve.game;

import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.GraphicsConfiguration;
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;

public class MovementExample implements ActionListener {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(MovementExample::new);
    }

    final int fps    = 60;
    final int period = 1000 / fps;

    final JFrame    frame;
    final GamePanel panel;
    final Controls  controls;
    final Ship      ship;

    final List<Bullet> bullets = new ArrayList<>();

    MovementExample() {
        frame = new JFrame("Movement Example");

        Dimension size = getMaximumWindowSize(frame);
        size.width  /= 2;
        size.height /= 2;
        frame.setPreferredSize(size);

        panel = new GamePanel();
        frame.setContentPane(panel);

        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        controls = new Controls();

        ship = new Ship(panel.getWidth()  / 2,
                        panel.getHeight() / 2);

        new Timer(period, this).start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        double secondsElapsed = 1.0 / fps;
        ship.update(secondsElapsed);

        bullets.forEach(b -> b.update(secondsElapsed));
        Rectangle bounds = panel.getBounds();
        bullets.removeIf(b -> !bounds.contains(b.locX, b.locY));

        panel.repaint();
    }

    class GamePanel extends JPanel {
        GamePanel() {
            setBackground(Color.WHITE);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);

            if (ship != null) {
                ship.draw(g2);
            }
            bullets.forEach(b -> b.draw(g2));

            g2.dispose();
        }
    }

    abstract class AbstractGameObject {
        double maxSpeed;
        double rotationAngle;
        double locX;
        double locY;
        double velX;
        double velY;

        AbstractGameObject(double initialX, double initialY) {
            locX = initialX;
            locY = initialY;
        }

        abstract void update(double secondsElapsed);
        abstract void draw(Graphics2D g2);
    }

    class Ship extends AbstractGameObject {
        Polygon shape;
        double  rotationRate;

        Ship(double initialX, double initialY) {
            super(initialX, initialY);
            maxSpeed      = 128; // pixels/second
            rotationAngle = Math.PI * 3 / 2;
            rotationRate  = (2 * Math.PI) / 2; // radians/second

            int xPoints[] = {0, -20, 0, 20};
            int yPoints[] = {0, 60, 40, 60};
            shape = new Polygon(xPoints, yPoints, 4);
        }

        Point2D.Double getTip() {
            Point2D.Double center = getCenter();
            // The tip is at (0,0) and it's already centered
            // on the x-axis origin, so the distance from the
            // tip to the center is just center.y.
            double distance = center.y;
            // Then find the location of the tip, relative
            // to the center.
            double tipX = distance * Math.cos(rotationAngle);
            double tipY = distance * Math.sin(rotationAngle);
            // Now find the actual location of the center.
            center.x += locX;
            center.y += locY;
            // And return the actual location of the tip, relative
            // to the actual location of the center.
            return new Point2D.Double(tipX + center.x, tipY + center.y);
        }

        Point2D.Double getCenter() {
            // Returns the center point of the ship,
            // relative to (0,0).
            Point2D.Double center = new Point2D.Double();
            for (int i = 0; i < shape.npoints; ++i) {
                center.x += shape.xpoints[i];
                center.y += shape.ypoints[i];
            }
            center.x /= shape.npoints;
            center.y /= shape.npoints;
            return center;
        }

        @Override
        void update(double secondsElapsed) {
            // See my answer here: https://stackoverflow.com/a/43692434/2891664
            // for a discussion of why this logic is the way it is.
            double speed = 0;
            if (controls.isUpHeld()) {
                speed += maxSpeed;
            }
            if (controls.isDownHeld()) {
                speed -= maxSpeed;
            }
            velX  = speed * Math.cos(rotationAngle);
            velY  = speed * Math.sin(rotationAngle);
            locX += secondsElapsed * velX;
            locY += secondsElapsed * velY;

            double rotation = 0;
            if (controls.isLeftHeld()) {
                rotation -= rotationRate;
            }
            if (controls.isRightHeld()) {
                rotation += rotationRate;
            }
            rotationAngle += secondsElapsed * rotation;
            // Cap the angle so it can never e.g. get so
            // large that it loses precision.
            if (rotationAngle > 2 * Math.PI) {
                rotationAngle -= 2 * Math.PI;
            }

            if (controls.isFireHeld()) {
                Point2D.Double tipLoc = getTip();
                Bullet bullet = new Bullet(tipLoc.x, tipLoc.y, rotationAngle);
                bullets.add(bullet);
            }
        }

        @Override
        void draw(Graphics2D g2) {
            Graphics2D copy = (Graphics2D) g2.create();
            copy.setColor(Color.RED);

            // Translate to the ship's location.
            copy.translate(locX, locY);
            // Rotate the ship around its center.
            Point2D.Double center = getCenter();
            // The PI/2 offset is necessary because the
            // polygon points are defined with the ship
            // already vertical, i.e. at an angle of -PI/2.
            copy.rotate(rotationAngle + (Math.PI / 2), center.x, center.y);

            copy.fill(shape);
        }
    }

    class Bullet extends AbstractGameObject {
        Ellipse2D.Double shape = new Ellipse2D.Double();

        Bullet(double initialX, double initialY, double initialRotation) {
            super(initialX, initialY);
            maxSpeed      = 512;
            rotationAngle = initialRotation;
            velX          = maxSpeed * Math.cos(rotationAngle);
            velY          = maxSpeed * Math.sin(rotationAngle);

            double radius = 3;
            shape.setFrame(-radius, -radius, 2 * radius, 2 * radius);
        }

        @Override
        void update(double secondsElapsed) {
            locX += secondsElapsed * velX;
            locY += secondsElapsed * velY;
        }

        @Override
        void draw(Graphics2D g2) {
            Graphics2D copy = (Graphics2D) g2.create();
            copy.setColor(Color.BLACK);
            copy.translate(locX, locY);
            copy.fill(shape);
        }
    }

    // See https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
    class Controls {
        final Set<Integer> keysHeld = new HashSet<>();

        Controls() {
            bind(KeyEvent.VK_A, "left");
            bind(KeyEvent.VK_D, "right");
            bind(KeyEvent.VK_W, "up");
            bind(KeyEvent.VK_S, "down");
            bind(KeyEvent.VK_SPACE, "fire");
        }

        boolean isLeftHeld()  { return keysHeld.contains(KeyEvent.VK_A); }
        boolean isRightHeld() { return keysHeld.contains(KeyEvent.VK_D); }
        boolean isUpHeld()    { return keysHeld.contains(KeyEvent.VK_W); }
        boolean isDownHeld()  { return keysHeld.contains(KeyEvent.VK_S); }
        boolean isFireHeld()  { return keysHeld.contains(KeyEvent.VK_SPACE); }

        void bind(int keyCode, String name) {
            bind(keyCode, name, true);
            bind(keyCode, name, false);
        }

        void bind(int keyCode, String name, boolean isOnRelease) {
            KeyStroke stroke = KeyStroke.getKeyStroke(keyCode, 0, isOnRelease);
            name += isOnRelease ? ".released" : ".pressed";
            panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
                 .put(stroke, name);
            panel.getActionMap()
                 .put(name, new AbstractAction() {
                     @Override
                     public void actionPerformed(ActionEvent e) {
                         if (isOnRelease) {
                             keysHeld.remove(keyCode);
                         } else {
                             keysHeld.add(keyCode);
                         }
                     }
                 });
        }
    }

    // This returns the usable size of the display which
    // the JFrame resides in, as described here:
    // http://docs.oracle.com/javase/8/docs/api/java/awt/GraphicsEnvironment.html#getMaximumWindowBounds--
    static Dimension getMaximumWindowSize(JFrame frame) {
        GraphicsConfiguration config = frame.getGraphicsConfiguration();
        Dimension size   = config.getBounds().getSize();
        Insets    insets = Toolkit.getDefaultToolkit().getScreenInsets(config);
        size.width  -= insets.left + insets.right;
        size.height -= insets.top  + insets.bottom;
        return size;
    }
}

There are other ways the tip of the ship could be calculated, but the way I did it in the MCVE is this:

Get the center point of the ship, relative to (0,0).

Get the distance from the center point to the tip. The tip is at (0,0) so this is just the y-coordinate of the center.

Then calculate the (x,y) location of the tip, relative to the center. This is done in a very similar way to the figure above for speed and velocity, but the hypotenuse is the distance between the center and the tip of the ship.

Translate the center to be relative to the ship's location.

Translate the location of the tip (which is relative to the center) to be relative to the ship's location.

It could also all be done with an AffineTransform, similar to what you are doing in the code in the question, but you'd set it on every update. Something like this:

AffineTransform transform = new AffineTransform();

@Override
void update(double secondsElapsed) {
    ...
    // Clear the previous translation and rotation.
    transform.setToIdentity();
    // Set to current.
    transform.translate(locX, locY);
    Point2D.Double center = getCenter();
    transform.rotate(rotationAngle + (Math.PI / 2), center.x, center.y);

    if (controls.isFireHeld()) {
        Point2D.Double tip = new Point2D.Double(0, 0);
        transform.transform(tip, tip);
        Bullet bullet = new Bullet(tip.x, tip.y, rotationAngle);
        bullets.add(bullet);
    }
}

You could still use a transform to do calculations that way, but you don't end up with any strangeness from depending on the transform for movement. (In the code in the question, the ship is e.g. only ever moved along the y-axis. The apparent sideways movement is due to the series of rotation concatenations.)


来源: stackexchange

问:
PARSE.COM: Fetch data at query
When a query is made in Parse, only the ObjectId is downloaded.

Is there any way to download all the columns data in the same call?

If there isn't, which is the quickest way to fetch it al?

This is what I came up with, but since the calls are done 1 after each other, it takes so long to execute.

```<code>// Create query
ParseUser user = ParseUser.getCurrentUser();
ParseQuery<Centro> query = ParseQuery.getQuery("...");
query.include(...);
query.whereEqualTo(...);
query.addAscendingOrder(...);

// Execute query
try {
    CLASS = query.find();
} catch (ParseException e) {
    return false;
}

// Force to fetch all data by reading a single column
for (CLASS class : classes){
    try {
        class.fetch();
        class.getSomething();
    } catch (ParseException e) { }
}
</code>```

Any help is appreciated, thank you.

答:
I don't think is does get just get the objectID if you structure your query as in the Docs then you could get something like this:</p>

```<code>ParseQuery<ParseObject> query = ParseQuery.getQuery("FamousPerson");
query.whereEqualTo("name", "Donald Trump");
query.getFirstInBackground(new GetCallback<ParseObject>() {
  public void done(ParseObject object, ParseException e) {
    if (object == null) {
      Log.d("person", "The getFirst request failed.");
    } else {
       String myJob = object.getString("Job") //equals "President"

    }
  }
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: PARSE.COM: Fetch data at query

Body:
When a query is made in Parse, only the ObjectId is downloaded.

Is there any way to download all the columns data in the same call?

If there isn't, which is the quickest way to fetch it al?

This is what I came up with, but since the calls are done 1 after each other, it takes so long to execute.

// Create query
ParseUser user = ParseUser.getCurrentUser();
ParseQuery<Centro> query = ParseQuery.getQuery("...");
query.include(...);
query.whereEqualTo(...);
query.addAscendingOrder(...);

// Execute query
try {
    CLASS = query.find();
} catch (ParseException e) {
    return false;
}

// Force to fetch all data by reading a single column
for (CLASS class : classes){
    try {
        class.fetch();
        class.getSomething();
    } catch (ParseException e) { }
}

Any help is appreciated, thank you.

Body:
I don't think is does get just get the objectID if you structure your query as in the Docs then you could get something like this:

ParseQuery<ParseObject> query = ParseQuery.getQuery("FamousPerson");
query.whereEqualTo("name", "Donald Trump");
query.getFirstInBackground(new GetCallback<ParseObject>() {
  public void done(ParseObject object, ParseException e) {
    if (object == null) {
      Log.d("person", "The getFirst request failed.");
    } else {
       String myJob = object.getString("Job") //equals "President"

    }
  }
});


问:
pyodbc and python 3.4 on Windows
pyodbc is a very nice thing, but the Windows installers only work with their very specific python version.  With the release of Python 3.4, the only available installers just stop once they don't see 3.3 in the registry (though 3.4 is certainly there).

Copying the .pyd and .egg-info files from a 3.3 installation into the 3.4 site-packages directory doesn't seem to do the trick.  When importing pyodbc, an ImportError is thrown: ImportError: DLL load failed: %1 is not a valid Win32 application.

Is there a secret sauce that can be added to make the 3.3 file work correctly?  Or do we just need to wait for a 3.4 installer version?

答:
I fixed this by installing pyodbc 3.0.10. The latest version of pyodbc didn't work on Windows with Python 3.4

However pyodbc 3.0.10 did work for me

Install command on command prompt : pip install pyodbc 3.0.10

Title: pyodbc and python 3.4 on Windows


问:
How can I find out what type of c# project I'm using in Visual Studio 2017?
I don't know a lot about c# or Visual Studio and I am working on a c# project, but I don't know the details of it. For example if it's a Desktop project, an Asp.net project, a .Net framework project, or what libraries it has access to.

How can I find this out?

答: If you right click the project and go to properties it will provide you with the information that you're looking for.</p>


问:
How do you uninstall in *nix?
One of the things I still can't wrap my head around is rules of thumb to uninstall programs in *nix environments. Most of the time I'm happy to let the sleeping dogs lie and not uninstall software that I no longer need. But from time to time I end up with several Apaches, svn, etc.

So far here's what I know about dealing with this:

1) if you installed using apt-get or yum, there's an uninstall command. Very rarely there's an uninstall script somewhere in the app's folder, something like uninstall.sh

2) to figure out which particular install is being called from the command line use "type -a" command

3) use "sudo find / | grep" to find where else stuff might be installed (from what I understand type only looks for things that are in the PATH variable)

4) Add/change order of things in PATH to make the desireable version of the app to be first in line or add an alias to .bashrc

5) delete the stuff I no longer want. This one is easy if the application was installed only in one folder, but tricky if there are multiple. One trick that I've heard of is running a find with a time range to find all the files that changed arount the time when the install happened - that roughly shows what was changed and added.

Do you have anything to add/correct?

答:
Generally, if you're compiling something from source, the procedure will be

```<code>$ make
$ su
# make install
</code>```

in which case, the vast majority of programs will have an uninstall target, which will let you reverse the steps that happened during install by

```<code>$ su
# make uninstall
</code>```

As always, read the program's README or INSTALL files to determine what's available.  In most situations you'll either install something via a package manager (which will also handle the uninstall), or you'll have invoked some kind of manual process (which should have come with a readme explaining how to uninstall it).

OwnerDisplayName: deadprogrammer

ContentLicense: CC BY-SA 2.5

Title: How do you uninstall in *nix?

LastEditorDisplayName: deadprogrammer

Body:
Generally, if you're compiling something from source, the procedure will be

$ make
$ su
# make install

in which case, the vast majority of programs will have an uninstall target, which will let you reverse the steps that happened during install by

$ su
# make uninstall

As always, read the program's README or INSTALL files to determine what's available.  In most situations you'll either install something via a package manager (which will also handle the uninstall), or you'll have invoked some kind of manual process (which should have come with a readme explaining how to uninstall it).

OwnerDisplayName: dtsazza


问:
What is the best way to cast from ArrayList to List in .Net 2.0
I have a ArrayList of type BookingData to List<BookingData> ?

I am using .net 2.0 so i cannot use arrayList.Cast<int>().ToList() , and I dont want to make here foreach loop , do you have better ideas ?

Thanks.

答:
Use this method:

```<code>public static List<T> ConvertToList<T>(ArrayList list)
{
    if (list == null)
        throw new ArgumentNullException("list");

    List<T> newList = new List<T>(list.Count);

    foreach (object obj in list)
        newList.Add((T)obj);

    // If you really don't want to use foreach:
    // for (int i = 0; i < list.Count; i++)
    //     newList.Add((T)list[i]);

    return newList;
}
</code>```

Then you can:

```<code>List<BookingData> someList = ConvertToList<BookingData>(someArrayList);
</code>```

Body:
Use this method:

public static List<T> ConvertToList<T>(ArrayList list)
{
    if (list == null)
        throw new ArgumentNullException("list");

    List<T> newList = new List<T>(list.Count);

    foreach (object obj in list)
        newList.Add((T)obj);

    // If you really don't want to use foreach:
    // for (int i = 0; i < list.Count; i++)
    //     newList.Add((T)list[i]);

    return newList;
}

Then you can:

List<BookingData> someList = ConvertToList<BookingData>(someArrayList);


问:
Large numbers conversion to Byte in Kotlin
Why does a double of 65555 converted to byte produce a result of 19 in Kotlin?

答: Double 65555.0 gets converted to integer 65555 which is 0x10013. Conversion to Byte takes lower byte which is 0x13 (19 decimal).</p>


问:
Inkscape objects lose transparency when saved as a PDF
I've seen a number of issues dealing with saving inkscape drawings as anything other than a svg but haven't seen a discussion specifically about transparent objects in PDFs. What's happening is that when I export a png any transparent object looks fine but if I save it as a PDF or eps the transparency is lost.
 I've created an example which you can see at this link ( http://imgur.com/a/ieVuu )

I've looked at a lot of other posts and feel like the explanation to this is layered within the responses but I'm a beginner and can't read between the lines to understand it. I wanted to just ask why this is happening and what can be done about it directly?

答: Use Alpha Channel to set the transparency instead of Opacity option.


问:
removing item from array
I have 2 arrays & 2 checkbox repeaters: the second gets populated w/ items selected from the first. I can add the items no problem. How do I then delete the item if it gets deselected from the first checkbox repeater?</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/mx"
        creationComplete="updateOlder();"
         >
<fx:Script>
    <![CDATA[
        import mx.collections.ArrayCollection;

        [Bindable]
        public var older:ArrayCollection  = new ArrayCollection ([]);

        [Bindable]
        public var newer:ArrayCollection  = new ArrayCollection ([]);

        private function updateOlder():void{
            older.addItem({label:"item1",desc:"desc1"});
            older.addItem({label:"item2",desc:"desc2"});
            older.addItem({label:"item3",desc:"desc3"});
        }

        private function updateNewer(evt:MouseEvent):void{
            if(evt.target.selected) {
                // add item to array
                newer.addItem({ label:evt.currentTarget.label,     desc:evt.currentTarget.data });
                newer.refresh();
            }
            else {
                // remove item from array
                newer.removeItemAt( newRepeater.currentIndex.valueOf() );
                newer.refresh();

            }
        }
    ]]>
</fx:Script>

<mx:HBox width="100%" height="100%">
<mx:VBox width="100%" height="100%">
    <mx:Repeater id="oldRepeater" dataProvider="{older}">
        <mx:CheckBox color="black" fontFamily="Arial" fontSize="14"
                     label="{oldRepeater.currentItem.label}"
                     data="{oldRepeater.currentItem.desc}"
                     click="updateNewer(event);"
                     />
    </mx:Repeater>
</mx:VBox>
    <mx:VBox width="100%" height="100%">
    <mx:Repeater id="newRepeater" dataProvider="{newer}">
        <mx:CheckBox color="red" fontFamily="Arial" fontSize="14"
                     label="{newRepeater.currentItem.label}"
                     data="{newRepeater.currentItem.desc}"
                     />
    </mx:Repeater>
</mx:VBox>
</mx:HBox>

</mx:Application>
</code>```

答:
Repeater.currentIndex property is not -1 only while the Repeater iterates through its' dataProvider.
here's your code working:

```<code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/mx"
        creationComplete="updateOlder();"
         >
<fx:Script>
    <![CDATA[
        import mx.collections.ArrayCollection;
        import flash.events.MouseEvent;
        import mx.controls.CheckBox;
        import mx.core.Repeater;
        [Bindable]
        public var older:ArrayCollection  = new ArrayCollection ([]);
        [Bindable]
        public var newer:ArrayCollection  = new ArrayCollection ([]);

        private function updateOlder():void{
            older.addItem({key:'item1',val:'desc1'});
            older.addItem({key:'item2',val:'desc2'});
            older.addItem({key:'item3',val:'desc3'});
        }

        private function updateNewer(evt:MouseEvent):void {
            var tmpBox:CheckBox = evt.target as CheckBox;
            if(tmpBox.selected) {
                // add item to array
                newer.addItem({key:tmpBox.label,val:tmpBox.data});
            }
            else {
                // remove item from array
                var newArrIndex: int = getArrayElementIndex(newer, older[tmpBox.instanceIndex]);
                if(newArrIndex != -1){
                    newer.removeItemAt(newArrIndex);
                }
            }
            newer.refresh();
        }

        private function getArrayElementIndex(arr:ArrayCollection, elementValue:Object):int{
            for (var retInd: int = 0; retInd < arr.length; retInd++) {
                if (arr[retInd]['key'] == elementValue['key'] && arr[retInd]['val'] == elementValue['val']) {
                    return retInd;
                }
            }
            return -1;
        }
    ]]>
</fx:Script>

<mx:HBox width="100%" height="100%">
<mx:VBox width="100%" height="100%">
    <mx:Repeater id="oldRepeater" dataProvider="{older}">
        <mx:CheckBox color="black" fontFamily="Arial" fontSize="14"
                     label="{oldRepeater.currentItem['key']}"
                     data="{oldRepeater.currentItem['val']}"
                     click="updateNewer(event);"
                     />
    </mx:Repeater>
</mx:VBox>
    <mx:VBox width="100%" height="100%">
    <mx:Repeater id="newRepeater" dataProvider="{newer}">
        <mx:CheckBox color="red" fontFamily="Arial" fontSize="14"
                     label="{newRepeater.currentItem['key']}"
                     data="{newRepeater.currentItem['val']}"
                     />
    </mx:Repeater>
</mx:VBox>
</mx:HBox>
</mx:Application>
</code>```

Title: removing item from array

Body:
I have 2 arrays & 2 checkbox repeaters: the second gets populated w/ items selected from the first. I can add the items no problem. How do I then delete the item if it gets deselected from the first checkbox repeater?

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/mx"
        creationComplete="updateOlder();"
         >
<fx:Script>
    <![CDATA[
        import mx.collections.ArrayCollection;

        [Bindable]
        public var older:ArrayCollection  = new ArrayCollection ([]);

        [Bindable]
        public var newer:ArrayCollection  = new ArrayCollection ([]);

        private function updateOlder():void{
            older.addItem({label:"item1",desc:"desc1"});
            older.addItem({label:"item2",desc:"desc2"});
            older.addItem({label:"item3",desc:"desc3"});
        }

        private function updateNewer(evt:MouseEvent):void{
            if(evt.target.selected) {
                // add item to array
                newer.addItem({ label:evt.currentTarget.label,     desc:evt.currentTarget.data });
                newer.refresh();
            }
            else {
                // remove item from array
                newer.removeItemAt( newRepeater.currentIndex.valueOf() );
                newer.refresh();

            }
        }
    ]]>
</fx:Script>

<mx:HBox width="100%" height="100%">
<mx:VBox width="100%" height="100%">
    <mx:Repeater id="oldRepeater" dataProvider="{older}">
        <mx:CheckBox color="black" fontFamily="Arial" fontSize="14"
                     label="{oldRepeater.currentItem.label}"
                     data="{oldRepeater.currentItem.desc}"
                     click="updateNewer(event);"
                     />
    </mx:Repeater>
</mx:VBox>
    <mx:VBox width="100%" height="100%">
    <mx:Repeater id="newRepeater" dataProvider="{newer}">
        <mx:CheckBox color="red" fontFamily="Arial" fontSize="14"
                     label="{newRepeater.currentItem.label}"
                     data="{newRepeater.currentItem.desc}"
                     />
    </mx:Repeater>
</mx:VBox>
</mx:HBox>

</mx:Application>

Body:
Repeater.currentIndex property is not -1 only while the Repeater iterates through its' dataProvider.
here's your code working:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/mx"
        creationComplete="updateOlder();"
         >
<fx:Script>
    <![CDATA[
        import mx.collections.ArrayCollection;
        import flash.events.MouseEvent;
        import mx.controls.CheckBox;
        import mx.core.Repeater;
        [Bindable]
        public var older:ArrayCollection  = new ArrayCollection ([]);
        [Bindable]
        public var newer:ArrayCollection  = new ArrayCollection ([]);

        private function updateOlder():void{
            older.addItem({key:'item1',val:'desc1'});
            older.addItem({key:'item2',val:'desc2'});
            older.addItem({key:'item3',val:'desc3'});
        }

        private function updateNewer(evt:MouseEvent):void {
            var tmpBox:CheckBox = evt.target as CheckBox;
            if(tmpBox.selected) {
                // add item to array
                newer.addItem({key:tmpBox.label,val:tmpBox.data});
            }
            else {
                // remove item from array
                var newArrIndex: int = getArrayElementIndex(newer, older[tmpBox.instanceIndex]);
                if(newArrIndex != -1){
                    newer.removeItemAt(newArrIndex);
                }
            }
            newer.refresh();
        }

        private function getArrayElementIndex(arr:ArrayCollection, elementValue:Object):int{
            for (var retInd: int = 0; retInd < arr.length; retInd++) {
                if (arr[retInd]['key'] == elementValue['key'] && arr[retInd]['val'] == elementValue['val']) {
                    return retInd;
                }
            }
            return -1;
        }
    ]]>
</fx:Script>

<mx:HBox width="100%" height="100%">
<mx:VBox width="100%" height="100%">
    <mx:Repeater id="oldRepeater" dataProvider="{older}">
        <mx:CheckBox color="black" fontFamily="Arial" fontSize="14"
                     label="{oldRepeater.currentItem['key']}"
                     data="{oldRepeater.currentItem['val']}"
                     click="updateNewer(event);"
                     />
    </mx:Repeater>
</mx:VBox>
    <mx:VBox width="100%" height="100%">
    <mx:Repeater id="newRepeater" dataProvider="{newer}">
        <mx:CheckBox color="red" fontFamily="Arial" fontSize="14"
                     label="{newRepeater.currentItem['key']}"
                     data="{newRepeater.currentItem['val']}"
                     />
    </mx:Repeater>
</mx:VBox>
</mx:HBox>
</mx:Application>


问:
fullCalendar - include end date
I'm working on a events cms and using fullCalendar.io to show the events.
My events are only dates without time and I'm storing the informations in a mySQL database.
I have no way to change the mySQL column format nor the event insertion method to add a time to the date, although I need to show the end date included while showing the calendar.
I'll paste my code to show how it works.

```<code>$('#calendar').fullCalendar({
    header: {
        left: 'prev,next,today',
        center: 'title'
    },
    defaultView: 'month',
    eventSources: [{
        url: 'getJsonEvents',
        type: 'POST',
        success: function(data) {
        },
        error: function() {
        },
        color: '#2D4047',
        textColor: 'white',
    }]
});
</code>```

the column that store the date is a simple DATE mysql column.

EDIT:
To be clear, the problem is that my event end (eg.) the 19th but on the calendar view it seems to end the 18th.

Attached image

答:
From https://fullcalendar.io/docs/event_data/Event_Object/ :

"end"...is the moment immediately after the event has ended. For
  example, if the last full day of an event is Thursday, the exclusive
  end of the event will be 00:00:00 on Friday!

So if you have an all-day event you simply need to increase the value of the "end" parameter you're sending to fullCalendar by 1 day. This is a pretty common approach - Google Calendar's API does it the same way, for example.

Title: fullCalendar - include end date

Body:
I'm working on a events cms and using fullCalendar.io to show the events.
My events are only dates without time and I'm storing the informations in a mySQL database.
I have no way to change the mySQL column format nor the event insertion method to add a time to the date, although I need to show the end date included while showing the calendar.
I'll paste my code to show how it works.

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next,today',
        center: 'title'
    },
    defaultView: 'month',
    eventSources: [{
        url: 'getJsonEvents',
        type: 'POST',
        success: function(data) {
        },
        error: function() {
        },
        color: '#2D4047',
        textColor: 'white',
    }]
});

the column that store the date is a simple DATE mysql column.

EDIT:
To be clear, the problem is that my event end (eg.) the 19th but on the calendar view it seems to end the 18th.

Attached image


问:
How to implement existential quantifiers in OO programming?
It's easy to asses and implement logic formulas including universal quantifiers via (nested) foreach or for loops:

(\forall x \in X)(\forall y \in Y) (Z(x,y))

```<code>foreach (type x in X)
{
   foreach (type y in Y)
   {
      if(Z(x,y))
         return true;
      else
         return false;
   }
}
</code>```

But how can one implement the existential quantifiers in OO programming languages, especially C# (not logic programming languages)?

(\forall x \in X)(\exists y \in Y) (Z(x,y))

For example, to assess a number x whether it is even or not, we must code the following formula:

(\forall x)(\exists y) (x = y + y)

答: You can also use "First-Order Logic Library" in particular, an open source library. You can use the source and related design documents of such a library as how to design OOP solution for concepts like "Propositional Logic", "First-Order Logic", "Conditional Logic", "Relational Conditional Logic" and "Probabilistic Conditional Logic". For example, http://tweetyproject.org/ is provide us such a library in Java.</p>

Body:
It's easy to asses and implement logic formulas including universal quantifiers via (nested) foreach or for loops:

(\forall x \in X)(\forall y \in Y) (Z(x,y))

foreach (type x in X)
{
   foreach (type y in Y)
   {
      if(Z(x,y))
         return true;
      else
         return false;
   }
}

But how can one implement the existential quantifiers in OO programming languages, especially C# (not logic programming languages)?

(\forall x \in X)(\exists y \in Y) (Z(x,y))

For example, to assess a number x whether it is even or not, we must code the following formula:

(\forall x)(\exists y) (x = y + y)


问:
C++ Printing Odd numbers instead of Prime Numbers
I have been working on an assignment question for days and cannot seem to get the correct output (I've tried so many things!) The question is:

Write a program that uses two nested for loops and the modulus operator (%) to detect and print the prime numbers from 1 to 10,000.

I have been doing from 1 to 10 as a small test to ensure its working. I am getting 2,3,5,7,9 as my output, so I know something is wrong. When I increase the number from 10 to 20 it is printing 2 plus all odd numbers. I am including my code below. Thanks!!

```<code>int main() {

        for (int i=2; i <=10; i++){
            for (int j=2; j<=i; j++){
                if (i%j==0 && j!=i) {

                    break;
                }

                else {

                    cout<< i <<endl;
                    break;
                }
            }
        }
}
</code>```

答:
In addition to Sumit Jindal's answer inner for loop can be done by this way as well:

```<code>for(int j=2; j*j<=i ; j++)
</code>```

If we think about every (x,y) ordered pair that satisfies x*y = i, maximum value of x can be square root of i.

Body:
I have been working on an assignment question for days and cannot seem to get the correct output (I've tried so many things!) The question is:

Write a program that uses two nested for loops and the modulus operator (%) to detect and print the prime numbers from 1 to 10,000.

I have been doing from 1 to 10 as a small test to ensure its working. I am getting 2,3,5,7,9 as my output, so I know something is wrong. When I increase the number from 10 to 20 it is printing 2 plus all odd numbers. I am including my code below. Thanks!!

int main() {

        for (int i=2; i <=10; i++){
            for (int j=2; j<=i; j++){
                if (i%j==0 && j!=i) {

                    break;
                }

                else {

                    cout<< i <<endl;
                    break;
                }
            }
        }
}

Body:
In addition to Sumit Jindal's answer inner for loop can be done by this way as well:

for(int j=2; j*j<=i ; j++)

If we think about every (x,y) ordered pair that satisfies x*y = i, maximum value of x can be square root of i.


问:
In angular bootstrap tabs, how to cancel tab change?
I want to cancel tab change/panel switch when user clicks another tab and I discover that changes in the current panel are not saved.

I use the deselect() attribute of element <tab>, documented here, to fire a function in my controller and in which I determine that I shouldn't change tab. Meaning: I don't want to deselect this and select the other that user clicked on.

How can I accomplish this? preferably from inside the controller, or in any other way?

I can't just do $event.stopPropagation() since I don't have a $event here... what am I missing?

Plunker isolating the problem.

答:
Suppose that you have 3 tabs and want the third tab to be unclickable. Then you should add a deselect attribute to clickable tabs, so that when deselect event happens, they checked what tab we're trying to switch to and if it's the third tab, prevented tab switch.

This works only in later versions of ui-bootstrap, around 0.12-0.14, can't say exactly:

template.html

```<code><uib-tabset class="tab-animation" active="activeTab">
    <uib-tab index="0" heading="Overview" id="overview" deselect="checkTab($event, $selectedIndex)"></uib-tab>
    <uib-tab index="1" heading="Details" id="details" deselect="checkTab($event, $selectedIndex)"></uib-tab>
    <uib-tab index="2" heading="Download" id="download"></uib-tab>
</uib-tabset>
</code>```

controller.js

```<code>// Downloads tab shouldn't be clickable
$scope.checkTab = function($event, $selectedIndex) {
    // $selectIndex is index of the tab, you're switching to
    if ($selectedIndex == 2) { // last tab is non-switchable
        $event.preventDefault();
    }
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Suppose that you have 3 tabs and want the third tab to be unclickable. Then you should add a deselect attribute to clickable tabs, so that when deselect event happens, they checked what tab we're trying to switch to and if it's the third tab, prevented tab switch.

This works only in later versions of ui-bootstrap, around 0.12-0.14, can't say exactly:

template.html

<uib-tabset class="tab-animation" active="activeTab">
    <uib-tab index="0" heading="Overview" id="overview" deselect="checkTab($event, $selectedIndex)"></uib-tab>
    <uib-tab index="1" heading="Details" id="details" deselect="checkTab($event, $selectedIndex)"></uib-tab>
    <uib-tab index="2" heading="Download" id="download"></uib-tab>
</uib-tabset>

controller.js

// Downloads tab shouldn't be clickable
$scope.checkTab = function($event, $selectedIndex) {
    // $selectIndex is index of the tab, you're switching to
    if ($selectedIndex == 2) { // last tab is non-switchable
        $event.preventDefault();
    }
};


问:
Gson Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
This is my arraylist

```<code> ArrayList<Eat> eatList = gson.fromJson(jsonString, new
 TypeToken<ArrayList<Eat>>() {
            }.getType());
</code>```

This is my json: http://www.mocky.io/v2/592fdc32110000ef12b392cc

and this is my model

```<code>public class Eat{

private String title,firstItemTitle,firstItemSutitle,
secondItemTitle,secondItemSutitle,
firstItemPrice,secondItemPrice,
firstItemImage,secondItemImage;

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getFirstItemTitle() {
    return firstItemTitle;
}

public void setFirstItemTitle(String firstItemTitle) {
    this.firstItemTitle = firstItemTitle;
}

public String getFirstItemSutitle() {
    return firstItemSutitle;
}

 public void setFirstItemSutitle(String firstItemSutitle) {
    this.firstItemSutitle = firstItemSutitle;
 }

 }
</code>```

答:
Since your JSON is not a JSON array, but rather a JSON object containing an array, you would need to write a class that contains the ArrayList:

```<code>public class EatResponse {
    @SerializedName("eat")
    private ArrayList<Eat> eatList;

    public ArrayList<Eat> getEatList() {
        return eatList;
    }
}
</code>```

Then, you just need to parse that from your JSON with a call that would look something like this:

```<code>EatResponse response = gson.fromJson(json, EatResponse.class);
ArrayList<Eat> eatList = response.getEatList();
</code>```

Body:
This is my arraylist

 ArrayList<Eat> eatList = gson.fromJson(jsonString, new
 TypeToken<ArrayList<Eat>>() {
            }.getType());

This is my json: http://www.mocky.io/v2/592fdc32110000ef12b392cc

and this is my model

public class Eat{

private String title,firstItemTitle,firstItemSutitle,
secondItemTitle,secondItemSutitle,
firstItemPrice,secondItemPrice,
firstItemImage,secondItemImage;

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getFirstItemTitle() {
    return firstItemTitle;
}

public void setFirstItemTitle(String firstItemTitle) {
    this.firstItemTitle = firstItemTitle;
}

public String getFirstItemSutitle() {
    return firstItemSutitle;
}

 public void setFirstItemSutitle(String firstItemSutitle) {
    this.firstItemSutitle = firstItemSutitle;
 }

 }

Body:
Since your JSON is not a JSON array, but rather a JSON object containing an array, you would need to write a class that contains the ArrayList:

public class EatResponse {
    @SerializedName("eat")
    private ArrayList<Eat> eatList;

    public ArrayList<Eat> getEatList() {
        return eatList;
    }
}

Then, you just need to parse that from your JSON with a call that would look something like this:

EatResponse response = gson.fromJson(json, EatResponse.class);
ArrayList<Eat> eatList = response.getEatList();


问:
how do I access model fields individually?
suppose I have this model:

```<code>id = models.AutoField(primary_key=True)
datetime_from = models.DateTimeField('time')

model = MyModel
def read(self, request, id=0):
    if not id:
        id = 0
 MyModel.object
    mmodel = MyModel.objects.filter(id__gt=id)
    return mmodel
</code>```

My question is, how do I possible get the model fields individually, because I need to validate the datetime_from before I have to output the data on json format

答:
You don't need to create an id column yourself. The read method is not necessary, either. Just say

```<code>from django.db import models

class MyModel(models.Model):
    datetime_from = models.DateTimeField('time')
</code>```

You can then query the table like so

```<code>>>> obj = MyModel.objects.get(id=<target id here>)
>>> date = obj.datetime_from
etc.
</code>```

Body:
suppose I have this model:

id = models.AutoField(primary_key=True)
datetime_from = models.DateTimeField('time')

model = MyModel
def read(self, request, id=0):
    if not id:
        id = 0
 MyModel.object
    mmodel = MyModel.objects.filter(id__gt=id)
    return mmodel

My question is, how do I possible get the model fields individually, because I need to validate the datetime_from before I have to output the data on json format

Body:
You don't need to create an id column yourself. The read method is not necessary, either. Just say

from django.db import models

class MyModel(models.Model):
    datetime_from = models.DateTimeField('time')

You can then query the table like so

>>> obj = MyModel.objects.get(id=<target id here>)
>>> date = obj.datetime_from
etc.


问:
SQL Data won't show up in JTable
I have a program that when the user clicks on a button that the SQL data from the database shows in the JTable. Problem is when i click the button nothing shows up. But when i print the variables, it does show the correct value. So why won't anything show up in my JTable?

Note: JTable/Button was added with GUI design.

Code:

```<code>import connection.connection;
import java.awt.BorderLayout;
import java.awt.Font;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author peter
 */
public class Tabel extends javax.swing.JFrame {

    /**
     * Creates new form Tabel
     */
    public Tabel() {
        initComponents();
    }

    private void showBtnActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        String[] columns = {"Nummer", "Adres", "Postcode", "Plaats",
                            "capaciteit"};

        String sql = "SELECT * FROM uitgiftepunt";

        try (
                Connection conn = connection.getConnection();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
            ){
               DefaultTableModel model = new DefaultTableModel(columns, 0);
                while (rs.next()) {
                    int nummer = rs.getObject("nummer", Integer.class);
                    String adres = rs.getObject("adres", String.class);
                    String postcode = rs.getObject("postcode", String.class);
                    String plaats = rs.getObject("plaats", String.class);
                    int cap = rs.getObject("capaciteit", Integer.class);
                    model.addRow(new Object[]{nummer,adres,postcode,plaats,cap});
                    System.out.printf("%d, %s, %s, %s, %d", nummer,adres,postcode,plaats,cap);

                }

                jTable1.setModel(model);
                jScrollPane1 = new JScrollPane(jTable1);
                jTable1.setFillsViewportHeight(true);

            } catch (SQLException ex) {
            Logger.getLogger(Tabel.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

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

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Tabel().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton showBtn;
    // End of variables declaration
}
</code>```

答:
I suggest to create a separate method to create the table

```<code>public static DefaultTableModel buildTableModel(ResultSet rs)throws SQLException {

    ResultSetMetaData metaData = rs.getMetaData();

    // names of columns
    Vector<String> columnNames = new Vector<String>();
    int columnCount = metaData.getColumnCount();
    for (int column = 1; column <= columnCount; column++) {
        columnNames.add(metaData.getColumnName(column));
    }

    // data of the table
    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
    while (rs.next()) {
        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            vector.add(rs.getObject(columnIndex));
        }
        data.add(vector);
    }

    return new DefaultTableModel(data, columnNames);
}
</code>```

In this way you create a new DefaultTableModel passing the data and columnNames as parameters, the first is a Vector of Vector and the second a Vector

And then

```<code>ResultSet rs = stmt.executeQuery(query);
JTable table = new JTable(buildTableModel(rs));
JScrollPane scrollPane = new JScrollPane(table);
</code>```

In previous table I used I had the problem that the table wasn't filled until I cliccked with the mouse on it, that is another problem, if you face it you can solve it by scrolling down or up by 1 pixel after creating the table

Title: SQL Data won't show up in JTable

Body:
I have a program that when the user clicks on a button that the SQL data from the database shows in the JTable. Problem is when i click the button nothing shows up. But when i print the variables, it does show the correct value. So why won't anything show up in my JTable?

Note: JTable/Button was added with GUI design.

Code:

import connection.connection;
import java.awt.BorderLayout;
import java.awt.Font;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author peter
 */
public class Tabel extends javax.swing.JFrame {

    /**
     * Creates new form Tabel
     */
    public Tabel() {
        initComponents();
    }

    private void showBtnActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        String[] columns = {"Nummer", "Adres", "Postcode", "Plaats",
                            "capaciteit"};

        String sql = "SELECT * FROM uitgiftepunt";

        try (
                Connection conn = connection.getConnection();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
            ){
               DefaultTableModel model = new DefaultTableModel(columns, 0);
                while (rs.next()) {
                    int nummer = rs.getObject("nummer", Integer.class);
                    String adres = rs.getObject("adres", String.class);
                    String postcode = rs.getObject("postcode", String.class);
                    String plaats = rs.getObject("plaats", String.class);
                    int cap = rs.getObject("capaciteit", Integer.class);
                    model.addRow(new Object[]{nummer,adres,postcode,plaats,cap});
                    System.out.printf("%d, %s, %s, %s, %d", nummer,adres,postcode,plaats,cap);

                }

                jTable1.setModel(model);
                jScrollPane1 = new JScrollPane(jTable1);
                jTable1.setFillsViewportHeight(true);

            } catch (SQLException ex) {
            Logger.getLogger(Tabel.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

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

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Tabel().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton showBtn;
    // End of variables declaration
}

Body:
I suggest to create a separate method to create the table

public static DefaultTableModel buildTableModel(ResultSet rs)throws SQLException {

    ResultSetMetaData metaData = rs.getMetaData();

    // names of columns
    Vector<String> columnNames = new Vector<String>();
    int columnCount = metaData.getColumnCount();
    for (int column = 1; column <= columnCount; column++) {
        columnNames.add(metaData.getColumnName(column));
    }

    // data of the table
    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
    while (rs.next()) {
        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            vector.add(rs.getObject(columnIndex));
        }
        data.add(vector);
    }

    return new DefaultTableModel(data, columnNames);
}

In this way you create a new DefaultTableModel passing the data and columnNames as parameters, the first is a Vector of Vector and the second a Vector

And then

ResultSet rs = stmt.executeQuery(query);
JTable table = new JTable(buildTableModel(rs));
JScrollPane scrollPane = new JScrollPane(table);

In previous table I used I had the problem that the table wasn't filled until I cliccked with the mouse on it, that is another problem, if you face it you can solve it by scrolling down or up by 1 pixel after creating the table


问:
Web APi OData V4 Issue "The entity '' does not have a key defined
When I run the following sample it is throwing the following exception...

Additional information: The entity 'TestEntity' does not have a key defined.

I have configured the key using code first entity context...
modelBuilder.Entity<TestEntity>().HasKey(t => t.EntityID);

What is the issue? why is OData V4 not using the configured key?

```<code>namespace WebApplication2
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.MapODataServiceRoute("odata", "odata", model: GetEDMModel());

        }

        private static IEdmModel GetEDMModel()
        {
            ODataModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<TestEntity>("TestEntities");
            return builder.GetEdmModel();
        }
    }

    public class TestEntity
    {
        public int EntityID { get; set; }
        public string Name { get; set; }
    }

    public partial class TestContext1 : DbContext
    {

        public TestContext1() : base("DB")
        {
        }
        public DbSet<TestEntity> Entities { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<TestEntity>().HasKey(t => t.EntityID);

        }
    }

}
</code>```

答:
You defined the key for the database mapping of Entity Framework but not for the OData mapping.

Try this:

```<code> private static IEdmModel GetEDMModel()
 {
       ODataModelBuilder builder = new ODataConventionModelBuilder();
       var entitySet = builder.EntitySet<TestEntity>("TestEntities");
       entitySet.EntityType.HasKey(entity => entity.EntityID)
       return builder.GetEdmModel();
 }
</code>```

Or try adding a [Key] Attribute to your TestEntity to tell OData (and Entity Framework at the same time) what Property is the key.

Like so:

```<code>using System.ComponentModel.DataAnnotations;

public class TestEntity
{
    [Key]
    public int EntityID { get; set; }
    public string Name { get; set; }
}
</code>```

Body:
When I run the following sample it is throwing the following exception...

Additional information: The entity 'TestEntity' does not have a key defined.

I have configured the key using code first entity context...
modelBuilder.Entity<TestEntity>().HasKey(t => t.EntityID);

What is the issue? why is OData V4 not using the configured key?

namespace WebApplication2
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.MapODataServiceRoute("odata", "odata", model: GetEDMModel());

        }

        private static IEdmModel GetEDMModel()
        {
            ODataModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<TestEntity>("TestEntities");
            return builder.GetEdmModel();
        }
    }

    public class TestEntity
    {
        public int EntityID { get; set; }
        public string Name { get; set; }
    }

    public partial class TestContext1 : DbContext
    {

        public TestContext1() : base("DB")
        {
        }
        public DbSet<TestEntity> Entities { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<TestEntity>().HasKey(t => t.EntityID);

        }
    }

}

Body:
You defined the key for the database mapping of Entity Framework but not for the OData mapping.

Try this:

 private static IEdmModel GetEDMModel()
 {
       ODataModelBuilder builder = new ODataConventionModelBuilder();
       var entitySet = builder.EntitySet<TestEntity>("TestEntities");
       entitySet.EntityType.HasKey(entity => entity.EntityID)
       return builder.GetEdmModel();
 }

Or try adding a [Key] Attribute to your TestEntity to tell OData (and Entity Framework at the same time) what Property is the key.

Like so:

using System.ComponentModel.DataAnnotations;

public class TestEntity
{
    [Key]
    public int EntityID { get; set; }
    public string Name { get; set; }
}


问:
How to stack submatrices of a matrix to reduce dimensionality
I couldn't find a good solution for this:

I have a matrix of this size: 60x10x3

And I want to transform it into a matrix of this size: 600x3

Basically I want to stack the 10 matrices with the dimension 60x3 next to each other in the first dimension.

How can I achieve that elegantly in matlab?

答:
```<code>A = rand(60, 10, 3);
B = reshape(A, [], size(A, 3));
</code>```

should work for any dimensions of A.

Body:
A = rand(60, 10, 3);
B = reshape(A, [], size(A, 3));

should work for any dimensions of A.


问:
Show progress dialog while adding views dynamically to scrollview in android

In the start of an activity in OnCreate method, I'm trying to add some text views dynamically to a scrollview of the layout file. But during the time of this operation the screen remains blank. Is it possible to show a progress dialog when adding views dynamically to a scrollview?

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

```<code>    for(i  = 0; i < 20; i++) {
         TextView txt = new TextView(this);
              scrolview.addView(txt);
          }
    }
</code>```

The code is similar to this...can u explain how to put a progress dialog...in this sample using AsyncTask...where should i perform this operation doInBackground method or on postExecute?

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

    for(i  = 0; i < 20; i++) {
         TextView txt = new TextView(this);
              scrolview.addView(txt);
          }
    }

The code is similar to this...can u explain how to put a progress dialog...in this sample using AsyncTask...where should i perform this operation doInBackground method or on postExecute?