问:
Making two objects rotate at the same time
So I have this assignment where I have to make two objects move at the same time. I know that I should use thread class but i am not sure how to do it. My project has two files. The first one has main method and implements fan object.Here it is:

```<code>import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;

    public class DrawArcs extends JFrame {
    public DrawArcs() {
        setTitle("DrawArcs");
        add(new ArcsPanel());
     }

     /** Main method */
    public static void main(String[] args) {
        DrawArcs frame = new DrawArcs();
        frame.setLocationRelativeTo(null); // Center the frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.add(new StillClock());

     }
    }

    class ArcsPanel extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        int xCenter = getWidth() / 2;
        int yCenter = getHeight() / 2;
        int radius = (int)(Math.min(getWidth(), getHeight()) * 0.4);

        int x = xCenter - radius;
        int y = yCenter - radius;

        g.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);
        g.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
        g.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
        g.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
    }
 }
</code>```

My second file includes implementation of the clock class.

```<code>public class StillClock  extends JPanel {
    private int hour;
    private int minute;
    private int second;

    public StillClock() {
        setCurrentTime();
    }

    public StillClock(int hour, int minute, int second) {
        this.hour = hour;
        this.minute = minute;
        this.second = second;
    }
////there are setters and getters here
 .
 .
 .
////

    @Override /** Draw the clock */
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        // Initialize clock parameters
        int clockRadius =
                (int)(Math.min(getWidth(), getHeight()) * 0.8 * 0.5);
        int xCenter = getWidth() / 2;
        int yCenter = getHeight() / 2;

        // Draw circle
        g.setColor(Color.black);
        g.drawOval(xCenter - clockRadius, yCenter - clockRadius,
                2 * clockRadius, 2 * clockRadius);
        g.drawString("12", xCenter - 5, yCenter - clockRadius + 12);
        g.drawString("9", xCenter - clockRadius + 3, yCenter + 5);
        g.drawString("3", xCenter + clockRadius - 10, yCenter + 3);
        g.drawString("6", xCenter - 3, yCenter + clockRadius - 3);

        // Draw second hand
        int sLength = (int)(clockRadius * 0.8);
        int xSecond = (int)(xCenter + sLength *
                Math.sin(second * (2 * Math.PI / 60)));
        int ySecond = (int)(yCenter - sLength *
                Math.cos(second * (2 * Math.PI / 60)));
        g.setColor(Color.red);
        g.drawLine(xCenter, yCenter, xSecond, ySecond);

        // Draw minute hand
        int mLength = (int)(clockRadius * 0.65);
        int xMinute = (int)(xCenter + mLength *
                Math.sin(minute * (2 * Math.PI / 60)));
        int yMinute = (int)(yCenter - mLength *
                Math.cos(minute * (2 * Math.PI / 60)));
        g.setColor(Color.blue);
        g.drawLine(xCenter, yCenter, xMinute, yMinute);

        // Draw hour hand
        int hLength = (int)(clockRadius * 0.5);
        int xHour = (int)(xCenter + hLength *
                Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
        int yHour = (int)(yCenter - hLength *
                Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
        g.setColor(Color.green);
        g.drawLine(xCenter, yCenter, xHour, yHour);
    }

    public void setCurrentTime() {
        // Construct a calendar for the current date and time
        Calendar calendar = new GregorianCalendar();

        // Set current hour, minute and second
        this.hour = calendar.get(Calendar.HOUR_OF_DAY);
        this.minute = calendar.get(Calendar.MINUTE);
        this.second = calendar.get(Calendar.SECOND);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200, 200);
    }
}
</code>```

So my question is how do I make both fan and clock rotate at the same time?

Here is how it looks the you run the codeenter image description here

答:
So, you're actually asking two questions:

How to animate a number of objects

How to rotate a object (as the clock doesn't need to be rotated)

Rotating

Rotating is relatively easy in 2D Graphics, with a number of possible options. I'm going to use a AffineTransform as a personal preference.

We need to add a couple of things to the ArcsPanel, we need a angle, which represents the current angle of rotation, and a delta, which represents the amount of movement on each animation pass...

```<code>public static class ArcsPanel extends JPanel {

    protected static final float DELTA = 1.0f;
    private float angle = 0;
</code>```

With this information, we can simply modify the paintComponent method to support the angle property and apply the AffineTransform

```<code>@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g.create();

    int xCenter = getWidth() / 2;
    int yCenter = getHeight() / 2;
    int radius = (int) (Math.min(getWidth(), getHeight()) * 0.4);

    g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(angle), xCenter, yCenter));

    int x = xCenter - radius;
    int y = yCenter - radius;

    g2d.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);
    g2d.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
    g2d.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
    g2d.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
    g2d.dispose();
}
</code>```

Animating a number of objects

Despite what you might think, you don't want more threads, you actually only want one.  This one thread will notify all the objects you want to be updated that they should update their animatable states.  This thread doesn't care "how" they do that, it only drives the process.  Equally, your objects don't care "how" the engine works, only that it will notify them on a regular bases.

Now, Swing is both single threaded and not thread safe. This raises a number of issues when dealing with threads.  You can't run long running or blocking operations within the context of the Event Dispatching Thread and you shouldn't update the state of the UI from outside the EDT either.

For simplicity, a Swing Timer is a perfect choice, as it waits off the EDT, but triggers it's updates in the EDT.

First, we need some way for the engine to tell other objects that they should update themselves.  Sure you can simply maintain a direct reference to the other components, but this both increases the coupling between objects, it also limits the engines re-usability.

Instead, we define a simple interface...

```<code>public interface Animatable {
    public void updateAnimatedState();
}
</code>```

All objects that want to be notified will implement this interface and can register with the engine

```<code>public class Engine {

    private List<Animatable> animatables;
    private Timer timer;

    public Engine() {
        animatables = new ArrayList<>(4);
        timer = new Timer(10, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (Animatable animatable : animatables) {
                    animatable.updateAnimatedState();
                }
            }
        });
    }

    public void add(Animatable animatable) {
        animatables.add(animatable);
    }

    public void start() {
        timer.start();
    }

    public void stop() {
        timer.stop();
    }
}
</code>```

Now, all we need to do is update the two components...

```<code>public static class ArcsPanel extends JPanel implements Animatable {
    //...
    @Override
    public void updateAnimatedState() {
        angle += DELTA;
        repaint();
    }
}

public class StillClock extends JPanel implements Animatable {
    //...

    @Override
    public void updateAnimatedState() {
        setCurrentTime();
        repaint();
    }
}
</code>```

You'll note that I've modified your code slightly so that both components now extend from JPanel, extending from JFrame is very limiting and generally discouraged.

Finally, we just need to set it all up...

```<code>public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                ArcsPanel arcPanel = new ArcsPanel();
                StillClock clockPanel = new StillClock();

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridLayout(0, 2));
                frame.add(arcPanel);
                frame.add(clockPanel);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                Engine engine = new Engine();
                engine.add(arcPanel);
                engine.add(clockPanel);
                engine.start();
            }
        });
    }
}
</code>```

Runnable example...

And because I know how confusing a bunch of out-of-context code snippets can be...

```<code>import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                ArcsPanel arcPanel = new ArcsPanel();
                StillClock clockPanel = new StillClock();

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridLayout(0, 2));
                frame.add(arcPanel);
                frame.add(clockPanel);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                Engine engine = new Engine();
                engine.add(arcPanel);
                engine.add(clockPanel);
                engine.start();
            }
        });
    }

    public class Engine {

        private List<Animatable> animatables;
        private Timer timer;

        public Engine() {
            animatables = new ArrayList<>(4);
            timer = new Timer(10, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    for (Animatable animatable : animatables) {
                        animatable.updateAnimatedState();
                    }
                }
            });
        }

        public void add(Animatable animatable) {
            animatables.add(animatable);
        }

        public void start() {
            timer.start();
        }

        public void stop() {
            timer.stop();
        }
    }

    public interface Animatable {

        public void updateAnimatedState();
    }

    public static class ArcsPanel extends JPanel implements Animatable {

        protected static final float DELTA = 1.0f;
        private float angle = 0;

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 300);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D) g.create();

            int xCenter = getWidth() / 2;
            int yCenter = getHeight() / 2;
            int radius = (int) (Math.min(getWidth(), getHeight()) * 0.4);

            g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(angle), xCenter, yCenter));

            int x = xCenter - radius;
            int y = yCenter - radius;

            g2d.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);
            g2d.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
            g2d.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
            g2d.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
            g2d.dispose();
        }

        @Override
        public void updateAnimatedState() {
            angle += DELTA;
            repaint();
        }
    }

    public class StillClock extends JPanel implements Animatable {

        private int hour;
        private int minute;
        private int second;

        public StillClock() {
            setCurrentTime();
        }

        public StillClock(int hour, int minute, int second) {
            this.hour = hour;
            this.minute = minute;
            this.second = second;
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 300);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            // Initialize clock parameters
            int clockRadius
                            = (int) (Math.min(getWidth(), getHeight()) * 0.8 * 0.5);
            int xCenter = getWidth() / 2;
            int yCenter = getHeight() / 2;

            // Draw circle
            g.setColor(Color.black);
            g.drawOval(xCenter - clockRadius, yCenter - clockRadius,
                            2 * clockRadius, 2 * clockRadius);
            g.drawString("12", xCenter - 5, yCenter - clockRadius + 12);
            g.drawString("9", xCenter - clockRadius + 3, yCenter + 5);
            g.drawString("3", xCenter + clockRadius - 10, yCenter + 3);
            g.drawString("6", xCenter - 3, yCenter + clockRadius - 3);

            // Draw second hand
            int sLength = (int) (clockRadius * 0.8);
            int xSecond = (int) (xCenter + sLength
                            * Math.sin(second * (2 * Math.PI / 60)));
            int ySecond = (int) (yCenter - sLength
                            * Math.cos(second * (2 * Math.PI / 60)));
            g.setColor(Color.red);
            g.drawLine(xCenter, yCenter, xSecond, ySecond);

            // Draw minute hand
            int mLength = (int) (clockRadius * 0.65);
            int xMinute = (int) (xCenter + mLength
                            * Math.sin(minute * (2 * Math.PI / 60)));
            int yMinute = (int) (yCenter - mLength
                            * Math.cos(minute * (2 * Math.PI / 60)));
            g.setColor(Color.blue);
            g.drawLine(xCenter, yCenter, xMinute, yMinute);

            // Draw hour hand
            int hLength = (int) (clockRadius * 0.5);
            int xHour = (int) (xCenter + hLength
                            * Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
            int yHour = (int) (yCenter - hLength
                            * Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
            g.setColor(Color.green);
            g.drawLine(xCenter, yCenter, xHour, yHour);
        }

        public void setCurrentTime() {
            // Construct a calendar for the current date and time
            Calendar calendar = new GregorianCalendar();

            // Set current hour, minute and second
            this.hour = calendar.get(Calendar.HOUR_OF_DAY);
            this.minute = calendar.get(Calendar.MINUTE);
            this.second = calendar.get(Calendar.SECOND);
        }

        @Override
        public void updateAnimatedState() {
            setCurrentTime();
            repaint();
        }
    }
}
</code>```

Body:
So I have this assignment where I have to make two objects move at the same time. I know that I should use thread class but i am not sure how to do it. My project has two files. The first one has main method and implements fan object.Here it is:

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;

    public class DrawArcs extends JFrame {
    public DrawArcs() {
        setTitle("DrawArcs");
        add(new ArcsPanel());
     }

     /** Main method */
    public static void main(String[] args) {
        DrawArcs frame = new DrawArcs();
        frame.setLocationRelativeTo(null); // Center the frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.add(new StillClock());

     }
    }

    class ArcsPanel extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        int xCenter = getWidth() / 2;
        int yCenter = getHeight() / 2;
        int radius = (int)(Math.min(getWidth(), getHeight()) * 0.4);

        int x = xCenter - radius;
        int y = yCenter - radius;

        g.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);
        g.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
        g.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
        g.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
    }
 }

My second file includes implementation of the clock class.

public class StillClock  extends JPanel {
    private int hour;
    private int minute;
    private int second;

    public StillClock() {
        setCurrentTime();
    }

    public StillClock(int hour, int minute, int second) {
        this.hour = hour;
        this.minute = minute;
        this.second = second;
    }
////there are setters and getters here
 .
 .
 .
////

    @Override /** Draw the clock */
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        // Initialize clock parameters
        int clockRadius =
                (int)(Math.min(getWidth(), getHeight()) * 0.8 * 0.5);
        int xCenter = getWidth() / 2;
        int yCenter = getHeight() / 2;

        // Draw circle
        g.setColor(Color.black);
        g.drawOval(xCenter - clockRadius, yCenter - clockRadius,
                2 * clockRadius, 2 * clockRadius);
        g.drawString("12", xCenter - 5, yCenter - clockRadius + 12);
        g.drawString("9", xCenter - clockRadius + 3, yCenter + 5);
        g.drawString("3", xCenter + clockRadius - 10, yCenter + 3);
        g.drawString("6", xCenter - 3, yCenter + clockRadius - 3);

        // Draw second hand
        int sLength = (int)(clockRadius * 0.8);
        int xSecond = (int)(xCenter + sLength *
                Math.sin(second * (2 * Math.PI / 60)));
        int ySecond = (int)(yCenter - sLength *
                Math.cos(second * (2 * Math.PI / 60)));
        g.setColor(Color.red);
        g.drawLine(xCenter, yCenter, xSecond, ySecond);

        // Draw minute hand
        int mLength = (int)(clockRadius * 0.65);
        int xMinute = (int)(xCenter + mLength *
                Math.sin(minute * (2 * Math.PI / 60)));
        int yMinute = (int)(yCenter - mLength *
                Math.cos(minute * (2 * Math.PI / 60)));
        g.setColor(Color.blue);
        g.drawLine(xCenter, yCenter, xMinute, yMinute);

        // Draw hour hand
        int hLength = (int)(clockRadius * 0.5);
        int xHour = (int)(xCenter + hLength *
                Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
        int yHour = (int)(yCenter - hLength *
                Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
        g.setColor(Color.green);
        g.drawLine(xCenter, yCenter, xHour, yHour);
    }

    public void setCurrentTime() {
        // Construct a calendar for the current date and time
        Calendar calendar = new GregorianCalendar();

        // Set current hour, minute and second
        this.hour = calendar.get(Calendar.HOUR_OF_DAY);
        this.minute = calendar.get(Calendar.MINUTE);
        this.second = calendar.get(Calendar.SECOND);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200, 200);
    }
}

So my question is how do I make both fan and clock rotate at the same time?

Here is how it looks the you run the codeenter image description here

Body:
So, you're actually asking two questions:

How to animate a number of objects

How to rotate a object (as the clock doesn't need to be rotated)

Rotating

Rotating is relatively easy in 2D Graphics, with a number of possible options. I'm going to use a AffineTransform as a personal preference.

We need to add a couple of things to the ArcsPanel, we need a angle, which represents the current angle of rotation, and a delta, which represents the amount of movement on each animation pass...

public static class ArcsPanel extends JPanel {

    protected static final float DELTA = 1.0f;
    private float angle = 0;

With this information, we can simply modify the paintComponent method to support the angle property and apply the AffineTransform

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g.create();

    int xCenter = getWidth() / 2;
    int yCenter = getHeight() / 2;
    int radius = (int) (Math.min(getWidth(), getHeight()) * 0.4);

    g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(angle), xCenter, yCenter));

    int x = xCenter - radius;
    int y = yCenter - radius;

    g2d.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);
    g2d.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
    g2d.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
    g2d.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
    g2d.dispose();
}

Animating a number of objects

Despite what you might think, you don't want more threads, you actually only want one.  This one thread will notify all the objects you want to be updated that they should update their animatable states.  This thread doesn't care "how" they do that, it only drives the process.  Equally, your objects don't care "how" the engine works, only that it will notify them on a regular bases.

Now, Swing is both single threaded and not thread safe. This raises a number of issues when dealing with threads.  You can't run long running or blocking operations within the context of the Event Dispatching Thread and you shouldn't update the state of the UI from outside the EDT either.

For simplicity, a Swing Timer is a perfect choice, as it waits off the EDT, but triggers it's updates in the EDT.

First, we need some way for the engine to tell other objects that they should update themselves.  Sure you can simply maintain a direct reference to the other components, but this both increases the coupling between objects, it also limits the engines re-usability.

Instead, we define a simple interface...

public interface Animatable {
    public void updateAnimatedState();
}

All objects that want to be notified will implement this interface and can register with the engine

public class Engine {

    private List<Animatable> animatables;
    private Timer timer;

    public Engine() {
        animatables = new ArrayList<>(4);
        timer = new Timer(10, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (Animatable animatable : animatables) {
                    animatable.updateAnimatedState();
                }
            }
        });
    }

    public void add(Animatable animatable) {
        animatables.add(animatable);
    }

    public void start() {
        timer.start();
    }

    public void stop() {
        timer.stop();
    }
}

Now, all we need to do is update the two components...

public static class ArcsPanel extends JPanel implements Animatable {
    //...
    @Override
    public void updateAnimatedState() {
        angle += DELTA;
        repaint();
    }
}

public class StillClock extends JPanel implements Animatable {
    //...

    @Override
    public void updateAnimatedState() {
        setCurrentTime();
        repaint();
    }
}

You'll note that I've modified your code slightly so that both components now extend from JPanel, extending from JFrame is very limiting and generally discouraged.

Finally, we just need to set it all up...

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                ArcsPanel arcPanel = new ArcsPanel();
                StillClock clockPanel = new StillClock();

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridLayout(0, 2));
                frame.add(arcPanel);
                frame.add(clockPanel);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                Engine engine = new Engine();
                engine.add(arcPanel);
                engine.add(clockPanel);
                engine.start();
            }
        });
    }
}

Runnable example...

And because I know how confusing a bunch of out-of-context code snippets can be...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                ArcsPanel arcPanel = new ArcsPanel();
                StillClock clockPanel = new StillClock();

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridLayout(0, 2));
                frame.add(arcPanel);
                frame.add(clockPanel);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                Engine engine = new Engine();
                engine.add(arcPanel);
                engine.add(clockPanel);
                engine.start();
            }
        });
    }

    public class Engine {

        private List<Animatable> animatables;
        private Timer timer;

        public Engine() {
            animatables = new ArrayList<>(4);
            timer = new Timer(10, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    for (Animatable animatable : animatables) {
                        animatable.updateAnimatedState();
                    }
                }
            });
        }

        public void add(Animatable animatable) {
            animatables.add(animatable);
        }

        public void start() {
            timer.start();
        }

        public void stop() {
            timer.stop();
        }
    }

    public interface Animatable {

        public void updateAnimatedState();
    }

    public static class ArcsPanel extends JPanel implements Animatable {

        protected static final float DELTA = 1.0f;
        private float angle = 0;

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 300);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D) g.create();

            int xCenter = getWidth() / 2;
            int yCenter = getHeight() / 2;
            int radius = (int) (Math.min(getWidth(), getHeight()) * 0.4);

            g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(angle), xCenter, yCenter));

            int x = xCenter - radius;
            int y = yCenter - radius;

            g2d.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);
            g2d.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
            g2d.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
            g2d.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
            g2d.dispose();
        }

        @Override
        public void updateAnimatedState() {
            angle += DELTA;
            repaint();
        }
    }

    public class StillClock extends JPanel implements Animatable {

        private int hour;
        private int minute;
        private int second;

        public StillClock() {
            setCurrentTime();
        }

        public StillClock(int hour, int minute, int second) {
            this.hour = hour;
            this.minute = minute;
            this.second = second;
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 300);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            // Initialize clock parameters
            int clockRadius
                            = (int) (Math.min(getWidth(), getHeight()) * 0.8 * 0.5);
            int xCenter = getWidth() / 2;
            int yCenter = getHeight() / 2;

            // Draw circle
            g.setColor(Color.black);
            g.drawOval(xCenter - clockRadius, yCenter - clockRadius,
                            2 * clockRadius, 2 * clockRadius);
            g.drawString("12", xCenter - 5, yCenter - clockRadius + 12);
            g.drawString("9", xCenter - clockRadius + 3, yCenter + 5);
            g.drawString("3", xCenter + clockRadius - 10, yCenter + 3);
            g.drawString("6", xCenter - 3, yCenter + clockRadius - 3);

            // Draw second hand
            int sLength = (int) (clockRadius * 0.8);
            int xSecond = (int) (xCenter + sLength
                            * Math.sin(second * (2 * Math.PI / 60)));
            int ySecond = (int) (yCenter - sLength
                            * Math.cos(second * (2 * Math.PI / 60)));
            g.setColor(Color.red);
            g.drawLine(xCenter, yCenter, xSecond, ySecond);

            // Draw minute hand
            int mLength = (int) (clockRadius * 0.65);
            int xMinute = (int) (xCenter + mLength
                            * Math.sin(minute * (2 * Math.PI / 60)));
            int yMinute = (int) (yCenter - mLength
                            * Math.cos(minute * (2 * Math.PI / 60)));
            g.setColor(Color.blue);
            g.drawLine(xCenter, yCenter, xMinute, yMinute);

            // Draw hour hand
            int hLength = (int) (clockRadius * 0.5);
            int xHour = (int) (xCenter + hLength
                            * Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
            int yHour = (int) (yCenter - hLength
                            * Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
            g.setColor(Color.green);
            g.drawLine(xCenter, yCenter, xHour, yHour);
        }

        public void setCurrentTime() {
            // Construct a calendar for the current date and time
            Calendar calendar = new GregorianCalendar();

            // Set current hour, minute and second
            this.hour = calendar.get(Calendar.HOUR_OF_DAY);
            this.minute = calendar.get(Calendar.MINUTE);
            this.second = calendar.get(Calendar.SECOND);
        }

        @Override
        public void updateAnimatedState() {
            setCurrentTime();
            repaint();
        }
    }
}


来源: stackexchange

问:
Login failed for user 'IIS APPPOOL\Classic .NET AppPool'
I just added my website to IIS. After much troubleshooting I was able to make it run with the Classic .NET App Pool.

But on the page which requires connecting with the database, I am getting the error "Login failed for the user 'IIS APPPOOL\Class .NET AppPool'

Please suggest a workaround.

答: Are you using integrated security in the DB connection string? if so, you either need to change the connection string to specify a username or password. or change the asp.net settings in IIS to enable impersonation, this will mean the web app is running as another specified user (you would need to ensure the alternate user has access to the database otherwise you will have the same problem!)</p>

ContentLicense: CC BY-SA 3.0


问:
relative and absolute html path?
The code snippet in html format is showing as below.
there are three requirements listed below for reference as well.</p>

```<code>   <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Images and Links - Fast Broccoli!</title>
    </head>
    <body>
        <div class="content">
            <h1>Fast Broccoli! - About Us</h1>
            <!--
                Use images and links to build an "About Us" page for Fast Broccoli!,
                the world's first one-hour organic produce delivery service.

            You'll need:
            1. A main image with source: https://upload.wikimedia.org/wikipedia/commons/0/03/Broccoli_and_cross_section_edit.jpg
                  and alt description: Fast Broccoli!'s Logo
            2. A link to the relative path: index.html
                with the text: Return Home
            3. A second link to the absolute path: https://shop.fastbrocolli.com
                The link should target a new browser window.
                The link should contain an image
                    with source: images/cabbage.png
                   -->
        </div>
    </body>
    </html>
</code>```

答:
This strangely looks like a school project. I could just give you the solution to your assignment, but I believe it would be better if you learn it.
Hope you enjoy!

Image Tag

Here's an example img tag from W3Schools:

```<code> <img src="smiley.gif" alt="Smiley face">
</code>```

This is pretty simple. The source is smiley.gif and the alt description is Smiley face. Now do you know how to make your own image tag? Otherwise, click the link above for more details.

Links

Relative

A relative link is, well, relative. Where it goes depends on where the current URL.

A relative link is anything that does not begin  http://, https://, file:///`, etc.

In the most basic sense, it's the current URL + the relative path. (Less simple, it's telling the browser it's in the same folder as the current page).

Example: If I added a link on this page that looks like:

```<code><a href="hi.html">Click me</a>

It would go to:
https://stackoverflow.com/questions/47361572/relative-and-absolute-html-path/hi.html

Because:
https://stackoverflow.com/questions/47361572/relative-and-absolute-html-path + hi.html
</code>```

If it begins with a forward slash (/), it will take the domain of the site and add to it. (Less simple, it's telling the browser the file is in the root directory of the site).

Example: If I added a link on this page that looks like:

```<code><a href="/hi.html">Click me</a>

It would go to:
https://stackoverflow.com/hi.html

Because:
https://stackoverflow.com + hi.html
</code>```

Absolute

An absolute path is absolute. It doesn't add to the end, but is an entirely new domain.

Example: If I added a link on this page that looks like:

```<code><a href="http://example.com/">Click me</a>

It would go to:
http://example.com/

Because it begins with http://
</code>```

Notes

In all the examples, the text of the links was "Click me".

More info on file paths.

More info on the target attribute. (Allows you to "target a new browser window.")

Title: relative and absolute html path?

Body:
The code snippet in html format is showing as below.
there are three requirements listed below for reference as well.

   <!DOCTYPE html>

        <title>Images and Links - Fast Broccoli!</title>

Fast Broccoli! - About Us

Body:
This strangely looks like a school project. I could just give you the solution to your assignment, but I believe it would be better if you learn it.
Hope you enjoy!

Image Tag

Here's an example img tag from W3Schools:

 <img src="smiley.gif" alt="Smiley face">

This is pretty simple. The source is smiley.gif and the alt description is Smiley face. Now do you know how to make your own image tag? Otherwise, click the link above for more details.

Links

Relative

A relative link is, well, relative. Where it goes depends on where the current URL.

A relative link is anything that does not begin  http://, https://, file:///`, etc.

In the most basic sense, it's the current URL + the relative path. (Less simple, it's telling the browser it's in the same folder as the current page).

Example: If I added a link on this page that looks like:

<a href="hi.html">Click me</a>

It would go to:
https://stackoverflow.com/questions/47361572/relative-and-absolute-html-path/hi.html

Because:
https://stackoverflow.com/questions/47361572/relative-and-absolute-html-path + hi.html

If it begins with a forward slash (/), it will take the domain of the site and add to it. (Less simple, it's telling the browser the file is in the root directory of the site).

Example: If I added a link on this page that looks like:

<a href="/hi.html">Click me</a>

It would go to:
https://stackoverflow.com/hi.html

Because:
https://stackoverflow.com + hi.html

Absolute

An absolute path is absolute. It doesn't add to the end, but is an entirely new domain.

Example: If I added a link on this page that looks like:

<a href="http://example.com/">Click me</a>

It would go to:
http://example.com/

Because it begins with http://

Notes

In all the examples, the text of the links was "Click me".

More info on file paths.

More info on the target attribute. (Allows you to "target a new browser window.")


问:
How to let user end program and shift list
Im trying to make an encryption program </p>

```<code>def intro():
    msg = input("Enter the message you wish to encrypt: ")
    return msg

def shift(msg):
    alpha = ['a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    rotate = int(input("The level of the encryption?: "))
    text = ""
    for ch in msg:
        if ch == " " or ch == ".":
            pass
        elif msg == "$":
            print("nah")
        else:
            index = alpha.index(ch)
            newindex = index + rotate
            new= alpha[newindex]
            text += new
    return text

def start():
    msg = intro()
    text = shift(msg)
    print("Your encryptions is: " + text)

start()
</code>```

<p>I can't figure out a way to loop the list without getting an index out of range error. For example, if you put "z" it will shift to an  "a". I also need for my program to loop till user inputs to end it.  I just started coding in python a few months ago so any help will be appreciated!beginner </p>

答:
All you need to do is add this line

```<code>newindex %= len(alpha)
</code>```

Detailed Change (with context)

```<code>index = alpha.index(ch)
newindex = index + rotate
new= alpha[newindex]
text += new
</code>```

to

```<code>index = alpha.index(ch)
newindex = index + rotate
newindex %= len(alpha) # <--- this is the new line
new= alpha[newindex]
text += new
</code>```

This will automatically make the new index loop so it never goes past the end!

Working example

```<code>>> Enter the message you wish to encrypt: 'xyz'
>> The level of the encryption?: 2
>> Your encryptions is: zab
</code>```

Body:
Im trying to make an encryption program

def intro():
    msg = input("Enter the message you wish to encrypt: ")
    return msg

def shift(msg):
    alpha = ['a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    rotate = int(input("The level of the encryption?: "))
    text = ""
    for ch in msg:
        if ch == " " or ch == ".":
            pass
        elif msg == "$":
            print("nah")
        else:
            index = alpha.index(ch)
            newindex = index + rotate
            new= alpha[newindex]
            text += new
    return text

def start():
    msg = intro()
    text = shift(msg)
    print("Your encryptions is: " + text)

start()

I can't figure out a way to loop the list without getting an index out of range error. For example, if you put "z" it will shift to an  "a". I also need for my program to loop till user inputs to end it.  I just started coding in python a few months ago so any help will be appreciated!beginner

Body:
All you need to do is add this line

newindex %= len(alpha)

Detailed Change (with context)

index = alpha.index(ch)
newindex = index + rotate
new= alpha[newindex]
text += new

to

index = alpha.index(ch)
newindex = index + rotate
newindex %= len(alpha) # <--- this is the new line
new= alpha[newindex]
text += new

This will automatically make the new index loop so it never goes past the end!

Working example

>> Enter the message you wish to encrypt: 'xyz'
>> The level of the encryption?: 2
>> Your encryptions is: zab


问:
Firebase Database not committing online data blocking Listeners
I am using the Firebase Database service to synchronize users data.
I enabled the offline compatibilities and the problem is that after some months the of usage, the users data is not committed into the online database apparently because the users phone systems are blocking the application internet connection.

In some cases, i managed to guide the users enable the "unlimited data usage" option, but isn't working for everyone.

In my case, the problem is that the listener:

```<code>void onDataChange(DataSnapshot var1);
</code>```

from ValueEventListener, is not fired when a huge amount of data is stored offline and not committed, and is blocking all the behaviors.

I don't have online storage limitation because I have the Blaze plan ( pay for consuming ).

The transactions are not committed too, and fires "The transaction was overridden by a subsequent set" with the error code -9.

The Connection detector provided by Firebase is always printing "not connected "

I also tried to alternate goOffline() with goOnline() but nothing happens.

I don't understand why the phone could block my app from synchronizing and let apps like Facebook and Youtube to consume a large amount of internet data.

This behavior is only happening on the Android devices, there is no problem on iOS phones that are using the same Firebase Database.

Doesn't work either with 4g, WI-FI nor with VPN ( used Opera VPN ).

Update 1:

The logs contains at launch for ~10 times:

```<code>11-13 21:12:28.477 15765 15856 D PersistentConnection: pc_0 - Scheduling connection attempt
11-13 21:12:28.477 15765 15856 D ConnectionRetryHelper: Scheduling retry in 26091ms
11-13 21:12:54.597 15765 15856 D PersistentConnection: pc_0 - Trying to fetch auth token
11-13 21:12:55.747 15765 15856 D PersistentConnection: pc_0 - Error fetching token: An internal error has occurred. [
TOKEN_EXPIRED ]
</code>```

When I'm trying to insert new data:

```<code>RepoOperation: Aborting transactions for path: [the path]
</code>```

答:
After a long investigation, I found out that the token was not refreshing automatically.

First of all, check if the current user is logged in with FirebaseAuth.AuthStateListener

To check if I need to refresh the token

1) Check if the application has internet connection:

```<code>    public static boolean isOnline(Context context)
    {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        return networkInfo != null && networkInfo.isConnectedOrConnecting();
    }
</code>```

2) Then I check if the database is connected to:
Detecting Connection State

If the app has an internet connection and the database is not connected then I try to refresh the token:

```<code>try
{
    user.getIdToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>()
    {
        @Override
        public void onComplete(@NonNull Task<GetTokenResult> task)
        {
            if (task.isSuccessful())
            {
                //succcess
            } else
            {
                //need login again
            }
        }
    });
}catch(Exception e)
{
    //need login again
}
</code>```

If there is an exception or the completion task fails then I try to login again the user. In most of the cases will be a transparent login, so will not be displayed to the user, because will use the credentials already stored by the sdk itself.

I think this is a hack because affects only a few users so it's an sdk bug.

Body:
I am using the Firebase Database service to synchronize users data.
I enabled the offline compatibilities and the problem is that after some months the of usage, the users data is not committed into the online database apparently because the users phone systems are blocking the application internet connection.

In some cases, i managed to guide the users enable the "unlimited data usage" option, but isn't working for everyone.

In my case, the problem is that the listener:

void onDataChange(DataSnapshot var1);

from ValueEventListener, is not fired when a huge amount of data is stored offline and not committed, and is blocking all the behaviors.

I don't have online storage limitation because I have the Blaze plan ( pay for consuming ).

The transactions are not committed too, and fires "The transaction was overridden by a subsequent set" with the error code -9.

The Connection detector provided by Firebase is always printing "not connected "

I also tried to alternate goOffline() with goOnline() but nothing happens.

I don't understand why the phone could block my app from synchronizing and let apps like Facebook and Youtube to consume a large amount of internet data.

This behavior is only happening on the Android devices, there is no problem on iOS phones that are using the same Firebase Database.

Doesn't work either with 4g, WI-FI nor with VPN ( used Opera VPN ).

Update 1:

The logs contains at launch for ~10 times:

11-13 21:12:28.477 15765 15856 D PersistentConnection: pc_0 - Scheduling connection attempt
11-13 21:12:28.477 15765 15856 D ConnectionRetryHelper: Scheduling retry in 26091ms
11-13 21:12:54.597 15765 15856 D PersistentConnection: pc_0 - Trying to fetch auth token
11-13 21:12:55.747 15765 15856 D PersistentConnection: pc_0 - Error fetching token: An internal error has occurred. [
TOKEN_EXPIRED ]

When I'm trying to insert new data:

RepoOperation: Aborting transactions for path: [the path]

Body:
After a long investigation, I found out that the token was not refreshing automatically.

First of all, check if the current user is logged in with FirebaseAuth.AuthStateListener

To check if I need to refresh the token

1) Check if the application has internet connection:

    public static boolean isOnline(Context context)
    {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        return networkInfo != null && networkInfo.isConnectedOrConnecting();
    }

2) Then I check if the database is connected to:
Detecting Connection State

If the app has an internet connection and the database is not connected then I try to refresh the token:

try
{
    user.getIdToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>()
    {
        @Override
        public void onComplete(@NonNull Task<GetTokenResult> task)
        {
            if (task.isSuccessful())
            {
                //succcess
            } else
            {
                //need login again
            }
        }
    });
}catch(Exception e)
{
    //need login again
}

If there is an exception or the completion task fails then I try to login again the user. In most of the cases will be a transparent login, so will not be displayed to the user, because will use the credentials already stored by the sdk itself.

I think this is a hack because affects only a few users so it's an sdk bug.


问:
Get sum of array and callback a function inside another function
I am trying to solve a problem where I have to get the sum of an array using the .reduce() method inside a function and instead of returning the sum, I need to invoke the callback and pass the sum there.

I am pretty sure I am using the .reduce() correctly but I keep getting 'undefined' and, for the life of me, I cannot figure out how to get invoke a function inside a function.

Any help/explanations would be greatly appreciated!

Question: Sum up all of the integers in the numbers array.
Instead of returning the sum invoke cb and pass in the sum there.

My code:

```<code>function sumArray(numbers, cb) {
  //code here

  numbers.reduce(function(sum, currentValue) {
    return sum + currentValue;
  }, 0);

  cb([1, 2, 3, 4, 5], result);

}

function addTwo(num) {
  const result =  num + 2;
}
</code>```

答:
Well, I guess you must be trying to do something like that.

You must to store the reduce return.

You must return the callback function.

To have access to the internal callback you must return the callback.

function sumArray(numbers, cb) {
  //code here
  let result = numbers.reduce(function(sum, currentValue) {
    return sum + currentValue;
  }, 0);

  return cb([1, 2, 3, 4, 5], result);

}

function sumTwo(arr, num) {
 return  Number(num + 2);
}

console.log(sumArray([1, 2, 3, 4, 5], sumTwo));```

Body:
I am trying to solve a problem where I have to get the sum of an array using the .reduce() method inside a function and instead of returning the sum, I need to invoke the callback and pass the sum there.

I am pretty sure I am using the .reduce() correctly but I keep getting 'undefined' and, for the life of me, I cannot figure out how to get invoke a function inside a function.

Any help/explanations would be greatly appreciated!

Question: Sum up all of the integers in the numbers array.
Instead of returning the sum invoke cb and pass in the sum there.

My code:

function sumArray(numbers, cb) {
  //code here

  numbers.reduce(function(sum, currentValue) {
    return sum + currentValue;
  }, 0);

  cb([1, 2, 3, 4, 5], result);

}

function addTwo(num) {
  const result =  num + 2;
}


问:
c programming read input error checking
Is there a way to make this error checking any better? Or is there something I am forgetting? I am expecting an integer then string. I added the suggestions to the code.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>

int main(void) {
    // your code goes here
    char line[150] = {0};
    int sscanf_counter = 0;
    int num = 0;
    char string[150] = {0};
    char dummy;

    while(fgets(line, sizeof line, stdin))
    {
        printf("line is %s\n", line);
        sscanf_counter = sscanf(line, "%d %s %c", &num, string, &dummy);
        printf ("sscanf_counter: %d\n", sscanf_counter);
        if (sscanf_counter == 2 && isalpha(string[0]))
        {
            printf ("Good value: %d\n", num);
            printf ("string: <%s>\n", string);
        }
        else
        {
            printf ("BAD VALUE: %d \n", num);
            printf ("string: <%s>\n", string);
        }
        memset(line, 0, sizeof line);
    }

    printf("Does this print? \n");

    return 0;
}
</code>```

I didn't want 222 to be converted to a string so I added a simple isalpha() check to my code. I want an actual number for my first value and actual alphabet characters not numbers converted to a string for the second value.

Output with small tweak:

```<code>aaa aaa
line is aaa aaa

sscanf_counter: 0
BAD VALUE: 0
string: <>
111 222
line is 111 222

sscanf_counter: 2
BAD VALUE: 111
string: <222>
111 aaa
line is 111 aaa

sscanf_counter: 2
Good value: 111
string: <aaa>
</code>```

答:
Is there a way to make this error checking any better?

"%d" is not specified on overflow.  Stronger error checking can be provided with strtol().

"%d %s" does not detect extraneous extra input.

To deal with extra input and still use sscanf(), see below.  If sscanf_counter == 3, extra non-white-space input detected.

```<code>char dummy;
sscanf_counter = sscanf(line, "%d %s %c", &num, string, &dummy);
</code>```

The test if (sscanf_counter == ...)  should happen before using the variables.

```<code>  printf ("sscanf_counter: %d\n", sscanf_counter);
  if (sscanf_counter >= 1) printf ("num: %d\n", num);
  if (sscanf_counter >= 2) printf ("string: %s\n", string);
</code>```

Tip: when printing a string, consider printable sententials to help detect leading/trailing white-space issues.  (Even though these are not expected with "%s".)

```<code>// printf ("string: %s\n", string);
printf ("string: <%s>\n", string);
</code>```

OT: Rather than code magic numbers, use code that adapts

```<code>// memset(line, 0, 150);
memset(line, 0, sizeof line);

// while(fgets(line, 150, stdin) != NULL)
while (fgets(line, sizeof line, stdin))
</code>```

Title: c programming read input error checking

Body:
Is there a way to make this error checking any better? Or is there something I am forgetting? I am expecting an integer then string. I added the suggestions to the code.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>

int main(void) {
    // your code goes here
    char line[150] = {0};
    int sscanf_counter = 0;
    int num = 0;
    char string[150] = {0};
    char dummy;

    while(fgets(line, sizeof line, stdin))
    {
        printf("line is %s\n", line);
        sscanf_counter = sscanf(line, "%d %s %c", &num, string, &dummy);
        printf ("sscanf_counter: %d\n", sscanf_counter);
        if (sscanf_counter == 2 && isalpha(string[0]))
        {
            printf ("Good value: %d\n", num);
            printf ("string: <%s>\n", string);
        }
        else
        {
            printf ("BAD VALUE: %d \n", num);
            printf ("string: <%s>\n", string);
        }
        memset(line, 0, sizeof line);
    }

    printf("Does this print? \n");

    return 0;
}

I didn't want 222 to be converted to a string so I added a simple isalpha() check to my code. I want an actual number for my first value and actual alphabet characters not numbers converted to a string for the second value.

Output with small tweak:

aaa aaa
line is aaa aaa

sscanf_counter: 0
BAD VALUE: 0
string: <>
111 222
line is 111 222

sscanf_counter: 2
BAD VALUE: 111
string: <222>
111 aaa
line is 111 aaa

sscanf_counter: 2
Good value: 111
string: <aaa>

Body:
Is there a way to make this error checking any better?

"%d" is not specified on overflow.  Stronger error checking can be provided with strtol().

"%d %s" does not detect extraneous extra input.

To deal with extra input and still use sscanf(), see below.  If sscanf_counter == 3, extra non-white-space input detected.

char dummy;
sscanf_counter = sscanf(line, "%d %s %c", &num, string, &dummy);

The test if (sscanf_counter == ...)  should happen before using the variables.

  printf ("sscanf_counter: %d\n", sscanf_counter);
  if (sscanf_counter >= 1) printf ("num: %d\n", num);
  if (sscanf_counter >= 2) printf ("string: %s\n", string);

Tip: when printing a string, consider printable sententials to help detect leading/trailing white-space issues.  (Even though these are not expected with "%s".)

// printf ("string: %s\n", string);
printf ("string: <%s>\n", string);

OT: Rather than code magic numbers, use code that adapts

// memset(line, 0, 150);
memset(line, 0, sizeof line);

// while(fgets(line, 150, stdin) != NULL)
while (fgets(line, sizeof line, stdin))


问:
in python, how to connect points with smooth line in plotting?
I am trying to plot points + smooth line using spline. But the line "overshoots" some points, e.g in following codes, over the point 0.85.

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import spline

x=np.array([0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9, 2])
y=np.array([0.57,0.85,0.66,0.84,0.59,0.55,0.61,0.76,0.54,0.55,0.48])

x_new = np.linspace(x.min(), x.max(),500)
y_smooth = spline(x, y, x_new)

plt.plot (x_new,y_smooth)
plt.scatter (x, y)
</code>```

how do I fix it?

答:
You might try the using interp1d in scipy.interpolate:

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d

x=np.array([0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9, 2])
y=np.array([0.57,0.85,0.66,0.84,0.59,0.55,0.61,0.76,0.54,0.55,0.48])

x_new = np.linspace(x.min(), x.max(),500)

f = interp1d(x, y, kind='quadratic')
y_smooth=f(x_new)

plt.plot (x_new,y_smooth)
plt.scatter (x, y)
</code>```

which yields:

some other options for the kind parameter are in the docs:

kind : str or int, optional Specifies the kind of interpolation as a string (‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’ where ‘zero’, ‘slinear’, ‘quadratic’ and ‘cubic’ refer to a spline interpolation of zeroth, first, second or third order) or as an integer specifying the order of the spline interpolator to use. Default is ‘linear’.

Body:
I am trying to plot points + smooth line using spline. But the line "overshoots" some points, e.g in following codes, over the point 0.85.

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import spline

x=np.array([0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9, 2])
y=np.array([0.57,0.85,0.66,0.84,0.59,0.55,0.61,0.76,0.54,0.55,0.48])

x_new = np.linspace(x.min(), x.max(),500)
y_smooth = spline(x, y, x_new)

plt.plot (x_new,y_smooth)
plt.scatter (x, y)

how do I fix it?

Body:
You might try the using interp1d in scipy.interpolate:

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d

x=np.array([0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9, 2])
y=np.array([0.57,0.85,0.66,0.84,0.59,0.55,0.61,0.76,0.54,0.55,0.48])

x_new = np.linspace(x.min(), x.max(),500)

f = interp1d(x, y, kind='quadratic')
y_smooth=f(x_new)

plt.plot (x_new,y_smooth)
plt.scatter (x, y)

which yields:

some other options for the kind parameter are in the docs:

kind : str or int, optional Specifies the kind of interpolation as a string (‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’ where ‘zero’, ‘slinear’, ‘quadratic’ and ‘cubic’ refer to a spline interpolation of zeroth, first, second or third order) or as an integer specifying the order of the spline interpolator to use. Default is ‘linear’.


问:
How to call two method one after another?
I'm building a simple Android Application. I want to parse JSON. I have everything working using Button. But I want call it without using Button. It need to be get the JSON first from url and then Parse it. I have function getJson() and parseJSON(). First I want getJSON to be called and after 5 second parseJSON(). here is my code:

```<code>Runnable[] methods = new Runnable[]{
            new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SheduleActivity.this, "This is gettin JSON", Toast.LENGTH_LONG).show();
                    getJSON();

                }
            },
            new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SheduleActivity.this, "This is Parsing JSON", Toast.LENGTH_LONG).show();
                    parseJSON();

                }
            }

    };

    for(Runnable r : methods)
        //r.run();
       service.submit(r);
   service.shutdown();
    while (!service.isTerminated()) {}
    Toast.makeText(SheduleActivity.this,"Finished all threads", Toast.LENGTH_LONG).show();
</code>```

Everytime I run my app only getJSON() method calls and stops. Any suggetions?

答: I think you need to use AsyncTask. put getJson() in doInBackground block and parseJSON() on onPostExecute block. hope this help. </p>

Body:
I'm building a simple Android Application. I want to parse JSON. I have everything working using Button. But I want call it without using Button. It need to be get the JSON first from url and then Parse it. I have function getJson() and parseJSON(). First I want getJSON to be called and after 5 second parseJSON(). here is my code:

Runnable[] methods = new Runnable[]{
            new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SheduleActivity.this, "This is gettin JSON", Toast.LENGTH_LONG).show();
                    getJSON();

                }
            },
            new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SheduleActivity.this, "This is Parsing JSON", Toast.LENGTH_LONG).show();
                    parseJSON();

                }
            }

    };

    for(Runnable r : methods)
        //r.run();
       service.submit(r);
   service.shutdown();
    while (!service.isTerminated()) {}
    Toast.makeText(SheduleActivity.this,"Finished all threads", Toast.LENGTH_LONG).show();

Everytime I run my app only getJSON() method calls and stops. Any suggetions?


问:
SQLite column error: table XXX has no column named YYY
I've looked at the following, among others and have found nothing that matches my problem (as far as I can tell):

android.database.sqlite.SQLiteException: table X has no column named Y: , while compiling: INSERT INTO

Android : Table has no column named "variable name" MySql Database error

Error compiling insert into: No column named ID

Android SQLite issue - table ... has no column named

https://sqlite.org/foreignkeys.html

I'm getting the following SQLite error:

```<code>SQLiteDatabase: Error inserting zipCode=23456 address2= city=state address1=123 petName=qwerty phoneNumber=null vetName=zaw emailAddress=
                                             android.database.sqlite.SQLiteException: table vets has no column named petName (code 1): , while compiling: INSERT INTO vets (zipCode,address2,city,address1,petName,phoneNumber,vetName,emailAddress) VALUES (?,?,?,?,?,?,?,?)
</code>```

I have a feeling that it has to do with the foreign key in VetTable but my research hasn't helped me with understanding what's going on.

VetTable is defined as follows:

```<code>public class VetTable {
    public static final String TABLE_VETS = "vets";
    public static final String VET_ID = "vetId";
    public static final String PET_ID = "petId";
    public static final String VET_NAME = "vetName";
    public static final String ADDRESS1 = "address1";
    public static final String ADDRESS2 = "address2";
    public static final String CITY = "city";
    public static final String STATE = "state";
    public static final String ZIP_CODE = "zipCode";
    public static final String PHONE_NUMBER = "phoneNumber";
    public static final String EMAIL_ADDRESS = "emailAddress";

public static final String SQL_CREATE =
        "CREATE TABLE " + TABLE_VETS + "(" +
                VET_ID + " INTEGER PRIMARY KEY UNIQUE, " +
                PET_ID + " INTEGER, " +
                VET_NAME + " TEXT, " +
                ADDRESS1 + " TEXT, " +
                ADDRESS2 + " TEXT, " +
                CITY + " TEXT, " +
                STATE + " TEXT, " +
                ZIP_CODE + " TEXT, " +
                PHONE_NUMBER + " TEXT, " +
                EMAIL_ADDRESS + " TEXT, " +
                "FOREIGN KEY(" + PET_ID + ") " +
                "REFERENCES pets(petId));";

    public static final String SQL_DELETE =
            "DROP TABLE" + TABLE_VETS;
}
</code>```

The relevant code from DBHelper code is as follows:

```<code>public void addVetInfo(String name, String address1, String address2, String city, String state, String zip, String phone, String email){
    try {
        db = this.getWritableDatabase();
        values.put(VET_NAME, name);
        values.put(ADDRESS1, address1);
        values.put(ADDRESS2, address2);
        values.put(CITY, city);
        values.put(CITY, state);
        values.put(ZIP_CODE, zip);
        values.put(PHONE_NUMBER, phone);
        values.put(EMAIL_ADDRESS, email);
        db.insert(TABLE_VETS, null, values);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
</code>```

As can be seen petName is not part of nor has ever been included in VetTable, nor is it part of the argument list in addVetInfo. So, what is SQLite doing that makes it think that petName should be a column in VetTable?

答:
Looks like your values variable already have that value inside the object, check this :</p>

```<code>public void addVetInfo(String name, String address1, String address2, String city, String state, String zip, String phone, String email){
    try {
        db = this.getWritableDatabase();
        //INITIALIZE YOUR VARIABLE VALUES HERE
        ContentValues values = new ContentValues();

    //if(name == "Enter vet name") name = null;
    values.put(VET_NAME, name);
    //if(address1 == "Enter address 1" || address1 == " ") address1 = null;
    values.put(ADDRESS1, address1);
    //if(address2 == "Enter address 2") address2 = null;
    values.put(ADDRESS2, address2);
    //if(city == "Enter city") city = null;
    values.put(CITY, city);
    //if(state == "Enter state") state = null;
    values.put(CITY, state);
    //if(zip == "Enter zip") zip = null;
    values.put(ZIP_CODE, zip);
    //if(phone == "Enter phone number") phone = null;
    values.put(PHONE_NUMBER, phone);
    //if(email == "Enter email address") email = null;
    values.put(EMAIL_ADDRESS, email);
    db.insert(TABLE_VETS, null, values);
} catch (SQLException e) {
    e.printStackTrace();
}
}
</code>```

Body:
I've looked at the following, among others and have found nothing that matches my problem (as far as I can tell):

android.database.sqlite.SQLiteException: table X has no column named Y: , while compiling: INSERT INTO

Android : Table has no column named "variable name" MySql Database error

Error compiling insert into: No column named ID

Android SQLite issue - table ... has no column named

https://sqlite.org/foreignkeys.html

I'm getting the following SQLite error:

SQLiteDatabase: Error inserting zipCode=23456 address2= city=state address1=123 petName=qwerty phoneNumber=null vetName=zaw emailAddress=
                                             android.database.sqlite.SQLiteException: table vets has no column named petName (code 1): , while compiling: INSERT INTO vets (zipCode,address2,city,address1,petName,phoneNumber,vetName,emailAddress) VALUES (?,?,?,?,?,?,?,?)

I have a feeling that it has to do with the foreign key in VetTable but my research hasn't helped me with understanding what's going on.

VetTable is defined as follows:

public class VetTable {
    public static final String TABLE_VETS = "vets";
    public static final String VET_ID = "vetId";
    public static final String PET_ID = "petId";
    public static final String VET_NAME = "vetName";
    public static final String ADDRESS1 = "address1";
    public static final String ADDRESS2 = "address2";
    public static final String CITY = "city";
    public static final String STATE = "state";
    public static final String ZIP_CODE = "zipCode";
    public static final String PHONE_NUMBER = "phoneNumber";
    public static final String EMAIL_ADDRESS = "emailAddress";

public static final String SQL_CREATE =
        "CREATE TABLE " + TABLE_VETS + "(" +
                VET_ID + " INTEGER PRIMARY KEY UNIQUE, " +
                PET_ID + " INTEGER, " +
                VET_NAME + " TEXT, " +
                ADDRESS1 + " TEXT, " +
                ADDRESS2 + " TEXT, " +
                CITY + " TEXT, " +
                STATE + " TEXT, " +
                ZIP_CODE + " TEXT, " +
                PHONE_NUMBER + " TEXT, " +
                EMAIL_ADDRESS + " TEXT, " +
                "FOREIGN KEY(" + PET_ID + ") " +
                "REFERENCES pets(petId));";

    public static final String SQL_DELETE =
            "DROP TABLE" + TABLE_VETS;
}

The relevant code from DBHelper code is as follows:

public void addVetInfo(String name, String address1, String address2, String city, String state, String zip, String phone, String email){
    try {
        db = this.getWritableDatabase();
        values.put(VET_NAME, name);
        values.put(ADDRESS1, address1);
        values.put(ADDRESS2, address2);
        values.put(CITY, city);
        values.put(CITY, state);
        values.put(ZIP_CODE, zip);
        values.put(PHONE_NUMBER, phone);
        values.put(EMAIL_ADDRESS, email);
        db.insert(TABLE_VETS, null, values);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

As can be seen petName is not part of nor has ever been included in VetTable, nor is it part of the argument list in addVetInfo. So, what is SQLite doing that makes it think that petName should be a column in VetTable?

Body:
Looks like your values variable already have that value inside the object, check this :

public void addVetInfo(String name, String address1, String address2, String city, String state, String zip, String phone, String email){
    try {
        db = this.getWritableDatabase();
        //INITIALIZE YOUR VARIABLE VALUES HERE
        ContentValues values = new ContentValues();

    //if(name == "Enter vet name") name = null;
    values.put(VET_NAME, name);
    //if(address1 == "Enter address 1" || address1 == " ") address1 = null;
    values.put(ADDRESS1, address1);
    //if(address2 == "Enter address 2") address2 = null;
    values.put(ADDRESS2, address2);
    //if(city == "Enter city") city = null;
    values.put(CITY, city);
    //if(state == "Enter state") state = null;
    values.put(CITY, state);
    //if(zip == "Enter zip") zip = null;
    values.put(ZIP_CODE, zip);
    //if(phone == "Enter phone number") phone = null;
    values.put(PHONE_NUMBER, phone);
    //if(email == "Enter email address") email = null;
    values.put(EMAIL_ADDRESS, email);
    db.insert(TABLE_VETS, null, values);
} catch (SQLException e) {
    e.printStackTrace();
}
}


问:
RSU not receiving WSMs in Veins 4.5
I am using the Veins 4.5 framework for a semester project. I am trying to observe the behavior of different functions in the sample codes given. For some reason, the RSU's onWSM function never gets called. I added a message (using the EV command) to print to the log whenever this function is called but the message is never logged. I tried the same thing in the vehicle's onWSM function and it works. I do not understand what the problem is here.

I searched Google and apparently other people have posted similar questions on different forums but have not received an answer (e.g. http://java.wekeepcoding.com/article/10429913/RSU+receiving+message+but+onWSM+method+not+executing+in+veins+4.5). There are answers regarding the same issue for a different version of Veins but the functions are now different in the version I am using (e.g. Allow a RSU receive messages in Veins).

Any help would be appreciated.

答: One thing that comes to mind is to look into the handleLowerMsg function inside BaseWaveApplLayer to see whether or not onWSM is actually getting called on arrival of a WSM for the RSU.</p>

Title: RSU not receiving WSMs in Veins 4.5


问:
JSON response not being shown inside the cell
I’m creating a Tableview and trying to include in the cell one information that I receive through a JSON from an API.
The information (JSON) is being received very well and recorded correctly inside the variable.
However, what I could find is that as the information is received with a small “delay” is not being set as the cell’s label text at the cell creation moment, which is being set with the default variable content.
I guess the solution would be to update the label at the moment I parse the JSON content, right? How do I do this? (Update a cell’s label after it is already created)
Any other insight/ solution is greatly appreciated. </p>

```<code>class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, AddStock {

    let operacoesAcoes = ListaOperacoes()
    var todasAsOperacoes : [Operacao] = []

    @IBOutlet weak var acoesTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        acoesTableView.delegate = self
        acoesTableView.dataSource = self
        acoesTableView.register(UINib(nibName: "StandardStockListCell", bundle: nil), forCellReuseIdentifier: "standardCell")
        operacoesAcoes.consolidaAcoes()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return operacoesAcoes.carteiraAcoes.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "standardCell", for: indexPath) as! StandardStockListCell
        let informacaoCompletaAcao = operacoesAcoes.carteiraAcoes[indexPath.row]

        cell.codigoTextField.text = informacaoCompletaAcao.codigoAcao
        cell.nomeTextField.text = informacaoCompletaAcao.nomeAcao
        cell.quantidadeTotal.text = String(informacaoCompletaAcao.quantidadeTotal)
        cell.precoMedioLabel.text = String(format: "%.2f", informacaoCompletaAcao.precoMedio)

       //
       // This is the part of the code that should set one label with a value returned from "buscaCotacao" but it does not work
       // because at the time the cell is displayed it is still not updated from JSON information:
       // Note: the buscaCotacao func is working fine

        cell.precoAtualLabel.text = buscaCotacao(ativo: informacaoCompletaAcao.codigoAcao)

        return cell
    }
</code>```

答:
You need to reload the table view on the main thread after receiving and parsing the JSON.

self.acoesTableView.reloadData()

Body:
I’m creating a Tableview and trying to include in the cell one information that I receive through a JSON from an API.
The information (JSON) is being received very well and recorded correctly inside the variable.
However, what I could find is that as the information is received with a small “delay” is not being set as the cell’s label text at the cell creation moment, which is being set with the default variable content.
I guess the solution would be to update the label at the moment I parse the JSON content, right? How do I do this? (Update a cell’s label after it is already created)
Any other insight/ solution is greatly appreciated.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, AddStock {

    let operacoesAcoes = ListaOperacoes()
    var todasAsOperacoes : [Operacao] = []

    @IBOutlet weak var acoesTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        acoesTableView.delegate = self
        acoesTableView.dataSource = self
        acoesTableView.register(UINib(nibName: "StandardStockListCell", bundle: nil), forCellReuseIdentifier: "standardCell")
        operacoesAcoes.consolidaAcoes()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return operacoesAcoes.carteiraAcoes.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "standardCell", for: indexPath) as! StandardStockListCell
        let informacaoCompletaAcao = operacoesAcoes.carteiraAcoes[indexPath.row]

        cell.codigoTextField.text = informacaoCompletaAcao.codigoAcao
        cell.nomeTextField.text = informacaoCompletaAcao.nomeAcao
        cell.quantidadeTotal.text = String(informacaoCompletaAcao.quantidadeTotal)
        cell.precoMedioLabel.text = String(format: "%.2f", informacaoCompletaAcao.precoMedio)

       //
       // This is the part of the code that should set one label with a value returned from "buscaCotacao" but it does not work
       // because at the time the cell is displayed it is still not updated from JSON information:
       // Note: the buscaCotacao func is working fine

        cell.precoAtualLabel.text = buscaCotacao(ativo: informacaoCompletaAcao.codigoAcao)

        return cell
    }


问:
Android add item to global context menu
When you long press on something in Android, a context menu comes up. I want to add something to this context menu for all TextViews in the system.

For example, the system does this with Copy and Paste. I would want to add my own, and have it appear in every application.

答: Push the Share button (tree of three dots) within selection menu. Then you should select your own app. Does't work for input field content, unfortunately. </p>

OwnerDisplayName: Isaac Waller

ContentLicense: CC BY-SA 2.5

Title: Android add item to global context menu


问:
Enterprise Edition Controller events not firing if Full Page Cache is enabled
So on one of our recent launches we had a lot of events that we were observer such as controller_action_predispatch. Once the site went live we started noticing that our observers were never getting called for those. After a little investigation one of our developers found this block of code in Mage_Core_Model_App around line 292

```<code>if ($this->_cache->processRequest()) {
            $this->getResponse()->sendResponse();
        } else {
            $this->_initModules();
            $this->loadAreaPart(Mage_Core_Model_App_Area::AREA_GLOBAL, Mage_Core_Model_App_Area::PART_EVENTS);

            if ($this->_config->isLocalConfigLoaded()) {
                $this->_initCurrentStore($scopeCode, $scopeType);
                $this->_initRequest();
                Mage_Core_Model_Resource_Setup::applyAllDataUpdates();
            }

            $this->getFrontController()->dispatch();
        }
</code>```

As you can see if $this->_cache->processRequest() that is true which it is when full page cache is enabled you never get to the dispatch. The developer did find http_response_send_before which gets call either way but it seems to me like this is a bug or you should never ever use those controller dispatch events for anything if you have full page caching enabled. Any thoughts?

答:
Given the nature of the full page caching, I'd call this "works as intended". While it can be a little strange not to have some events firing, they had to pick a line and this one makes sense to me, especially since the controller is never really dispatched.

You should use those controller dispatch events for anything that affects the page (as it still needs to be generated), but if you are using it for tracking and such, no it would not be appropriate.

Body:
So on one of our recent launches we had a lot of events that we were observer such as controller_action_predispatch. Once the site went live we started noticing that our observers were never getting called for those. After a little investigation one of our developers found this block of code in Mage_Core_Model_App around line 292

if ($this->_cache->processRequest()) {
            $this->getResponse()->sendResponse();
        } else {
            $this->_initModules();
            $this->loadAreaPart(Mage_Core_Model_App_Area::AREA_GLOBAL, Mage_Core_Model_App_Area::PART_EVENTS);

            if ($this->_config->isLocalConfigLoaded()) {
                $this->_initCurrentStore($scopeCode, $scopeType);
                $this->_initRequest();
                Mage_Core_Model_Resource_Setup::applyAllDataUpdates();
            }

            $this->getFrontController()->dispatch();
        }

As you can see if $this->_cache->processRequest() that is true which it is when full page cache is enabled you never get to the dispatch. The developer did find http_response_send_before which gets call either way but it seems to me like this is a bug or you should never ever use those controller dispatch events for anything if you have full page caching enabled. Any thoughts?


问:
ruby on rails - add end_time upon record creation
I'm trying to have a record with ends_at column which is suppose to have the created_at value with 5 minutes added to it for instance:

```<code>Class Post < ApplicationRecord
  after_create :set_end_time

  private
    def set_end_time
      self.ends_at = self.created_at + 5.minutes
    end
end
</code>```

this saves the ends_at column as a null in the database

答:
You forgot to save the record</p>

```<code>def set_end_time
  self.ends_at = self.created_at + 5.minutes
  save
end
</code>```

Body:
I'm trying to have a record with ends_at column which is suppose to have the created_at value with 5 minutes added to it for instance:

Class Post < ApplicationRecord
  after_create :set_end_time

  private
    def set_end_time
      self.ends_at = self.created_at + 5.minutes
    end
end

this saves the ends_at column as a null in the database

Body:
You forgot to save the record

def set_end_time
  self.ends_at = self.created_at + 5.minutes
  save
end


问:
Ask dialog to delete an item from listview
I have this code that work perfect to delete an item from listview and it disappear. I want to show dialog to ask if the user want to delete an item. </p>

```<code>public void ShowdatainlstView() {
    Boodschappenlst.clear();
    final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            Boodschappenlst);
    lstviewProducten.setAdapter(arrayAdapter);
    lstviewProducten.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Boodschappenlst.remove(position);
            arrayAdapter.notifyDataSetChanged();
        }
    });
}
</code>```

答:
```<code>        new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Are you sure?")
            .setMessage("do you want to delete this?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Log.i("Button Tapped","Yes");
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Log.i("Button Tapped","No");
                }
            })
            .show();
</code>```

Body:
I have this code that work perfect to delete an item from listview and it disappear. I want to show dialog to ask if the user want to delete an item.

public void ShowdatainlstView() {
    Boodschappenlst.clear();
    final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            Boodschappenlst);
    lstviewProducten.setAdapter(arrayAdapter);
    lstviewProducten.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Boodschappenlst.remove(position);
            arrayAdapter.notifyDataSetChanged();
        }
    });
}


问:
Using Bootstrap 4 with Grails
I'm using Grails for a web project for a CSE class in college. I've noticed many of the other groups doing this project are using Bootstrap 4 for the web design (I'm in the only group using Grails). I looked into Bootstrap 4 and I really love the way it looks. Personally I don't like the way Grails looks with standard HTML. I was wondering if there is a way that I can use Bootstrap 4 with Grails. For example in standard HTML I can have a button and forms that will submit data to a controller and some action will happen, it doesn't seem to work the same way with Grails.

Would anyone know if I can integrate Bootstrap 4 with Grails and if so how I can do it?

答: Bootstrap has nothing to do with Grails. Just include the dependencies and use the bootstrap classes in your GSP just like you'd do in a plain HTML page. You can use the <g:form> tag to post to your Grails controller.

Title: Using Bootstrap 4 with Grails


问:
How to reset state of redux store while using react-navigation when react-navigation reset does not immediately unmount screens from stack?
I'm trying to do auth sign-out with react-native and am experiencing an issue where I want to reset the state of the redux store but, because I am using react-navigation, I have a bunch of redux-connected screens that are still mounted that re-render when the state tree is reset to it's initialState causing a bunch of exception errors. I tried to unmount them on sign-out with a react-navigation reset which redirects the user to the signup/login screen but I have no way of knowing when these screens are actually unmounted in order to call the RESET_STATE action. Initially I was dispatching the action via saga.

sagas/logout.js

import { LOGOUT, RESET_STATE } from 'Actions/user';

// clear localstorage once user logs out.
const clearData = function* clearData(action) {
  AsyncStorage.removeItem('user');

  yield put(
    NavigationActions.reset({
      index: 0,
      actions: [
        NavigationActions.navigate({ routeName: 'SignedOut' })
      ],
    })
  );
  // causes re-renders, screens still mounted
  yield put({type: RESET_STATE});
}

export default function* logoutSaga () {
  yield all([
    yield takeEvery(LOGOUT, clearData),
  ]);
}```
</div>
</div>
</p>

<p>I also tried to reset once user reaches the SignedOut screen in it's componentDidMount cycle but unfortunately the screens unmount at some point well after componentDidMount is triggered:</p>

<p><strong>screens/SignedOut.js</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { resetState } from 'Actions/user';
import ActionButton from 'Components/FormElements/ActionButton';

class SignedOut extends Component {
  // screens are still mounted, causing screens from
  // previous screens to throw exception errors
  componentDidMount() {
    this.props.dispatch(resetState());
  }

  componentWillUnmount() {
    // never called
  }

  handleSignup = () => {
    this.props.navigation.navigate('Signup');
  }

  handleLogin = () => {
    this.props.navigation.navigate('Login');
  }

  render() {
    return(
      <Container>
        <ActionButton
          text="Sign Up"
          handleButtonPress={this.handleSignup}
        />
        <ActionButton
          text="Log In"
          handleButtonPress={this.handleLogin}
        />
      </Container>
    );
  }
}

export default connect()(SignedOut);</code>```

My question is, can anyone think of a way to reset state of redux store after all of my screens have finally unmounted by the react-navigation reset action?

答: The issue is you're using navigate to navigate to the login/signup screen which leaves all your other components mounted, you should probably use back or reset to unmount all the components and show the login screen.</p>

Body:
I'm trying to do auth sign-out with react-native and am experiencing an issue where I want to reset the state of the redux store but, because I am using react-navigation, I have a bunch of redux-connected screens that are still mounted that re-render when the state tree is reset to it's initialState causing a bunch of exception errors. I tried to unmount them on sign-out with a react-navigation reset which redirects the user to the signup/login screen but I have no way of knowing when these screens are actually unmounted in order to call the RESET_STATE action. Initially I was dispatching the action via saga.

sagas/logout.js

import { LOGOUT, RESET_STATE } from 'Actions/user';

// clear localstorage once user logs out.
const clearData = function* clearData(action) {
  AsyncStorage.removeItem('user');

  yield put(
    NavigationActions.reset({
      index: 0,
      actions: [
        NavigationActions.navigate({ routeName: 'SignedOut' })
      ],
    })
  );
  // causes re-renders, screens still mounted
  yield put({type: RESET_STATE});
}

export default function* logoutSaga () {
  yield all([
    yield takeEvery(LOGOUT, clearData),
  ]);
}

I also tried to reset once user reaches the SignedOut screen in it's componentDidMount cycle but unfortunately the screens unmount at some point well after componentDidMount is triggered:

screens/SignedOut.js

import { resetState } from 'Actions/user';
import ActionButton from 'Components/FormElements/ActionButton';

class SignedOut extends Component {
  // screens are still mounted, causing screens from
  // previous screens to throw exception errors
  componentDidMount() {
    this.props.dispatch(resetState());
  }

  componentWillUnmount() {
    // never called
  }

  handleSignup = () => {
    this.props.navigation.navigate('Signup');
  }

  handleLogin = () => {
    this.props.navigation.navigate('Login');
  }

  render() {
    return(
      <Container>
        <ActionButton
          text="Sign Up"
          handleButtonPress={this.handleSignup}
        />
        <ActionButton
          text="Log In"
          handleButtonPress={this.handleLogin}
        />
      </Container>
    );
  }
}

export default connect()(SignedOut);

My question is, can anyone think of a way to reset state of redux store after all of my screens have finally unmounted by the react-navigation reset action?


问:
Why we need toJSON when comparing to two components equality?
I write component which convert text with \n line break to html paragraph

Text.js

```<code>const Text = props => ((
  <div>
    { props.paragraph.split('\n').map((line, index) => {
      if (line.length === 0) return;
      return <p key={index}>{ line }</p>;
    })}
  </div>
)
);
</code>```

When I want to compare to Components, there is error if I call it without toJSON to rendered Component. (Even though result is the same when I check with toMatchSnapshot())

Text.spec.js

```<code>it('ignores \\n at last', () => {
  const paragraphA = 'aa\nbbb\n';
  const paragraphB = 'aa\nbbb';
  const cA = renderer.create(<Text paragraph={paragraphA} />);
  const cB = renderer.create(<Text paragraph={paragraphB} />);
  expect(cA).toEqual(cB); // NG
  expect(cA.toJSON()).toEqual(cB.toJSON()); // OK
});
</code>```

jest tells Difference as below

Compared values serialize to the same structure.
  Printing internal object structure without calling toJSON instead.

I google it but could not find any clue about toJSON

Why do we need toJSON here?

what toJSON do generally?

Where can I find reference about toJSON?

Env

react: 16.1
jest-cli": "^21.2.1"

Thanks in advance!!

答:
From the fine manual:

toJSON behavior

If an object being stringified has a property named toJSON whose value is a function, then the toJSON method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON method when called will be serialized.

Examples:

//without toJSON
const a = {
  b: 1
};
console.log(
  JSON.stringify(a)
);```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//with toJSON
const a = {
  b: 1,
  toJSON: () => ({
    c: 100
  })
};
console.log(
  JSON.stringify(a)
);</code>```

I think you should compare cA.toJSON() instead of raw function cA.toJSON.

Why it's necessary? When you compare objects (including arrays and functions), they are compared by referrence instead of value. React component has complex structure (e.g. references to another components as properties), so trying to stringify it instead of its .toJSON() (which returns safe object) would throw an error. For example, it wouldn't work if you have custom function for parsing JSON which don't checks for .toJSON method.

Body:
I write component which convert text with \n line break to html paragraph

Text.js

const Text = props => ((

    { props.paragraph.split('\n').map((line, index) => {
      if (line.length === 0) return;
      return
{ line }
;
    })}

)
);

When I want to compare to Components, there is error if I call it without toJSON to rendered Component. (Even though result is the same when I check with toMatchSnapshot())

Text.spec.js

it('ignores \\n at last', () => {
  const paragraphA = 'aa\nbbb\n';
  const paragraphB = 'aa\nbbb';
  const cA = renderer.create(<Text paragraph={paragraphA} />);
  const cB = renderer.create(<Text paragraph={paragraphB} />);
  expect(cA).toEqual(cB); // NG
  expect(cA.toJSON()).toEqual(cB.toJSON()); // OK
});

jest tells Difference as below

Compared values serialize to the same structure.
  Printing internal object structure without calling toJSON instead.

I google it but could not find any clue about toJSON

Why do we need toJSON here?

what toJSON do generally?

Where can I find reference about toJSON?

Env

react: 16.1
jest-cli": "^21.2.1"

Thanks in advance!!

Body:
From the fine manual:

toJSON behavior

If an object being stringified has a property named toJSON whose value is a function, then the toJSON method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON method when called will be serialized.

Examples:

//without toJSON
const a = {
  b: 1
};
console.log(
  JSON.stringify(a)
);

//with toJSON
const a = {
  b: 1,
  toJSON: () => ({
    c: 100
  })
};
console.log(
  JSON.stringify(a)
);

I think you should compare cA.toJSON() instead of raw function cA.toJSON.

Why it's necessary? When you compare objects (including arrays and functions), they are compared by referrence instead of value. React component has complex structure (e.g. references to another components as properties), so trying to stringify it instead of its .toJSON() (which returns safe object) would throw an error. For example, it wouldn't work if you have custom function for parsing JSON which don't checks for .toJSON method.


问:
PHP count of occurrences of characters of a string within another string
Let's say I have two strings.

```<code>$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';
</code>```

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!

答:
I'd do something like:

split the string to chars (str_split), and then

use  array_count_values to get an array of characters with the respective number of occurrences.

Code:

```<code>$needle = 'AGUXYZ';
$string = "asdasdadas asdadas asd asdsd";
$array_chars = str_split($string);
$value_count = array_count_values($array_chars);
for ($i = 0; $i < count($needle); $i++)
    echo $needle[$i]. " is occur " .
         ($value_count[$needle[$i]] ? $value_count[$needle[$i]] : '0')." times";
</code>```

Body:
Let's say I have two strings.

$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!

Body:
I'd do something like:

split the string to chars (str_split), and then

use  array_count_values to get an array of characters with the respective number of occurrences.

Code:

$needle = 'AGUXYZ';
$string = "asdasdadas asdadas asd asdsd";
$array_chars = str_split($string);
$value_count = array_count_values($array_chars);
for ($i = 0; $i < count($needle); $i++)
    echo $needle[$i]. " is occur " .
         ($value_count[$needle[$i]] ? $value_count[$needle[$i]] : '0')." times";

ContentLicense: CC BY-SA 4.0