/**
 * (C) Copyright IBM Corporation 2017, 2018.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.wasdev.wlp.common.arquillian.objects;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import net.wasdev.wlp.common.arquillian.util.ArquillianConfigurationException;

public class LibertyProperty {

    public interface LibertyPropertyI {
    }

    /**
     * Converts Map<String, String> to Map<LibertyPropertyI, String>. Validates
     * each key property name.
     *
     * @param arquillianProperties
     * @return a map of converted arquillianProperties
     * @throws ArquillianConfigurationException
     *             if a property name is invalid.
     */
    public static Map<LibertyPropertyI, String> getArquillianProperties(Map<String, String> arquillianProperties,
            Class<?> cls) throws ArquillianConfigurationException {
        Map<LibertyPropertyI, String> props = new HashMap<LibertyPropertyI, String>();
        if (arquillianProperties != null && !arquillianProperties.isEmpty()) {
            for (Entry<String, String> entry : arquillianProperties.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (key != null && value != null) {
                    LibertyPropertyI p = getArquillianProperty(key, cls);
                    props.put(p, value);
                }
            }
        }
        return props;
    }

    /**
     * Check that the given key exists in ArquillianProperties
     *
     * @param key
     * @return true if so, fail the build otherwise
     * @throws MojoFailureException
     */
    private static LibertyPropertyI getArquillianProperty(String key, Class<?> cls)
            throws ArquillianConfigurationException {
        try {
            if (cls == LibertyManagedObject.LibertyManagedProperty.class) {
                return LibertyManagedObject.LibertyManagedProperty.valueOf(key);
            } else if (cls == LibertyRemoteObject.LibertyRemoteProperty.class) {
                return LibertyRemoteObject.LibertyRemoteProperty.valueOf(key);
            }
        } catch (IllegalArgumentException e) {
            throw new ArquillianConfigurationException(
                    "Property \"" + key + "\" in arquillianProperties does not exist. You probably have a typo.");
        }
        throw new ArquillianConfigurationException("This should never happen.");
    }

    protected static void write(StringBuilder xml, File arquillianXml) throws IOException {
        // First create the parent folder of arquillian.xml if it doesn't exist
        // (this happens in gradle if you don't specify any resources in
        // src/test/resources)
        File arquillianXmlFolder = arquillianXml.getParentFile();
        if (!arquillianXmlFolder.exists()) {
            arquillianXmlFolder.mkdirs();
        }

        // Now that we are guaranteed that the folder exists, we can write
        FileWriter writer = new FileWriter(arquillianXml);
        writer.write(xml.toString());
        writer.close();
    }

}


package org.teachingextensions.approvals.lite.reporters;

import java.awt.GraphicsEnvironment;

import org.teachingextensions.approvals.lite.util.TestUtils;

public class ImageWebReporter implements EnvironmentAwareReporter {
    public static final ImageWebReporter INSTANCE = new ImageWebReporter();

    @Override
    public void report(String received, String approved) throws Exception {
        String text = "

approved	received

  %s
 to approve : copy clipboard to command window
 %s";
        String moveText = ClipboardReporter.getAcceptApprovalText(received, approved);
        text = String.format(text, approved, received, received, moveText);
        TestUtils.displayHtml(text);
    }

    /**
     * We assume any environment that is not headless will have a web browser to display the image in a web page.
     */
    @Override
    public boolean isWorkingInThisEnvironment(String forFile) {
        return !GraphicsEnvironment.isHeadless()
                && GenericDiffReporter.isFileExtensionValid(forFile, GenericDiffReporter.IMAGE_FILE_EXTENSIONS);
    }
}


package org.teachingextensions.logo.utils.EventUtils;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import org.teachingextensions.approvals.lite.util.NumberUtils;

/**
 *

 * Fancy MessageBox is a pop up window that you can change!

 * Use it to collect input from the user, or to display a message for the user to read.

 */
public class FancyMessageBox
{
  private static FancyMessageBoxInstance fancyMessageBox = new FancyMessageBoxInstance();
  /**
   * Prints a request for a numerical input to the window.

   * Example:
   * {@code  int cookies = FancyMessageBox.askForNumericalInput("How many cookies would you like?", "Cookies");}
   *
   * @param message
   *            the text in the FancyMessageBox
   * @param title
   *            the title of the FancyMessageBox
   * @return the user input as a number
   */
  public static int askForNumericalInput(String message, String title)
  {
    return fancyMessageBox.askForNumericalInput(message, title);
  }
  /**
   * Prints a request for a text input to the window.

   * Example:
   * {@code  String name = FancyMessageBox.askForTextInput("What is your nickname?", "Nicknames");}
   *
   * @param message
   *            the text in the FancyMessageBox
    * @param title
   *            the title of the FancyMessageBox
   * @return the user input as a string
   */
  public static String askForTextInput(String message, String title)
  {
    return fancyMessageBox.askForTextInput(message, title);
  }
  /**
   * Prints the message to the window.

   * Example: {@code  FancyMessageBox.showMessage("Girl programmers rule!","Just the Facts");}
   *
   * @param message
   *            the text in the FancyMessageBox
   * @param title
   *            the title of the FancyMessageBox
   * @param icon
   *            a file and path that has an image for the MessageBox
   */
  public static void showMesage(String message, String title, ImageIcon icon)
  {
    fancyMessageBox.showMessage(message, title, icon);
  }
  public static class FancyMessageBoxInstance
  {
    public static void mock(FancyMessageBoxInstance messageBoxMock)
    {
      fancyMessageBox = messageBoxMock;
    }
    public int askForNumericalInput(String message, String title)
    {
      String input = askForTextInput(message, title);
      return NumberUtils.load(input, 0);
    }
    public String askForTextInput(String message, String title)
    {
      return JOptionPane.showInputDialog(null, message, title, -1);
    }
    public void showMessage(String message, String title, ImageIcon icon)
    {
      JOptionPane.showMessageDialog(null, message, title, -1, icon);
    }
  }
}


package org.teachingextensions.logo.utils.MVCUtils;

import java.lang.reflect.Field;
import java.util.List;

import org.teachingextensions.approvals.lite.util.ObjectUtils;
import org.teachingextensions.approvals.lite.util.io.FileUtils;
import org.teachingextensions.approvals.lite.util.lambda.Function1;
import org.teachingextensions.approvals.lite.util.lambda.Query;

/**
 *
 * Parses a data object for display, using a template
 */
public class Parser
{
  /**
   * Parses a template with a data object to create a string
   *
   *
Example:
{@code
   * Words data = new Words();
   * data.action = "Shake";
   * data.weapon = "speare";
   * String greeting = Parser.parse("Captain {action}{weapon}!!!", data);
   * }

   *
   * Captain Shakespeare!!!
   *
   * @param text
   *          The template with the fields from the data object surrounded in {curlyBraces}
   * @param data
   *          an object whose fields will be merged with the template during parsing
   * @return the completed string
   */
  public static String parse(String text, Object data)
  {
    return parse(text, "{", "}", data);
  }
  public static String parse(String text, String startCharacter, String endCharacter, Object data)
  {
    StringBuilder sb = new StringBuilder();
    String temp = text;
    int start = temp.indexOf(startCharacter);
    while (start > 0)
    {
      int end = temp.indexOf(endCharacter, start);
      sb.append(temp.substring(0, start));
      String key = temp.substring(start + startCharacter.length(), end);
      sb.append(getValue(key, data));
      temp = temp.substring(end + endCharacter.length());
      start = temp.indexOf(startCharacter);
    }
    sb.append(temp);
    return sb.toString();
  }
  private static String getValue(final String piece, Object data)
  {
    try
    {
      Field[] declaredFields = data.getClass().getDeclaredFields();
      List<Field> f = Query.where(declaredFields, new Function1<Field, Boolean>()
      {
        @Override
        public Boolean call(Field i)
        {
          return i.getName().equals(piece);
        }
      });
      f.get(0).setAccessible(true);
      return "" + f.get(0).get(data);
    }
    catch (Exception e)
    {
      return piece;
    }
  }
  /**
   * Parses a file
   *
Example: {@code parser.parseRtfFile(filename,data)}

   *
   * @param fileName A filename for the new file, built from the template view.rtf
   * @param data A data object to put into the template fields.
   * @return the completed template
   */
  public static String parseRtfFile(String fileName, Object data)
  {
    try
    {
      String text = FileUtils.readFromClassPath(data.getClass(), fileName);
      return parse(text, "\\{", "\\}", data);
    }
    catch (Exception e)
    {
      throw ObjectUtils.throwAsError(e);
    }
  }
}


package org.teachingextensions.logo.utils.LineAndShapeUtils;

import org.teachingextensions.WindowUtils.ProgramWindow;
import org.teachingextensions.logo.utils.ColorUtils.PenColors;

import javax.swing.*;
import java.awt.*;

/**
 *
 * The Circle allows you to draw circles on the window
 */
public class Circle implements Paintable
{
  private final int   radius;
  private final Color mainColor;
  private int         x;
  private int         y;
  private int         percentTransparent;
  public Circle(int radius, Color color)
  {
    this.radius = radius;
    this.mainColor = color;
  }
  /**
   * Sets the center the circle
   *
Example: {@code  circle.setCenter(8,10)}

   *
   * @param x
   *          The x value
   * @param y
   *          The y value
   */
  public void setCenter(int x, int y)
  {
    this.x = x;
    this.y = y;
  }
  public int getRadius()
  {
    return this.radius;
  }
  /**
   * Adds a circle to the window
   *
Example: {@code  circle.addTo(panel)}

   *
   * @param panel
   *          the ProgramWindow or panel
   */
  public void addTo(ProgramWindow panel)
  {
    panel.getCanvas().add(this);
  }
  /**
   * Paints a circle
   *
Example: {@code  circle.paint(g,caller)}

   *
   * @param g
   *          the graphics object
   * @param caller
   *          the Program Window or panel
   */
  @Override
  public void paint(Graphics2D g, JPanel caller)
  {
    Color color2 = PenColors.getTransparentVersion(mainColor, percentTransparent);
    g.setColor(color2);
    g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
  }
  /**
   * Sets the transparency of the circle
   *
Example: {@code  circle.setTransparency(80)}

   *
   * @param percentTransparent
   *          The percentage of transparency of the circle
   */
  public void setTransparency(int percentTransparent)
  {
    this.percentTransparent = percentTransparent;
  }
  public void removeFrom(ProgramWindow panel)
  {
    panel.remove(this);
  }
  public int getX()
  {
    return this.x;
  }
  public int getY()
  {
    return this.y;
  }
}


package org.teachingextensions.logo;

import java.awt.Color;

import org.teachingextensions.WindowUtils.TurtleWindow;
import org.teachingextensions.logo.Turtle.Animals;
import org.teachingextensions.logo.utils.TortoiseUtils;
import org.teachingextensions.logo.utils.ColorUtils.PenColors;
import org.teachingextensions.logo.utils.LineAndShapeUtils.Text;
import org.teachingextensions.logo.utils.PizzaUtils.Pizza;
import org.teachingextensions.logo.utils.PizzaUtils.Topping;
import org.teachingextensions.virtualproctor.VirtualProctor;

/**
 *
 * The Tortoise allows you to draw lines and shapes by moving it around on the window
 */
public class Tortoise
{
  private Topping topping;
  /**
   * Displays the Tortoise
   *
Example: {@code  Tortoise.show()}

   */
  public static void show()
  {
    turtle().show();
  }
  /**
   * Gets the name for the tortoise
   *
Example: {@code String name =  Tortoise.getName("Anita Borg");}

   *
   * @return the name for the Tortoise
   */
  public static String getName()
  {
    return turtle().getName();
  }
  /**
   * Sets the name for the tortoise
   *
Example: {@code  Tortoise.setName("Ada Lovelace")}

   *
   * @param name
   *          The name for the Tortoise
   */
  public static void setName(String name)
  {
    turtle().setName(name);
  }
  /**
   * Gets the speed that the tortoise moves
   *
Example: {@code int speed =  Tortoise.getSpeed(8);}

   *
   * @return the speed the Tortoise is currently set to
   */
  public static int getSpeed()
  {
    return turtle().getSpeed();
  }
  /**
   * Sets the speed the tortoise moves
   *
Example: {@code  Tortoise.setSpeed(8)}

   *
   * @param speed
   *          The speed from 1 (slowest) to 10 (fastest)
   */
  public static void setSpeed(int speed)
  {
    turtle().setSpeed(speed);
  }
  /**
   * Moves the Tortoise Forward the number of pixels specified.

   *
Example: {@code Tortoise.move(72)}

   *
   * @param lengthInPixels
   *          The number of pixels to move. Negative numbers will move the
   *          Tortoise backwards.
   */
  public static void move(Number lengthInPixels)
  {
    turtle().move(lengthInPixels);
  }
  /**
   * Turns the Tortoise to the right (clockwise) the degrees specified.

   *
Example: {@code Tortoise.turn(90)}

   *
   * @param degreesToTheRight
   *          The degrees to turn. Negative numbers will move the Tortoise to
   *          the left (counter-clockwise)
   */
  public static void turn(Number degreesToTheRight)
  {
    turtle().turn(degreesToTheRight.doubleValue());
  }
  /**
   * Gives you access to the window the
   * Tortoise is moving on so you can do things like change it's color.

   * Example: {@code  TurtlePanel panel = Tortoise.getBackgroundWindow()}
   * @return the (program) window that the Tortoise is moving on
   */
  public static TurtleWindow getBackgroundWindow()
  {
    return turtle().getBackgroundWindow();
  }
  /**
   * Gets the current width of the pen drawn by the Tortoise.

   *
Example: {@code  width = Tortoise.getPenWidth()}

   *
   * @return the width of the pen stroke
   */
  public static int getPenWidth()
  {
    return turtle().getPenWidth();
  }
  /**
   * Sets the width of the pen drawn by the Tortoise.

   *
Example: {@code  Tortoise.setPenWidth(2)}

   *
   * @param width
   *          the width of the pen stroke
   */
  public static void setPenWidth(Number width)
  {
    turtle().setPenWidth(width.intValue());
  }
  /**
   * Gets the current color of the pen drawn by the Tortoise.

   *
Example: {@code  pen = Tortoise.getPenColor()}

   *
   * @return the color of the pen stroke
   */
  public static Color getPenColor()
  {
    return turtle().getPenColor();
  }
  /**
   * Sets the color of the line drawn by the Tortoise.

   *
Example: {@code  Tortoise.setPenColor(PenColors.Reds.Red)}

   *
   * @param color
   *          the color of the line drawn
   * @see PenColors
   */
  public static void setPenColor(Color color)
  {
    turtle().setPenColor(color);
  }
  /**
   * Gets the current position of the Tortoise on the y axis.

   * (0,0) is the top left of the screen

   *
Example: {@code  y = Tortoise.getY()}

   *
   * @return y the position in pixels of the Tortoise on the Y axis
   */
  public static int getY()
  {
    return turtle().getY();
  }
  /**
   * Sets the position of the Tortoise on the y axis.

   * (0,0) is the top left of the screen

   *
Example: {@code  Tortoise.setY(30);}

   *
   * @param y
   *          the position in pixels of the Tortoise on the Y axis
   */
  public static void setY(int y)
  {
    turtle().setY(y);
  }
  /**
   * Gets the current position of the Tortoise on the x axis.

   * (0,0) is the top left of the screen

   *
Example: {@code  x = Tortoise.getX()}

   *
   * @return x the position in pixels of the Tortoise on the X axis
   */
  public static int getX()
  {
    return turtle().getX();
  }
  /**
   * Sets the position of the Tortoise on the x axis.

   * (0,0) is the top left of the screen

   *
Example: {@code  Tortoise.setX(30);}

   *
   * @param x
   *          the position in pixels of the Tortoise on the X axis
   */
  public static void setX(int x)
  {
    turtle().setX(x);
  }
  /**
   * Gets the current heading of the Tortoise.

   * 0 degrees is due north.

   * 90 degrees is due east.

   *
Example: {@code  angle = Tortoise.getAngleInDegrees()}

   *
   * @return the angle in degrees of the Tortoise
   */
  public static double getAngle()
  {
    return turtle().getAngleInDegrees();
  }
  /**
   * Sets the angle the Tortoise is facing.

   * 0 is straight up (like 'North')

   *
Example: {@code  Tortoise.setAngle(42);}

   *
   * @param angle
   *          the angle in degrees
   */
  public static void setAngle(int angle)
  {
    turtle().setAngleInDegrees(angle);
  }
  /**
   * Changes the type of animal you are using.

   *
Example: {@code  Tortoise.setAnimal(Animals.Spider);}

   *
   * @param animal the animal you want to use
   * @see Animals
   */
  public static void setAnimal(Animals animal)
  {
    turtle().setAnimal(animal);
  }
  /**
   * Blows up your turtle!

   *
Example: {@code  Tortoise.explode(Animals.ExplodedTurtle);}

   *
   * @see Animals
   */
  public static void explode()
  {
    turtle().setAnimal(Animals.ExplodedTurtle);
  }
  /**
   * Makes it so the tortoise will not draw a line of color out of its butt.

   * Example: {@code  Tortoise.penUp()}
   */
  public static void setPenUp()
  {
    turtle().penUp();
  }
  /**
   * Makes it so a line of color out of will trail from the Tortoise.

   * Example: {@code  Tortoise.penDown()}
   */
  public static void setPenDown()
  {
    turtle().penDown();
  }
  /**
   * Removes everything from the window.

   * Example: {@code  Tortoise.clearWindow()}
   */
  public static void clear()
  {
    turtle().clear();
    turtle().getBackgroundWindow().setTurtle(turtle());
  }
  /**
   * Hides the tortoise, you will still see the pen markings it made before and after it's hidden.

   * Example: {@code  Tortoise.hide()}
   */
  public static void hide()
  {
    turtle().hide();
  }
  private static Turtle turtle()
  {
    return TortoiseUtils.getTurtle();
  }
  /**
   * Moves the Tortoise to a particular spot on the canvas.

   *
Example: {@code  Tortoise.moveTo(100,200);}

   *
   * @param x
   *          the x position
   * @param y
   *          the y position
   */
  public static void moveTo(int x, int y)
  {
    turtle().moveTo(x, y);
  }
  public static TurtleWindow ___()
  {
    return new TurtleWindow();
  }
  /**
   * Makes a cool shape fast
   *
Example:  {@code tortoise.drawShape(6,PenColors.Reds.Red, 50, 20)}

   * @param sides
   *            the number of sides
   * @param color
   *            a snazzy line color
   * @param length
   *            the bigger the better
   * @param width
   *            make a thick line - it's cool
   */
  public static void drawShape(int sides, Color color, int length, int width)
  {
    Tortoise.show();
    Tortoise.setSpeed(7);
    Tortoise.getBackgroundWindow().getCanvas().setBackground(PenColors.Yellows.Goldenrod);
    new Text("TKP Java - Make Some Shapes!").setTopLeft(225, 50).addTo(Tortoise.getBackgroundWindow());
    for (int i = 0; i < sides; i++)
    {
      Tortoise.setPenColor(color);
      Tortoise.setPenWidth(width);
      Tortoise.move(length);
      Tortoise.turn(360 / sides);
    }
    VirtualProctor.setClassName("Grace Hopper's Class");
    VirtualProctor.setName("Jean Bartik");
  }
  /**
   * Draws an entire Tortoise --  fast!
   *
Example:  {@code tortoise.drawTortoise()}

   */
  public static void drawTortoise()
  {
    Tortoise.show();
    Tortoise.setSpeed(9);
    Tortoise.getBackgroundWindow().setBackground(PenColors.Greens.DarkSeaGreen);
    new Text("TKP Java - It's the Tortoise!").setTopLeft(200, 75).addTo(Tortoise.getBackgroundWindow());
    Tortoise.setPenColor(PenColors.Greens.Green);
    Tortoise.setPenWidth(3);
    makeTortoiseBody();
    Tortoise.setPenColor(PenColors.Browns.Brown);
    Tortoise.turn(-65);
    Tortoise.makeTortoiseLeg();
    Tortoise.turn(90);
    Tortoise.move(150);
    Tortoise.turn(-90);
    Tortoise.makeTortoiseLeg();
  }
  private static void makeTortoiseLeg()
  {
    for (int i = 0; i < 4; i++)
    {
      Tortoise.move(35);
      Tortoise.turn(90);
    }
  }
  private static void makeTortoiseBody()
  {
    Tortoise.turn(-90);
    Tortoise.move(255);
    Tortoise.turn(135);
    Tortoise.move(135);
    Tortoise.turn(45);
    Tortoise.move(120);
    Tortoise.turn(45);
    Tortoise.move(70);
    Tortoise.turn(-90);
    Tortoise.move(35);
    Tortoise.turn(45);
    Tortoise.move(60);
    Tortoise.turn(65);
    Tortoise.move(50);
    Tortoise.turn(115);
    Tortoise.move(65);
    Tortoise.turn(-25);
    Tortoise.move(65);
  }
  public static void setVisible(boolean b)
  {
    turtle().setFrameVisible(b);
    turtle().setPanelVisible(b);
  }
  /**
   * Checks if a tortoise can eat a slice of a pizza
   *
Example: {@code  tortoise.eatPizza(pizza)}

   *
   * @param pizza
   *            the pizza
   * @return whether or not there is pizza left to eat that a tortoise likes
   */
  public boolean eatPizza(Pizza pizza)
  {
    if (!pizza.takeSlice()) { return false; }
    if (this.topping == null) { return true; }
    if (this.topping != Topping.Cheese) { return pizza.hasTopping(topping); }
    return pizza.wasCooked() && pizza.hasTopping(topping);
  }
  /**
   * Checks to see if a tortoise likes a particular kind of pizza topping
   *
Example: {@code  tortoise.likesTopping(topping)}

   *
   * @param topping
   *            the topping
   */
  public void likesTopping(Topping topping)
  {
    this.topping = topping;
  }
}


package org.teachingkidsprogramming.recipes.completed.section05recursion;

import org.teachingextensions.logo.Tortoise;
import org.teachingextensions.logo.utils.ColorUtils.PenColors;

public class RecursiveSquare
{
  public static void main(String[] args) throws Exception
  {
    Tortoise.show();
    Tortoise.getBackgroundWindow().setBackground(PenColors.Greens.DarkGreen);
    Tortoise.setPenColor(PenColors.Yellows.Gold);
    //  Set the speed to the fastest --#8
    Tortoise.setSpeed(10);
    //  Set the length to 100.0 --#1.1
    double length = 100.0;
    //  MakeASquare with the current length(recipe below) --#11.4
    makeASquare(length);
  }
  //
  //    Create the makeASquare recipe --#11.1
  private static void makeASquare(double length)
  {
    //  If the current length is greater than 10 --#10.2
    if (length > 10)
    {
      //    Run the recipe moveToTheSquareStart with the current length  --#4.3
      moveToTheSquareStart(length);
      //
      //    Do the following 4 times --#7.1
      for (int i = 0; i < 4; i++)
      {
        //      Move the Tortoise the current length
        Tortoise.move(length);
        //      MakeASquare with the current length divided by 1.7 (recipe below)--#11.3
        makeASquare(length / 1.7);
        //          If the current process count is less than 3 (HINT: use 'i') --#9
        if (i < 3)
        {
          //            Turn the tortoise 90 degrees to the right
          Tortoise.turn(90);
          //
        }
        //  End Repeat --#7.2
      }
      //  MoveBackToCenter with the current length (recipe below)--#5.3
      moveBackToCenter(length);
      //  Set the current length to the current length times two --#10.1
      length = length * 2;
    }
    //  End of makeASquare recipe
  }
  //  Create the moveToTheSquareStart recipe --#4.1
  private static void moveToTheSquareStart(double length)
  {
    //    Set the pen up for the tortoise --#1.2
    Tortoise.setPenUp();
    //    Move the tortoise the current length divided by two --#1.3
    Tortoise.move(length / 2);
    //    Turn the tortoise 90 degrees to the left --#2.1
    Tortoise.turn(-90);
    //    Move the tortoise the current length divided by two --#2.2
    Tortoise.move(length / 2);
    //    Turn the tortoise 180 degrees to the right --#3.1
    Tortoise.turn(180);
    //    Set the pen down for the tortoise --#3.2
    Tortoise.setPenDown();
    //  End of moveToTheSquareStart recipe --#4.2
  }
  //
  //  Create the moveBackToCenter recipe
  private static void moveBackToCenter(double length)
  {
    Tortoise.setPenUp();
    Tortoise.turn(90);
    Tortoise.move(length / 2);
    Tortoise.turn(90);
    Tortoise.move(length / 2);
    Tortoise.turn(180);
    Tortoise.setPenDown();
    //
  }
  //  End of moveBackToCenter recipe
}


package org.teachingextensions.approvals.lite.util;

import java.awt.Image;
import java.net.URL;

import javax.swing.ImageIcon;

/**
 * A static class of convenience functions for Manipulating objects
 */
public class ObjectUtils {

  /**
   * A convenience function to check if two objects are equal.
   *
   * @param s1
   *          The first object
   * @param s2
   *          The second object
   * @return true if Equal.
   */
  public static boolean isEqual(Object s1, Object s2) {
    return s1 == s2 || (s1 != null) && s1.equals(s2);
  }

  public static boolean isThisInstanceOfThat(Class<?> type, Class<?> that) {
    return that.isAssignableFrom(type);
  }

  public static Error throwAsError(Throwable t) throws Error {
    if (t instanceof RuntimeException) {
      throw (RuntimeException) t;
    } else if (t instanceof Error) {
      throw (Error) t;
    } else {
      throw new Error(t);
    }
  }

  public static String getClassName(Object o) {
    return o == null ? "null" : o.getClass().getName();
  }

  public static Image loadImage(Class<?> type, String name) {
    URL resource = type.getResource(name);
    if (resource == null) {
      resource = type.getClassLoader().getResource(name);
    }
    if (resource == null) {
      throw new IllegalStateException("Could not find image: " + name);
    }
    return new ImageIcon(resource).getImage();
  }
}


package org.teachingextensions.logo.utils.MVCUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.teachingextensions.approvals.lite.util.ObjectUtils;
import org.teachingextensions.approvals.lite.util.TestUtils;

/**
 *
 * Displays a view via a template, populated with a data object
 */
public class Viewer
{
  /**
   * Uses a RTF Viewer to display the results of a model (or text)
   *
Example: {@code  viewer.displayRtfFile(text)}

   *
   * @param text
   *            A model created from a String (text)
   */
  public static void displayRtfFile(String text)
  {
    try
    {
      File file;
      file = File.createTempFile("currentStory", ".rtf");
      FileWriter f = new FileWriter(file);
      f.write(text);
      f.close();
      TestUtils.displayFile(file.getPath());
    }
    catch (IOException e)
    {
      throw ObjectUtils.throwAsError(e);
    }
  }
}


package org.teachingextensions.approvals.lite.util;

import java.util.Random;

/**
 * A static class of convenience functions for Manipulating numbers
 */
public class NumberUtils
{
  public static Random RANDOM = new Random();
  /**
   * Loads an int from a String.
   *
   * @param i            a string with an integer in it
   * @param defaultValue value to use when no integer can be found in the string
   * @return the integer found in the string
   */
  public static int load(String i, int defaultValue)
  {
    return load(i, defaultValue, true);
  }
  /**
   * Loads an int from a String.
   *
   * @param i               a string with an integer in it
   * @param defaultValue    value to use when no integer can be found in the string
   * @param stripNonNumeric true if non-numeric characters should be removed from the string
   * @return the integer found in the string
   */
  public static int load(String i, int defaultValue, boolean stripNonNumeric)
  {
    try
    {
      i = stripNonNumeric ? StringUtils.stripNonNumeric(i, true, true) : i;
      defaultValue = Integer.parseInt(i);
    }
    catch (Exception ignored)
    {
    }
    return defaultValue;
  }
  public static boolean equals(double one, double two, double delta)
  {
    double actualDelta = one - two;
    return (-delta < actualDelta) && (actualDelta < delta);
  }
  /**
   * randomly chooses a number between the minimum and maximum
   *
Example:
   * {@code int grade =  NumberUtils.getRandomInt(1,100);}

   *
   * @param minimum The lowest possible value (inclusive)
   * @param maximum The highest possible value (inclusive)
   * @return the random number
   */
  public static int getRandomInt(int minimum, int maximum)
  {
    int diff = maximum - minimum;
    if (diff == 0)
    {
      return maximum;
    }
    else
    {
      return RANDOM.nextInt(diff) + minimum;
    }
  }
}


package org.teachingkidsprogramming.section07objects;

import java.awt.Cursor;

import org.junit.Assert;
import org.junit.Test;
import org.teachingextensions.logo.Tortoise;
import org.teachingextensions.logo.Turtle;
import org.teachingextensions.logo.Turtle.Animals;
import org.teachingextensions.logo.utils.PizzaUtils.Pizza;
import org.teachingextensions.logo.utils.PizzaUtils.Topping;

@SuppressWarnings("unused")
public class DeepDive07Objects
{
  //  Step 1: SELECT the method name (twoTortoises on line 26), then click the Run Button
  //            Keyboard shortcut to run ->  PC: Ctrl+F11 or Mac: Command+fn+F11
  //  Step 2: READ the name of the method that failed
  //  Step 3: FILL IN the blank (___) to make that method pass
  //  Step 4: SAY at least one thing you just learned
  //  Step 5: GO to the next method
  //  IMPORTANT - Do NOT change anything except the blank (___)//
  //
  @Test
  public void twoTortoises() throws Exception
  {
    Tortoise rafael = new Tortoise();
    Tortoise michealangelo = new Tortoise();
    boolean result = rafael.equals(michealangelo);
    Assert.assertEquals(______, result);
  }
  @Test
  public void twoTortoisesAgain() throws Exception
  {
    Tortoise rafael = new Tortoise();
    Tortoise anonymousNinja = rafael;
    boolean result = rafael.equals(anonymousNinja);
    Assert.assertEquals(_____, result);
  }
  @Test
  public void twoTortoisesYetAgain() throws Exception
  {
    Tortoise rafael = new Tortoise();
    Tortoise michelangelo = new Tortoise();
    Tortoise anonymousNinja = ________;
    boolean result = michelangelo.equals(anonymousNinja);
    Assert.assertEquals(true, result);
  }
  //Turtle Leonardo belongs to "this"
  private Turtle leonardo;
  @Test
  public void fatTrailTurtle() throws Exception
  {
    Turtle ninja = new Turtle();
    this.leonardo = _______;
    ninja.setPenWidth(30);
    Assert.assertEquals(30, this.leonardo.getPenWidth());
  }
  //Turtle Donatello belongs to "this"
  private Turtle donatello;
  @Test
  public void explodingTurtle() throws Exception
  {
    Turtle ninja = new Turtle();
    this._______ = ninja;
    this.donatello.setAnimal(Animals.ExplodedTurtle);
    Assert.assertTrue("The ninja is still alive!", ninja.isDead());
  }
  @Test
  public void feedTheNinja() throws Exception
  {
    Tortoise michelangelo = new Tortoise();
    michelangelo.likesTopping(Topping.Pepperoni);
    Pizza pizza = new Pizza();
    pizza.addTopping(_________);
    boolean likedIt = michelangelo.eatPizza(pizza);
    Assert.assertTrue("Michelangelo barfs! Wrong pizza!", likedIt);
  }
  @Test
  public void feedTheNinjaTwo() throws Exception
  {
    Tortoise karai = new Tortoise();
    karai.likesTopping(Topping.Anchovy);
    Pizza pizza = new Pizza();
    pizza.addTopping(Topping.Anchovy);
    boolean likedIt = karai.eatPizza(pizza);
    Assert.assertTrue("Karai turns greener! Wrong pizza!", _____);
  }
  @Test
  public void checkOutThePizza() throws Exception
  {
    Tortoise cecil = new Tortoise();
    cecil.likesTopping(Topping.Cheese);
    Pizza pizza = new Pizza();
    pizza.addTopping(Topping.Cheese);
    pizza.____();
    boolean likedIt = cecil.eatPizza(pizza);
    Assert.assertTrue("Cecil sends it back, raw pizza!", likedIt);
  }
  @Test
  public void feedAllTheNinjas() throws Exception
  {
    Tortoise[] tortoises = throwPizzaParty();
    Pizza pizza = new Pizza();
    pizza.____();
    for (Tortoise tortoise : tortoises)
    {
      gotASlice = tortoise.eatPizza(pizza);
      if (!gotASlice)
      {
        break;
      }
    }
    Assert.assertTrue("The ninja flips out - not enough pizza!", gotASlice);
  }
  @Test
  public void feedAllTheNinjasAgain() throws Exception
  {
    Tortoise[] tortoises = throwPizzaParty();
    Pizza pizza = new Pizza();
    pizza.superSizeIt();
    for (Tortoise tortoise : tortoises)
    {
      _____ = tortoise.eatPizza(pizza);
      if (!this.gotASlice)
      {
        break;
      }
    }
    Assert.assertTrue("The ninja flips out - not enough pizza!", this.gotASlice);
  }
  /**
   * Ignore the following, It's needed to run the deep dive
   *
   *
   *
   *
   *
   *
   *
   *
   *
   *
   */
  private Tortoise[] throwPizzaParty()
  {
    Tortoise karai = new Tortoise();
    Tortoise cecil = new Tortoise();
    Tortoise michealangelo = new Tortoise();
    Tortoise fred = new Tortoise();
    return new Tortoise[]{karai, cecil, michealangelo, fred};
  }
  private boolean gotASlice;
  public boolean  _____     = false;
  public boolean  ______    = true;
  public String   ___       = "You need to fill in the blank ___";
  public int      ____      = 0;
  public Turtle   _______   = new Turtle();
  public Tortoise ________;
  public Topping  _________ = Topping.NoTopping;
  public String ___()
  {
    return ___;
  }
  private Cursor getCursor()
  {
    return Tortoise.getBackgroundWindow().getCanvas().getCursor();
  }
  public DeepDive07Objects()
  {
    this.leonardo = new Turtle();
    this.donatello = new Turtle();
  }
}


package org.teachingextensions.logo.utils.PizzaUtils;

import java.util.ArrayList;

/**
 *
 * The Pizza allows you to make different sizes and kinds of pizza!
 */
public class Pizza
{
  private ArrayList<Topping> toppings = new ArrayList<Topping>();
  private boolean            cooked;
  private int                slices   = 2;
  /**
   * Adds a topping to a pizza
   *
Example: {@code pizza.addTopping(Topping.Spam)}

   *
   * @param topping A topping from the list
   */
  public void addTopping(Topping topping)
  {
    this.toppings.add(topping);
  }
  /**
   * Checks to see if a pizza has a particular kind of topping
   *
Example: {@code pizza.hasTopping(topping)}

   *
   * @param topping A topping from the list to check for
   * @return true when the pizza has the topping on it
   */
  public boolean hasTopping(Topping topping)
  {
    for (Topping toppingToday : toppings)
    {
      if (toppingToday == topping) { return true; }
    }
    return false;
  }
  /**
   * Cooks a pizza
   *
Example: {@code pizza.cook()}

   */
  public void cook()
  {
    this.cooked = true;
  }
  /**
   * Checks whether a pizza was cooked
   *
Example: {@code pizza.wasCooked()}

   *
   * @return whether or not the pizza has been cooked already
   */
  public boolean wasCooked()
  {
    return this.cooked;
  }
  public void ____()
  {
  }
  /**
   * Checks whether you can take a slice of pizza or not
   *
Example: {@code pizza.takeSlice()}

   *
   * @return whether or not the pizza has any more slices to take
   * If there are still slices, takes one slice
   */
  public boolean takeSlice()
  {
    if (0 < this.slices)
    {
      this.slices--;
      return true;
    }
    return false;
  }
  /**
   * Adds more slices to a pizza
   *
Example: {@code pizza.superSizeIt()}

   */
  public void superSizeIt()
  {
    this.slices = 8;
  }
}


package org.teachingextensions.approvals.lite.util.io;

import java.io.File;

public class SimpleFileFilter implements java.io.FileFilter {
    /**
     * ********************************************************************
     */
    public SimpleFileFilter() {
    }

    /**
     * *******************************************************************
     */
    public boolean accept(File pathname) {
        String name = pathname.getName().toLowerCase();
        boolean accept;
        accept = !(name.equals(".") || name.equals("..")) && !pathname.isDirectory();
        return accept;
    }
    /************************************************************************/
    /************************************************************************/
}


package org.teachingkidsprogramming.recipes.completed.section04mastery;

import java.awt.Color;

import org.teachingextensions.logo.Tortoise;
import org.teachingextensions.logo.utils.ColorUtils.ColorWheel;
import org.teachingextensions.logo.utils.ColorUtils.PenColors;

public class DigiFlower
{
  public static void main(String[] args)
  {
    //    Show the tortoise --#1
    Tortoise.show();
    //    Make the tortoise move as fast as possible --#6
    Tortoise.setSpeed(10);
    //    Make the background silver (use PenColors) --#7
    Tortoise.getBackgroundWindow().setBackground(PenColors.Grays.Silver);
    //    Make the line the tortoise draws 3 pixels wide --#12
    Tortoise.setPenWidth(3);
    //    CreateColorPalette (recipe below) --#8.1
    createColorPalette();
    //    Do the following 15 times --#11.1
    for (int i = 0; i < 15; i++)
    {
      //    DrawOctogon (recipe below) --#9.1
      drawOctogon();
      //     Turn the tortoise 1/15th of 360 degrees to the right --#10
      Tortoise.turn(360.0 / 15);
    }
  }
  //    ------------- Recipe for CreateColorPalette --#8.2
  private static void createColorPalette()
  {
    Color color1 = PenColors.Reds.Red;
    Color color2 = PenColors.Oranges.DarkOrange;
    Color color3 = PenColors.Yellows.Gold;
    Color color4 = PenColors.Yellows.Yellow;
    ColorWheel.addColor(color1);
    ColorWheel.addColor(color2);
    ColorWheel.addColor(color3);
    ColorWheel.addColor(color4);
    ColorWheel.addColor(color4);
    ColorWheel.addColor(color3);
    ColorWheel.addColor(color2);
    ColorWheel.addColor(color1);
    //  ------------- End of createColorPalette recipe --#8.3
  }
  //    ------------- Recipe for DrawOctogon --#9.2
  private static void drawOctogon()
  {
    //     Do the following 8 times --#5.1
    for (int i = 0; i < 8; i++)
    {
      //     Change the pen color of the line the tortoise draws to the next color on the color wheel --#3
      Tortoise.setPenColor(ColorWheel.getNextColor());
      //     Move the tortoise 50 pixels --#2
      Tortoise.move(50);
      //     Turn the tortoise 1/8th of 360 degrees to the right --#4
      Tortoise.turn(360.0 / 8);
      //    End Repeat --#5.2
    }
    //    ------------- End of drawOctogon recipe --#10.3
  }
}


package org.teachingextensions.logo.utils;

import org.teachingextensions.approvals.lite.Approvals;
import org.teachingextensions.approvals.lite.namer.ApprovalResults;
import org.teachingextensions.approvals.lite.util.ObjectUtils;
import org.teachingextensions.logo.Turtle;

public class TortoiseUtils {
  private static Turtle TURTLE = new Turtle();

  /**
   * Captures an image of the result of your program and displays it to you
   */
  public static void verify() {
    try {
      Approvals.verify(TURTLE.getImage());
    } catch (Exception e) {
      throw ObjectUtils.throwAsError(e);
    } finally {
      TortoiseUtils.resetTurtle();
    }
  }

  public static void resetTurtle() {
    TURTLE = new Turtle();
  }

  public static void setOrientation(int x, int y, int angle) {
    TURTLE.setX(x);
    TURTLE.setY(y);
    TURTLE.setAngleInDegrees(angle);
  }

  public static Turtle getTurtle() {
    return TURTLE;
  }

  public static void setTurtle(Turtle turtle) {
    TortoiseUtils.TURTLE = turtle;
  }

  public static void verifyForOs() {
    ApprovalResults.UniqueForOs();
    verify();
  }

  public static void writeMessage(String string, int x, int y) {
    TURTLE.setX(x);
    TURTLE.setY(y);
    TURTLE.print(string);
  }
}


package org.teachingextensions.logo.utils.PuzzleUtils;

import java.awt.Point;
import java.util.Arrays;

/**
 * A nine-puzzle
 *
 * @see Wikipedia
 */
public class Puzzle
{
  private static final int blank = 8;
  private final int[]      cells;
  public Puzzle(int[] cells)
  {
    this.cells = cells;
  }
  /**
   * Gives the position of the cell as it would appear on a 3x3 board.
   *
   * @param cell
   *     The cell to get the position for.
   * @return The position of the cell.
   */
  public static Point getPosition(int cell)
  {
    return new Point(cell % 3, cell / 3);
  }
  /**
   * Calculate the Manhattan Distance between two positions.
   *
   * @param start
   *     The starting position.
   * @param end
   *     The ending position.
   * @return The distance between the two positions.
   */
  public static int getDistance(Point start, Point end)
  {
    return Math.abs(start.x - end.x) + Math.abs(start.y - end.y);
  }
  /**
   * Calculate the Manhattan Distance between two cells by first converting them to positions.
   *
   * @param start
   *     The starting cell
   * @param end
   *     The ending cell
   * @return The distance between the cells.
   */
  public static int getDistance(int start, int end)
  {
    return getDistance(getPosition(start), getPosition(end));
  }
  @Override
  public int hashCode()
  {
    return Arrays.hashCode(cells);
  }
  @Override
  public boolean equals(Object o)
  {
    if (this == o)
      return true;
    if (o == null || getClass() != o.getClass())
      return false;
    Puzzle puzzle = (Puzzle) o;
    return Arrays.equals(cells, puzzle.cells);
  }
  @Override
  public String toString()
  {
    return Arrays.toString(cells);
  }
  public boolean isSolved()
  {
    return getDistanceToGoal() == 0;
  }
  public int getBlankIndex()
  {
    for (int i = 0; i < cells.length; i++)
    {
      if (cells[i] == blank) { return i; }
    }
    return -1;
  }
  /**
   * Create a copy of the puzzle where the blank swapped with the value in the target position
   *
   * @param target
   *     move the blank to this location, and move the value from this location to the current blank location
   * @return A copy of the puzzle with the blank and target swapped.
   */
  public Puzzle swapBlank(int target)
  {
    int[] copy = Arrays.copyOf(cells, cells.length);
    int x = copy[target];
    copy[getBlankIndex()] = x;
    copy[target] = 8;
    return new Puzzle(copy);
  }
  /**
   * Calculate the distance between the goal by summing the distance between each cell and its goal.
   *
   * @return The distance to the goal.
   */
  public int getDistanceToGoal()
  {
    int distance = 0;
    for (int i = 0; i < cells.length; i++)
    {
      distance += getDistance(i, cells[i]);
    }
    return distance;
  }
  public int[] getCells()
  {
    return Arrays.copyOf(cells, cells.length);
  }
}


package org.teachingextensions.logo;

import java.awt.Toolkit;
import java.net.URL;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

/**
 *
 * Sound allows you to play a sound, like a 'beep' or the sound from a file
 */
public class Sound
{
  private URL soundUrl = null;
  public Sound()
  {
    this(TKPSound.Yay);
  }
  public Sound(TKPSound sound)
  {
    this.setSound(sound);
  }
  /**
   * Plays a beep through your speakers. BEEP!

   * Example: {@code  Sound.playBeep()}
   */
  public static void playBeep()
  {
    Toolkit.getDefaultToolkit().beep();
  }
  /**
   * Sets a sound that you can play through your speakers.
   * Use a TKPSound (there is a list)

   * Example: {@code  Sound.setSound(TKPSound.Ahem)}
   */
  public synchronized void setSound(TKPSound mySound)
  {
    String sound = "soundFiles/" + mySound + ".wav";
    URL resource = this.getClass().getResource(sound);
    if (resource == null)
    {
      resource = this.getClass().getClassLoader().getResource(sound);
    }
    if (resource == null) { throw new IllegalStateException("Could not get TKPSound: " + sound); }
    this.soundUrl = resource;
  }
  /**
   * Plays a TKPSound through your speakers.
   * You must first set the TKPSound

   * Example: {@code  Sound.playSound()}
   */
  public synchronized void playSound()
  {
    final URL sound = this.soundUrl;
    new Thread(new Runnable()
    {
      @Override
      public void run()
      {
        try
        {
          Clip clip = AudioSystem.getClip();
          AudioInputStream inputStream = AudioSystem.getAudioInputStream(sound);
          clip.open(inputStream);
          clip.start();
        }
        catch (Exception e)
        {
          System.out.println("play sound error: " + e.getMessage() + " for " + sound);
        }
      }
    }).start();
  }
  /**
   * Check out our cool sounds - thanks to http://www.wavsource.com/
   */
  public enum TKPSound {
                        Ahem, Applause, BrainIsGone, CatMeow, Cheering, Crickets, DoctorMccoy, Fanfare, FargoYah,
                        Gong, LLCoolJYaKnow, LosingPower, LoveBeingATurtle, Malfunction, Pizza, RunAway,
                        SheerIgnorance, SoBeIt, StrangePerson, Stubborn, Yahoo, Yay
  }
}


package org.teachingextensions.logo.utils.MazeUtils;

/******************************************************************************
 *  Compilation:  javac StdOut.java
 *  Execution:    java StdOut
 *  Dependencies: none
 *
 *  Writes data of various types to standard output.
 *
 ******************************************************************************/
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Locale;

/**
 *  This class provides methods for printing strings and numbers to standard output.
 *

 *  Getting started.
 *  To use this class, you must have <tt>StdOut.class</tt> in your
 *  Java classpath. If you used our autoinstaller, you should be all set.
 *  Otherwise, download
 *  StdOut.java
 *  and put a copy in your working directory.
 *

 *  Here is an example program that uses StdOut:
 *

 *   public class TestStdOut {
 *       public static void main(String[] args) {
 *           int a = 17;
 *           int b = 23;
 *           int sum = a + b;
 *           StdOut.println("Hello, World");
 *           StdOut.printf("%d + %d = %d\n", a, b, sum);
 *       }
 *   }
 *

 *

 *  Differences with System.out.
 *  The behavior of StdOut is similar to that of {@link System#out},
 *  but there are a few subtle differences:
 *

 *
 StdOut coerces the character-set encoding to UTF-8,
 *       which is a standard character encoding for Unicode.
 *
 StdOut coerces the locale to {@link Locale#US},
 *       for consistency with {@link StdIn}, {@link Double#parseDouble(String)},
 *       and floating-point literals.
 *
 StdOut flushes standard output after each call to
 *       print() so that text will appear immediately in the terminal.
 *

 *

 *  Reference.
 *  For additional documentation,
 *  see Section 1.5 of
 *  Introduction to Programming in Java: An Interdisciplinary Approach
 *  by Robert Sedgewick and Kevin Wayne.
 *
 *  @author Robert Sedgewick
 *  @author Kevin Wayne
 */
public final class StdOut
{
  // force Unicode UTF-8 encoding; otherwise it's system dependent
  private static final String CHARSET_NAME = "UTF-8";
  // assume language = English, country = US for consistency with StdIn
  private static final Locale LOCALE       = Locale.US;
  // send output here
  private static PrintWriter  out;
  // this is called before invoking any methods
  static
  {
    try
    {
      out = new PrintWriter(new OutputStreamWriter(System.out, CHARSET_NAME), true);
    }
    catch (UnsupportedEncodingException e)
    {
      System.out.println(e);
    }
  }
  // don't instantiate
  private StdOut()
  {
  }
  /**
    * Closes standard output.
    */
  public static void close()
  {
    out.close();
  }
  /**
    * Terminates the current line by printing the line-separator string.
    */
  public static void println()
  {
    out.println();
  }
  /**
    * Prints an object to this output stream and then terminates the line.
    *
    * @param x the object to print
    */
  public static void println(Object x)
  {
    out.println(x);
  }
  /**
    * Prints a boolean to standard output and then terminates the line.
    *
    * @param x the boolean to print
    */
  public static void println(boolean x)
  {
    out.println(x);
  }
  /**
    * Prints a character to standard output and then terminates the line.
    *
    * @param x the character to print
    */
  public static void println(char x)
  {
    out.println(x);
  }
  /**
    * Prints a double to standard output and then terminates the line.
    *
    * @param x the double to print
    */
  public static void println(double x)
  {
    out.println(x);
  }
  /**
    * Prints an integer to standard output and then terminates the line.
    *
    * @param x the integer to print
    */
  public static void println(float x)
  {
    out.println(x);
  }
  /**
    * Prints an integer to standard output and then terminates the line.
    *
    * @param x the integer to print
    */
  public static void println(int x)
  {
    out.println(x);
  }
  /**
    * Prints a long to standard output and then terminates the line.
    *
    * @param x the long to print
    */
  public static void println(long x)
  {
    out.println(x);
  }
  /**
    * Prints a short integer to standard output and then terminates the line.
    *
    * @param x the short to print
    */
  public static void println(short x)
  {
    out.println(x);
  }
  /**
    * Prints a byte to standard output and then terminates the line.
    *

    * To write binary data, see {@link BinaryStdOut}.
    *
    * @param x the byte to print
    */
  public static void println(byte x)
  {
    out.println(x);
  }
  /**
    * Flushes standard output.
    */
  public static void print()
  {
    out.flush();
  }
  /**
    * Prints an object to standard output and flushes standard output.
    *
    * @param x the object to print
    */
  public static void print(Object x)
  {
    out.print(x);
    out.flush();
  }
  /**
    * Prints a boolean to standard output and flushes standard output.
    *
    * @param x the boolean to print
    */
  public static void print(boolean x)
  {
    out.print(x);
    out.flush();
  }
  /**
    * Prints a character to standard output and flushes standard output.
    *
    * @param x the character to print
    */
  public static void print(char x)
  {
    out.print(x);
    out.flush();
  }
  /**
    * Prints a double to standard output and flushes standard output.
    *
    * @param x the double to print
    */
  public static void print(double x)
  {
    out.print(x);
    out.flush();
  }
  /**
    * Prints a float to standard output and flushes standard output.
    *
    * @param x the float to print
    */
  public static void print(float x)
  {
    out.print(x);
    out.flush();
  }
  /**
    * Prints an integer to standard output and flushes standard output.
    *
    * @param x the integer to print
    */
  public static void print(int x)
  {
    out.print(x);
    out.flush();
  }
  /**
    * Prints a long integer to standard output and flushes standard output.
    *
    * @param x the long integer to print
    */
  public static void print(long x)
  {
    out.print(x);
    out.flush();
  }
  /**
    * Prints a short integer to standard output and flushes standard output.
    *
    * @param x the short integer to print
    */
  public static void print(short x)
  {
    out.print(x);
    out.flush();
  }
  /**
    * Prints a byte to standard output and flushes standard output.
    *
    * @param x the byte to print
    */
  public static void print(byte x)
  {
    out.print(x);
    out.flush();
  }
  /**
    * Prints a formatted string to standard output, using the specified format
    * string and arguments, and then flushes standard output.
    *
    *
    * @param format the format string
    * @param args   the arguments accompanying the format string
    */
  public static void printf(String format, Object... args)
  {
    out.printf(LOCALE, format, args);
    out.flush();
  }
  /**
    * Prints a formatted string to standard output, using the locale and
    * the specified format string and arguments; then flushes standard output.
    *
    * @param locale the locale
    * @param format the format string
    * @param args   the arguments accompanying the format string
    */
  public static void printf(Locale locale, String format, Object... args)
  {
    out.printf(locale, format, args);
    out.flush();
  }
  /**
    * Unit tests some of the methods in <tt>StdOut</tt>.
    */
  public static void main(String[] args)
  {
    // write to stdout
    StdOut.println("Test");
    StdOut.println(17);
    StdOut.println(true);
    StdOut.printf("%.6f\n", 1.0 / 7.0);
  }
}


package org.teachingkidsprogramming.recipes.completed.section07objects;

import javax.swing.ImageIcon;

import org.teachingextensions.logo.utils.EventUtils.FancyMessageBox;

//*************This Lesson is In Development*****************************//
public class WhichFish
{
  public static void main(String[] args)
  {
    //  Uncomment to create a variable called 'numberOfFish' to hold the result of the question "How many fishes?"
    //  Use the FancyMessageBox with a title of "Are fishes like wishes?"
    int numberOfFish = FancyMessageBox.askForNumericalInput("How many fishes?", "Are Fishes Like Wishes?");
    //  create recipe makeAFishyDecision using the numberOfFish (recipe below)
    makeAFishyDecision(numberOfFish);
  }
  //    recipe for makeAFishyDecision with the numberOfFish
  public static void makeAFishyDecision(int numberOfFish)
  {
    // Use a switch...case on the numberOfFish
    switch (numberOfFish)
    {
      // When the numberOfFish is -1
      case -1 :
        // Uncomment to create a string of this image
        String image = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/thumb-up.png";
        //  Create a new ImageIcon from your image
        ImageIcon icon = new ImageIcon(image);
        // Show a message with the fancy message box this text, this title and this icon...
        FancyMessageBox.showMesage("Had a Fish", "Not hungry anymore...", icon);
        // End
        break;
      // When the numberOfFish is 0
      case 0 :
        // Uncomment to create a string of this image
        String image0 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/information.png";
        //  Create a new ImageIcon from your image
        ImageIcon icon0 = new ImageIcon(image0);
        // Show a message with the fancy message box this text, this title and this icon...
        FancyMessageBox.showMesage("No Fish", "Still hungry", icon0);
        // End
        break;
      // When the numberOfFish is 1
      case 1 :
        // Uncomment to create a string of this image
        String image1 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/star.png";
        // Create a new ImageIcon from your image
        ImageIcon icon1 = new ImageIcon(image1);
        // Show a message with the fancy message box this text, this title and this icon...
        FancyMessageBox.showMesage("One Fish", "This one has a little star", icon1);
        // End
        break;
      // When the numberOfFish is 0
      case 2 :
        // Uncomment to create a string of this image
        String image2 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/github.png";
        //  Create a new ImageIcon from your image
        ImageIcon icon2 = new ImageIcon(image2);
        // Show a message with the fancy message box this text, this title and this icon...
        FancyMessageBox.showMesage("Two Fish", "Funny things are everywhere", icon2);
        // End
        break;
      // Otherwise
      default :
        // Uncomment to create a string of this image
        String image4 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/hint.png";
        // Create a new ImageIcon from your image
        ImageIcon icon4 = new ImageIcon(image4);
        // Show a message with the fancy message box this text, this title and this icon...
        FancyMessageBox.showMesage("Vegetaraian meal", "Fish are icky", icon4);
        // End
        break;
    }
  }
}


package org.teachingextensions.logo.utils.MazeUtils;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.DirectColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.TreeSet;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;

public final class StdDraw implements ActionListener, KeyListener
{
  private static final int             DEFAULT_SIZE       = 350;
  private static int                   width              = DEFAULT_SIZE;
  private static int                   height             = DEFAULT_SIZE;
  private static final double          DEFAULT_PEN_RADIUS = 0.0175;
  private static double                currentPenRadius;
  private static boolean               defer              = false;
  private static final double          BORDER             = 0.00;
  private static final double          DEFAULT_XMIN       = 0.0;
  private static final double          DEFAULT_XMAX       = 1.0;
  private static final double          DEFAULT_YMIN       = 0.0;
  private static final double          DEFAULT_YMAX       = 1.0;
  private static double                xmin, ymin, xmax, ymax;
  private static final Font            DEFAULT_FONT       = new Font("SansSerif", Font.PLAIN, 16);
  private static Font                  font;
  private static BufferedImage         offscreenImage, onscreenImage;
  private static Graphics2D            offscreen, onscreen;
  private static StdDraw               stdDraw            = new StdDraw();
  public static JFrame                 frame;
  private static Object                keyLock            = new Object();
  private static LinkedList<Character> keysTyped          = new LinkedList<Character>();
  private static TreeSet<Integer>      keysDown           = new TreeSet<Integer>();
  private static long                  nextDrawInMS       = -1;
  private StdDraw()
  {
  }
  static
  {
    init();
  }
  public static void main(String[] args)
  {
    StdDraw.square(.2, .8, .1);
    StdDraw.filledSquare(.8, .8, .2);
    StdDraw.circle(.8, .2, .2);
    StdDraw.setPenColor(StdDrawColors.BOOK_RED);
    StdDraw.setPenRadius(.02);
    StdDraw.arc(.8, .2, .1, 200, 45);
    StdDraw.setPenRadius();
    StdDraw.setPenColor(StdDrawColors.BOOK_BLUE);
    double[] x = {.1, .2, .3, .2};
    double[] y = {.2, .3, .2, .1};
    StdDraw.filledPolygon(x, y);
    StdDraw.setPenColor(StdDrawColors.BLACK);
    StdDraw.text(0.2, 0.5, "black text");
    StdDraw.setPenColor(StdDrawColors.WHITE);
    StdDraw.text(0.8, 0.8, "white text");
  }
  public static void setCanvasSize()
  {
    setCanvasSize(DEFAULT_SIZE, DEFAULT_SIZE);
  }
  public static void setCanvasSize(int canvasWidth, int canvasHeight)
  {
    if (width <= 0 || height <= 0)
      throw new IllegalArgumentException("width and height must be positive");
    width = canvasWidth;
    height = canvasHeight;
    init();
  }
  private static void init()
  {
    if (frame != null)
      frame.setVisible(false);
    frame = new JFrame();
    offscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    onscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    offscreen = offscreenImage.createGraphics();
    onscreen = onscreenImage.createGraphics();
    setXscale();
    setYscale();
    offscreen.setColor(StdDrawColors.DEFAULT_CLEAR_COLOR);
    offscreen.fillRect(0, 0, width, height);
    setPenColor();
    setPenRadius();
    setFont();
    clearScreenToWhite();
    RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    offscreen.addRenderingHints(hints);
    ImageIcon icon = new ImageIcon(onscreenImage);
    JLabel draw = new JLabel(icon);
    frame.setContentPane(draw);
    frame.addKeyListener(stdDraw);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // close all windows
    // frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);      // closes only current window
    frame.setTitle("Amazing Maze!");
    frame.setJMenuBar(createMenuBar());
    frame.pack();
    frame.requestFocusInWindow();
    frame.setVisible(true);
    // TODO: This is not working, so mouse events won't work yet...
    //draw.addMouseListener(stdDraw);
    //draw.addMouseMotionListener(stdDraw);
    MouseListener l = null;
    draw.addMouseListener(l);
    MouseMotionListener m = null;
    draw.addMouseMotionListener(m);
  }
  private static JMenuBar createMenuBar()
  {
    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu("File");
    menuBar.add(menu);
    JMenuItem menuItem1 = new JMenuItem(" Save...   ");
    menuItem1.addActionListener(stdDraw);
    menuItem1.setAccelerator(
        KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    menu.add(menuItem1);
    return menuBar;
  }
  public static void setXscale()
  {
    setXscale(DEFAULT_XMIN, DEFAULT_XMAX);
  }
  public static void setYscale()
  {
    setYscale(DEFAULT_YMIN, DEFAULT_YMAX);
  }
  public static void setScale()
  {
    setXscale();
    setYscale();
  }
  public static void setXscale(double min, double max)
  {
    double size = max - min;
    if (size == 0.0)
      throw new IllegalArgumentException("the min and max are the same");
    synchronized (StdDrawMouseEvents.mouseLock)
    {
      xmin = min - BORDER * size;
      xmax = max + BORDER * size;
    }
  }
  public static void setYscale(double min, double max)
  {
    double size = max - min;
    if (size == 0.0)
      throw new IllegalArgumentException("the min and max are the same");
    synchronized (StdDrawMouseEvents.mouseLock)
    {
      ymin = min - BORDER * size;
      ymax = max + BORDER * size;
    }
  }
  public static void setScale(double min, double max)
  {
    double size = max - min;
    if (size == 0.0)
      throw new IllegalArgumentException("the min and max are the same");
    synchronized (StdDrawMouseEvents.mouseLock)
    {
      xmin = min - BORDER * size;
      xmax = max + BORDER * size;
      ymin = min - BORDER * size;
      ymax = max + BORDER * size;
    }
  }
  private static double scaleX(double x)
  {
    return width * (x - xmin) / (xmax - xmin);
  }
  private static double scaleY(double y)
  {
    return height * (ymax - y) / (ymax - ymin);
  }
  private static double factorX(double w)
  {
    return w * width / Math.abs(xmax - xmin);
  }
  private static double factorY(double h)
  {
    return h * height / Math.abs(ymax - ymin);
  }
  static double userX(double x)
  {
    return xmin + x * (xmax - xmin) / width;
  }
  static double userY(double y)
  {
    return ymax - y * (ymax - ymin) / height;
  }
  public static void clearScreenToWhite()
  {
    clearScreenToColor(StdDrawColors.DEFAULT_CLEAR_COLOR);
  }
  public static void clearScreenToColor(Color color)
  {
    offscreen.setColor(color);
    offscreen.fillRect(0, 0, width, height);
    offscreen.setColor(StdDrawColors.currentPenColor);
    draw();
  }
  public static double getPenRadius()
  {
    return currentPenRadius;
  }
  public static void setPenRadius()
  {
    setPenRadius(DEFAULT_PEN_RADIUS);
  }
  public static void setPenRadius(double radius)
  {
    if (!(radius >= 0))
      throw new IllegalArgumentException("pen radius must be nonnegative");
    currentPenRadius = radius;
    float scaledPenRadius = (float) (radius * DEFAULT_SIZE);
    BasicStroke stroke = new BasicStroke(scaledPenRadius, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
    offscreen.setStroke(stroke);
  }
  public static Color getPenColor()
  {
    return StdDrawColors.currentPenColor;
  }
  public static void setPenColor()
  {
    setPenColor(StdDrawColors.DEFAULT_PEN_COLOR);
  }
  public static void setPenColor(Color color)
  {
    if (color == null)
      throw new NullPointerException();
    StdDrawColors.currentPenColor = color;
    offscreen.setColor(StdDrawColors.currentPenColor);
  }
  public static void setPenColor(int red, int green, int blue)
  {
    if (red < 0 || red >= 256)
      throw new IllegalArgumentException("amount of red must be between 0 and 255");
    if (green < 0 || green >= 256)
      throw new IllegalArgumentException("amount of green must be between 0 and 255");
    if (blue < 0 || blue >= 256)
      throw new IllegalArgumentException("amount of blue must be between 0 and 255");
    setPenColor(new Color(red, green, blue));
  }
  public static Font getFont()
  {
    return font;
  }
  public static void setFont()
  {
    setFont(DEFAULT_FONT);
  }
  public static void setFont(Font font)
  {
    if (font == null)
      throw new NullPointerException();
    StdDraw.font = font;
  }
  /**
   * Draws a line segment between (x0, y0) and
   * (x1, y1).
   *
   * @param  x0 the x-coordinate of one endpoint
   * @param  y0 the y-coordinate of one endpoint
   * @param  x1 the x-coordinate of the other endpoint
   * @param  y1 the y-coordinate of the other endpoint
   */
  public static void line(double x0, double y0, double x1, double y1)
  {
    offscreen.draw(new Line2D.Double(scaleX(x0), scaleY(y0), scaleX(x1), scaleY(y1)));
    draw();
  }
  /**
   * Draws one pixel at (x, y).
   * This method is private because pixels depend on the display.
   * To achieve the same effect, set the pen radius to 0 and call {@code point()}.
   *
   * @param  x the x-coordinate of the pixel
   * @param  y the y-coordinate of the pixel
   */
  private static void pixel(double x, double y)
  {
    offscreen.fillRect((int) Math.round(scaleX(x)), (int) Math.round(scaleY(y)), 1, 1);
  }
  /**
   * Draws a point centered at (x, y).
   * The point is a filled circle whose radius is equal to the pen radius.
   * To draw a single-pixel point, first set the pen radius to 0.
   *
   * @param x the x-coordinate of the point
   * @param y the y-coordinate of the point
   */
  public static void point(double x, double y)
  {
    double xs = scaleX(x);
    double ys = scaleY(y);
    double r = currentPenRadius;
    float scaledPenRadius = (float) (r * DEFAULT_SIZE);
    if (scaledPenRadius <= 1)
      pixel(x, y);
    else
      offscreen.fill(new Ellipse2D.Double(xs - scaledPenRadius / 2, ys - scaledPenRadius / 2, scaledPenRadius,
          scaledPenRadius));
    draw();
  }
  /**
   * Draws a circle of the specified radius, centered at (x, y).
   *
   * @param  x the x-coordinate of the center of the circle
   * @param  y the y-coordinate of the center of the circle
   * @param  radius the radius of the circle
   * @throws IllegalArgumentException if {@code radius} is negative
   */
  public static void circle(double x, double y, double radius)
  {
    if (!(radius >= 0))
      throw new IllegalArgumentException("radius must be nonnegative");
    double xs = scaleX(x);
    double ys = scaleY(y);
    double ws = factorX(2 * radius);
    double hs = factorY(2 * radius);
    if (ws <= 1 && hs <= 1)
      pixel(x, y);
    else
      offscreen.draw(new Ellipse2D.Double(xs - ws / 2, ys - hs / 2, ws, hs));
    draw();
  }
  /**
   * Draws a filled circle of the specified radius, centered at (x, y).
   *
   * @param  x the x-coordinate of the center of the circle
   * @param  y the y-coordinate of the center of the circle
   * @param  radius the radius of the circle
   * @throws IllegalArgumentException if {@code radius} is negative
   */
  public static void filledCircle(double x, double y, double radius)
  {
    if (!(radius >= 0))
      throw new IllegalArgumentException("radius must be nonnegative");
    double xs = scaleX(x);
    double ys = scaleY(y);
    double ws = factorX(2 * radius);
    double hs = factorY(2 * radius);
    if (ws <= 1 && hs <= 1)
      pixel(x, y);
    else
      offscreen.fill(new Ellipse2D.Double(xs - ws / 2, ys - hs / 2, ws, hs));
    draw();
  }
  /**
   * Draws an ellipse with the specified semimajor and semiminor axes,
   * centered at (x, y).
   *
   * @param  x the x-coordinate of the center of the ellipse
   * @param  y the y-coordinate of the center of the ellipse
   * @param  semiMajorAxis is the semimajor axis of the ellipse
   * @param  semiMinorAxis is the semiminor axis of the ellipse
   * @throws IllegalArgumentException if either {@code semiMajorAxis}
   *         or {@code semiMinorAxis} is negative
   */
  public static void ellipse(double x, double y, double semiMajorAxis, double semiMinorAxis)
  {
    if (!(semiMajorAxis >= 0))
      throw new IllegalArgumentException("ellipse semimajor axis must be nonnegative");
    if (!(semiMinorAxis >= 0))
      throw new IllegalArgumentException("ellipse semiminor axis must be nonnegative");
    double xs = scaleX(x);
    double ys = scaleY(y);
    double ws = factorX(2 * semiMajorAxis);
    double hs = factorY(2 * semiMinorAxis);
    if (ws <= 1 && hs <= 1)
      pixel(x, y);
    else
      offscreen.draw(new Ellipse2D.Double(xs - ws / 2, ys - hs / 2, ws, hs));
    draw();
  }
  /**
   * Draws an ellipse with the specified semimajor and semiminor axes,
   * centered at (x, y).
   *
   * @param  x the x-coordinate of the center of the ellipse
   * @param  y the y-coordinate of the center of the ellipse
   * @param  semiMajorAxis is the semimajor axis of the ellipse
   * @param  semiMinorAxis is the semiminor axis of the ellipse
   * @throws IllegalArgumentException if either {@code semiMajorAxis}
   *         or {@code semiMinorAxis} is negative
   */
  public static void filledEllipse(double x, double y, double semiMajorAxis, double semiMinorAxis)
  {
    if (!(semiMajorAxis >= 0))
      throw new IllegalArgumentException("ellipse semimajor axis must be nonnegative");
    if (!(semiMinorAxis >= 0))
      throw new IllegalArgumentException("ellipse semiminor axis must be nonnegative");
    double xs = scaleX(x);
    double ys = scaleY(y);
    double ws = factorX(2 * semiMajorAxis);
    double hs = factorY(2 * semiMinorAxis);
    if (ws <= 1 && hs <= 1)
      pixel(x, y);
    else
      offscreen.fill(new Ellipse2D.Double(xs - ws / 2, ys - hs / 2, ws, hs));
    draw();
  }
  /**
   * Draws a circular arc of the specified radius,
   * centered at (x, y), from angle1 to angle2 (in degrees).
   *
   * @param  x the x-coordinate of the center of the circle
   * @param  y the y-coordinate of the center of the circle
   * @param  radius the radius of the circle
   * @param  angle1 the starting angle. 0 would mean an arc beginning at 3 o'clock.
   * @param  angle2 the angle at the end of the arc. For example, if
   *         you want a 90 degree arc, then angle2 should be angle1 + 90.
   * @throws IllegalArgumentException if {@code radius} is negative
   */
  public static void arc(double x, double y, double radius, double angle1, double angle2)
  {
    if (radius < 0)
      throw new IllegalArgumentException("arc radius must be nonnegative");
    while (angle2 < angle1)
      angle2 += 360;
    double xs = scaleX(x);
    double ys = scaleY(y);
    double ws = factorX(2 * radius);
    double hs = factorY(2 * radius);
    if (ws <= 1 && hs <= 1)
      pixel(x, y);
    else
      offscreen.draw(new Arc2D.Double(xs - ws / 2, ys - hs / 2, ws, hs, angle1, angle2 - angle1, Arc2D.OPEN));
    draw();
  }
  /**
   * Draws a square of side length 2r, centered at (x, y).
   *
   * @param  x the x-coordinate of the center of the square
   * @param  y the y-coordinate of the center of the square
   * @param  halfLength one half the length of any side of the square
   * @throws IllegalArgumentException if {@code halfLength} is negative
   */
  public static void square(double x, double y, double halfLength)
  {
    if (!(halfLength >= 0))
      throw new IllegalArgumentException("half length must be nonnegative");
    double xs = scaleX(x);
    double ys = scaleY(y);
    double ws = factorX(2 * halfLength);
    double hs = factorY(2 * halfLength);
    if (ws <= 1 && hs <= 1)
      pixel(x, y);
    else
      offscreen.draw(new Rectangle2D.Double(xs - ws / 2, ys - hs / 2, ws, hs));
    draw();
  }
  /**
   * Draws a filled square of the specified size, centered at (x, y).
   *
   * @param  x the x-coordinate of the center of the square
   * @param  y the y-coordinate of the center of the square
   * @param  halfLength one half the length of any side of the square
   * @throws IllegalArgumentException if {@code halfLength} is negative
   */
  public static void filledSquare(double x, double y, double halfLength)
  {
    if (!(halfLength >= 0))
      throw new IllegalArgumentException("half length must be nonnegative");
    double xs = scaleX(x);
    double ys = scaleY(y);
    double ws = factorX(2 * halfLength);
    double hs = factorY(2 * halfLength);
    if (ws <= 1 && hs <= 1)
      pixel(x, y);
    else
      offscreen.fill(new Rectangle2D.Double(xs - ws / 2, ys - hs / 2, ws, hs));
    draw();
  }
  /**
   * Draws a rectangle of the specified size, centered at (x, y).
   *
   * @param  x the x-coordinate of the center of the rectangle
   * @param  y the y-coordinate of the center of the rectangle
   * @param  halfWidth one half the width of the rectangle
   * @param  halfHeight one half the height of the rectangle
   * @throws IllegalArgumentException if either {@code halfWidth} or {@code halfHeight} is negative
   */
  public static void rectangle(double x, double y, double halfWidth, double halfHeight)
  {
    if (!(halfWidth >= 0))
      throw new IllegalArgumentException("half width must be nonnegative");
    if (!(halfHeight >= 0))
      throw new IllegalArgumentException("half height must be nonnegative");
    double xs = scaleX(x);
    double ys = scaleY(y);
    double ws = factorX(2 * halfWidth);
    double hs = factorY(2 * halfHeight);
    if (ws <= 1 && hs <= 1)
      pixel(x, y);
    else
      offscreen.draw(new Rectangle2D.Double(xs - ws / 2, ys - hs / 2, ws, hs));
    draw();
  }
  /**
   * Draws a filled rectangle of the specified size, centered at (x, y).
   *
   * @param  x the x-coordinate of the center of the rectangle
   * @param  y the y-coordinate of the center of the rectangle
   * @param  halfWidth one half the width of the rectangle
   * @param  halfHeight one half the height of the rectangle
   * @throws IllegalArgumentException if either {@code halfWidth} or {@code halfHeight} is negative
   */
  public static void filledRectangle(double x, double y, double halfWidth, double halfHeight)
  {
    if (!(halfWidth >= 0))
      throw new IllegalArgumentException("half width must be nonnegative");
    if (!(halfHeight >= 0))
      throw new IllegalArgumentException("half height must be nonnegative");
    double xs = scaleX(x);
    double ys = scaleY(y);
    double ws = factorX(2 * halfWidth);
    double hs = factorY(2 * halfHeight);
    if (ws <= 1 && hs <= 1)
      pixel(x, y);
    else
      offscreen.fill(new Rectangle2D.Double(xs - ws / 2, ys - hs / 2, ws, hs));
    draw();
  }
  /**
   * Draws a polygon with the vertices
   * (x0, y0),
   * (x1, y1), ...,
   * (xn−1, yn−1).
   *
   * @param  x an array of all the x-coordinates of the polygon
   * @param  y an array of all the y-coordinates of the polygon
   * @throws IllegalArgumentException unless {@code x[]} and {@code y[]}
   *         are of the same length
   */
  public static void polygon(double[] x, double[] y)
  {
    if (x == null)
      throw new NullPointerException();
    if (y == null)
      throw new NullPointerException();
    int n1 = x.length;
    int n2 = y.length;
    if (n1 != n2)
      throw new IllegalArgumentException("arrays must be of the same length");
    int n = n1;
    GeneralPath path = new GeneralPath();
    path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0]));
    for (int i = 0; i < n; i++)
      path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i]));
    path.closePath();
    offscreen.draw(path);
    draw();
  }
  /**
   * Draws a polygon with the vertices
   * (x0, y0),
   * (x1, y1), ...,
   * (xn−1, yn−1).
   *
   * @param  x an array of all the x-coordinates of the polygon
   * @param  y an array of all the y-coordinates of the polygon
   * @throws IllegalArgumentException unless {@code x[]} and {@code y[]}
   *         are of the same length
   */
  public static void filledPolygon(double[] x, double[] y)
  {
    if (x == null)
      throw new NullPointerException();
    if (y == null)
      throw new NullPointerException();
    int n1 = x.length;
    int n2 = y.length;
    if (n1 != n2)
      throw new IllegalArgumentException("arrays must be of the same length");
    int n = n1;
    GeneralPath path = new GeneralPath();
    path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0]));
    for (int i = 0; i < n; i++)
      path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i]));
    path.closePath();
    offscreen.fill(path);
    draw();
  }
  private static Image getImageFromFile(String filename)
  {
    if (filename == null)
      throw new NullPointerException();
    ImageIcon icon = new ImageIcon(filename);
    if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE))
    {
      try
      {
        URL url = new URL(filename);
        icon = new ImageIcon(url);
      }
      catch (Exception e)
      {
      }
    }
    if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE))
    {
      // in case file is inside a .jar (classpath relative to StdDraw)
      URL url = StdDraw.class.getResource(filename);
      if (url != null)
        icon = new ImageIcon(url);
    }
    if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE))
    {
      // in case file is inside a .jar (classpath relative to root of jar)
      URL url = StdDraw.class.getResource("/" + filename);
      if (url == null)
        throw new IllegalArgumentException("image " + filename + " not found");
      icon = new ImageIcon(url);
    }
    return icon.getImage();
  }
  /**
   * Draws the specified image centered at (x, y).
   * The supported image formats are JPEG, PNG, and GIF.
   * As an optimization, the picture is cached, so there is no performance
   * penalty for redrawing the same image multiple times (e.g., in an animation).
   * However, if you change the picture file after drawing it, subsequent
   * calls will draw the original picture.
   *
   * @param  x the center x-coordinate of the image
   * @param  y the center y-coordinate of the image
   * @param  filename the name of the image/picture, e.g., "ball.gif"
   * @throws IllegalArgumentException if the image filename is invalid
   */
  public static void picture(double x, double y, String filename)
  {
    Image image = getImageFromFile(filename);
    double xs = scaleX(x);
    double ys = scaleY(y);
    int ws = image.getWidth(null);
    int hs = image.getHeight(null);
    if (ws < 0 || hs < 0)
      throw new IllegalArgumentException("image " + filename + " is corrupt");
    offscreen.drawImage(image, (int) Math.round(xs - ws / 2.0), (int) Math.round(ys - hs / 2.0), null);
    draw();
  }
  /**
   * Draws the specified image centered at (x, y),
   * rotated given number of degrees.
   * The supported image formats are JPEG, PNG, and GIF.
   *
   * @param  x the center x-coordinate of the image
   * @param  y the center y-coordinate of the image
   * @param  filename the name of the image/picture, e.g., "ball.gif"
   * @param  degrees is the number of degrees to rotate counterclockwise
   * @throws IllegalArgumentException if the image filename is invalid
   */
  public static void picture(double x, double y, String filename, double degrees)
  {
    Image image = getImageFromFile(filename);
    double xs = scaleX(x);
    double ys = scaleY(y);
    int ws = image.getWidth(null);
    int hs = image.getHeight(null);
    if (ws < 0 || hs < 0)
      throw new IllegalArgumentException("image " + filename + " is corrupt");
    offscreen.rotate(Math.toRadians(-degrees), xs, ys);
    offscreen.drawImage(image, (int) Math.round(xs - ws / 2.0), (int) Math.round(ys - hs / 2.0), null);
    offscreen.rotate(Math.toRadians(+degrees), xs, ys);
    draw();
  }
  /**
   * Draws the specified image centered at (x, y),
   * rescaled to the specified bounding box.
   * The supported image formats are JPEG, PNG, and GIF.
   *
   * @param  x the center x-coordinate of the image
   * @param  y the center y-coordinate of the image
   * @param  filename the name of the image/picture, e.g., "ball.gif"
   * @param  scaledWidth the width of the scaled image in pixels
   * @param  scaledHeight the height of the scaled image in pixels
   * @throws IllegalArgumentException if either {@code scaledWidth}
   *         or {@code scaledHeight} is negative
   * @throws IllegalArgumentException if the image filename is invalid
   */
  public static void picture(double x, double y, String filename, double scaledWidth, double scaledHeight)
  {
    Image image = getImageFromFile(filename);
    if (scaledWidth < 0)
      throw new IllegalArgumentException("width is negative: " + scaledWidth);
    if (scaledHeight < 0)
      throw new IllegalArgumentException("height is negative: " + scaledHeight);
    double xs = scaleX(x);
    double ys = scaleY(y);
    double ws = factorX(scaledWidth);
    double hs = factorY(scaledHeight);
    if (ws < 0 || hs < 0)
      throw new IllegalArgumentException("image " + filename + " is corrupt");
    if (ws <= 1 && hs <= 1)
      pixel(x, y);
    else
    {
      offscreen.drawImage(image, (int) Math.round(xs - ws / 2.0), (int) Math.round(ys - hs / 2.0),
          (int) Math.round(ws), (int) Math.round(hs), null);
    }
    draw();
  }
  /**
   * Draws the specified image centered at (x, y), rotated
   * given number of degrees, and rescaled to the specified bounding box.
   * The supported image formats are JPEG, PNG, and GIF.
   *
   * @param  x the center x-coordinate of the image
   * @param  y the center y-coordinate of the image
   * @param  filename the name of the image/picture, e.g., "ball.gif"
   * @param  scaledWidth the width of the scaled image in pixels
   * @param  scaledHeight the height of the scaled image in pixels
   * @param  degrees is the number of degrees to rotate counterclockwise
   * @throws IllegalArgumentException if either {@code scaledWidth}
   *         or {@code scaledHeight} is negative
   * @throws IllegalArgumentException if the image filename is invalid
   */
  public static void picture(double x, double y, String filename, double scaledWidth, double scaledHeight,
      double degrees)
  {
    if (scaledWidth < 0)
      throw new IllegalArgumentException("width is negative: " + scaledWidth);
    if (scaledHeight < 0)
      throw new IllegalArgumentException("height is negative: " + scaledHeight);
    Image image = getImageFromFile(filename);
    double xs = scaleX(x);
    double ys = scaleY(y);
    double ws = factorX(scaledWidth);
    double hs = factorY(scaledHeight);
    if (ws < 0 || hs < 0)
      throw new IllegalArgumentException("image " + filename + " is corrupt");
    if (ws <= 1 && hs <= 1)
      pixel(x, y);
    offscreen.rotate(Math.toRadians(-degrees), xs, ys);
    offscreen.drawImage(image, (int) Math.round(xs - ws / 2.0), (int) Math.round(ys - hs / 2.0),
        (int) Math.round(ws), (int) Math.round(hs), null);
    offscreen.rotate(Math.toRadians(+degrees), xs, ys);
    draw();
  }
  /**
   * Write the given text string in the current font, centered at (x, y).
   *
   * @param  x the center x-coordinate of the text
   * @param  y the center y-coordinate of the text
   * @param  text the text to write
   */
  public static void text(double x, double y, String text)
  {
    if (text == null)
      throw new NullPointerException();
    offscreen.setFont(font);
    FontMetrics metrics = offscreen.getFontMetrics();
    double xs = scaleX(x);
    double ys = scaleY(y);
    int ws = metrics.stringWidth(text);
    int hs = metrics.getDescent();
    offscreen.drawString(text, (float) (xs - ws / 2.0), (float) (ys + hs));
    draw();
  }
  /**
   * Write the given text string in the current font, centered at (x, y) and
   * rotated by the specified number of degrees.
   * @param  x the center x-coordinate of the text
   * @param  y the center y-coordinate of the text
   * @param  text the text to write
   * @param  degrees is the number of degrees to rotate counterclockwise
   */
  public static void text(double x, double y, String text, double degrees)
  {
    if (text == null)
      throw new NullPointerException();
    double xs = scaleX(x);
    double ys = scaleY(y);
    offscreen.rotate(Math.toRadians(-degrees), xs, ys);
    text(x, y, text);
    offscreen.rotate(Math.toRadians(+degrees), xs, ys);
  }
  /**
   * Write the given text string in the current font, left-aligned at (x, y).
   * @param  x the x-coordinate of the text
   * @param  y the y-coordinate of the text
   * @param  text the text
   */
  public static void textLeft(double x, double y, String text)
  {
    if (text == null)
      throw new NullPointerException();
    offscreen.setFont(font);
    FontMetrics metrics = offscreen.getFontMetrics();
    double xs = scaleX(x);
    double ys = scaleY(y);
    int hs = metrics.getDescent();
    offscreen.drawString(text, (float) xs, (float) (ys + hs));
    draw();
  }
  /**
   * Write the given text string in the current font, right-aligned at (x, y).
   *
   * @param  x the x-coordinate of the text
   * @param  y the y-coordinate of the text
   * @param  text the text to write
   */
  public static void textRight(double x, double y, String text)
  {
    if (text == null)
      throw new NullPointerException();
    offscreen.setFont(font);
    FontMetrics metrics = offscreen.getFontMetrics();
    double xs = scaleX(x);
    double ys = scaleY(y);
    int ws = metrics.stringWidth(text);
    int hs = metrics.getDescent();
    offscreen.drawString(text, (float) (xs - ws), (float) (ys + hs));
    draw();
  }
  public static void show(int t)
  {
    long millis = System.currentTimeMillis();
    if (millis < nextDrawInMS)
    {
      try
      {
        Thread.sleep(nextDrawInMS - millis);
      }
      catch (InterruptedException e)
      {
        System.out.println("Error sleeping");
      }
      millis = nextDrawInMS;
    }
    defer = false;
    draw();
    defer = true;
    nextDrawInMS = millis + t;
  }
  /**
   * Display on-screen and turn off animation mode:
   * subsequent calls to
   * drawing methods such as {@code line()}, {@code circle()},
   * and {@code square()} will be displayed on screen when called.
   * This is the default.
   */
  public static void show()
  {
    defer = false;
    nextDrawInMS = -1;
    draw();
  }
  private static void draw()
  {
    if (defer)
      return;
    onscreen.drawImage(offscreenImage, 0, 0, null);
    frame.repaint();
  }
  /**
   * Saves the drawing to using the specified filename.
   * The supported image formats are JPEG and PNG;
   * the filename suffix must be <tt>.jpg</tt> or <tt>.png</tt>.
   *
   * @param  filename the name of the file with one of the required suffixes
   */
  public static void save(String filename)
  {
    if (filename == null)
      throw new NullPointerException();
    File file = new File(filename);
    String suffix = filename.substring(filename.lastIndexOf('.') + 1);
    if (suffix.toLowerCase().equals("png"))
    {
      try
      {
        ImageIO.write(onscreenImage, suffix, file);
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }
    else if (suffix.toLowerCase().equals("jpg"))
    {
      WritableRaster raster = onscreenImage.getRaster();
      WritableRaster newRaster;
      newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[]{0, 1, 2});
      DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel();
      DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(), cm.getRedMask(), cm.getGreenMask(),
          cm.getBlueMask());
      BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null);
      try
      {
        ImageIO.write(rgbBuffer, suffix, file);
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }
    else
    {
      System.out.println("Invalid image file type: " + suffix);
    }
  }
  @Override
  public void actionPerformed(ActionEvent e)
  {
    FileDialog chooser = new FileDialog(StdDraw.frame, "Use a .png or .jpg extension", FileDialog.SAVE);
    chooser.setVisible(true);
    String filename = chooser.getFile();
    if (filename != null)
    {
      StdDraw.save(chooser.getDirectory() + File.separator + chooser.getFile());
    }
  }
  public static boolean isNextKeyTyped()
  {
    synchronized (keyLock)
    {
      return !keysTyped.isEmpty();
    }
  }
  /**
   * Returns the next key that was typed by the user (that your program has not already processed).
   * This method should be preceded by a call to {@link #isNextKeyTyped()} to ensure
   * that there is a next key to process.
   * This method returns a Unicode character corresponding to the key
   * typed (such as {@code 'a'} or {@code 'A'}).
   * It cannot identify action keys (such as F1 and arrow keys)
   * or modifier keys (such as control).
   *
   * @return the next key typed by the user (that your program has not already processed).
   * @throws NoSuchElementException if there is no remaining key
   */
  public static char nextKeyTyped()
  {
    synchronized (keyLock)
    {
      if (keysTyped
          .isEmpty()) { throw new NoSuchElementException("your program has already processed all keystrokes"); }
      return keysTyped.removeLast();
    }
  }
  /**
   * Returns true if the given key is being pressed.
   *

   * This method takes the keycode (corresponding to a physical key)
  *  as an argument. It can handle action keys
   * (such as F1 and arrow keys) and modifier keys (such as shift and control).
   * See {@link KeyEvent} for a description of key codes.
   *
   * @param  keycode the key to check if it is being pressed
   * @return <tt>true</tt> if {@code keycode} is currently being pressed;
   *         <tt>false</tt> otherwise
   */
  public static boolean isKeyPressed(int keycode)
  {
    synchronized (keyLock)
    {
      return keysDown.contains(keycode);
    }
  }
  @Override
  public void keyTyped(KeyEvent e)
  {
    synchronized (keyLock)
    {
      keysTyped.addFirst(e.getKeyChar());
    }
  }
  @Override
  public void keyPressed(KeyEvent e)
  {
    synchronized (keyLock)
    {
      keysDown.add(e.getKeyCode());
    }
  }
  @Override
  public void keyReleased(KeyEvent e)
  {
    synchronized (keyLock)
    {
      keysDown.remove(e.getKeyCode());
    }
  }
}


package org.teachingextensions.approvals.lite.util;

import java.io.PrintWriter;
import java.util.Vector;

/**
 * A class for printing comments in a standardized format.
 *
 * @author Llewellyn
 * @version 2.0
 */
public class MySystem {
    public static boolean event = true;
    public static boolean variable = true;
    public static int hourGlass = 0;
    private static long lastTime = System.currentTimeMillis();
    private static PrintWriter SYSTEM_OUT_WRITER = new PrintWriter(System.out, true);

    private static void clearHourGlass() {
        if (hourGlass > 0) {
            System.out.println("");
            hourGlass = 0;
        }
    }

    private static String getIndent() {

        return "";
    }

    private static String timeStamp() {
        clearHourGlass();
        String text;
        long current = System.currentTimeMillis();
        java.text.DateFormat df = java.text.DateFormat.getDateTimeInstance();
        text = "[" + df.format(new java.util.Date(current)) + " ~" + padNumber(current - lastTime) + "ms]"
                + getIndent();
        lastTime = current;
        return text;
    }

    private static String padNumber(long number) {
        String text = "" + number;
        while (text.length() < 6) {
            text = "0" + text;
        }
        return text;
    }

    private static String indentMessage(String message) {
        Vector<Integer> v = new Vector<>();
        int place = 0;
        while ((place = message.indexOf('\n', place + 1)) != -1) {
            v.addElement(place);
        }
        if (v.size() == 0) {
            // no '\n'
            return message;
        }
        String theIndention = getIndent();
        StringBuilder buffer = new StringBuilder(message);
        for (int i = (v.size() - 1); i >= 0; i--) {
            int template = v.elementAt(i);
            buffer.insert(template + 1, theIndention);
        }
        return buffer.toString();
    }

    /**
     * Prints to screen any variable information to be viewed.
     *
     * @param statement The statement to print
     */
    public synchronized static void variable(String statement) {
        variable(statement, SYSTEM_OUT_WRITER);
    }

    public synchronized static void variable(String statement, PrintWriter out) {
        if (!variable) {
            return;
        }
        out.println(timeStamp() + "*=>" + statement);
    }

    /**
     * Prints to screen any variable information to be viewed.
     *
     * @param name  The value's name
     * @param value The value to print
     */
    public synchronized static void variable(String name, Object value) {
        if (!variable) {
            return;
        }
        System.out.println(timeStamp() + "*=> " + name + " = '" + (value == null ? null : value.toString()) + "'");
    }

    /**
     * Prints to screen any messages to be viewed.
     *
     * @param Statement The statement to print
     */
    public synchronized static void message(String Statement) {
        System.out.println(timeStamp() + indentMessage(Statement));
    }

    /**
     * Prints to screen any events to be viewed.
     *
     * @param Statement The statement to print
     */
    public static void event(String Statement) {
        if (!event) {
            return;
        }
        System.out.println(timeStamp() + "*--" + Statement);
    }

    /**
     * Prints to screen any warnings to be viewed.
     *
     * @param statement The statement to print
     */
    public synchronized static void warning(String statement) {
        warning(statement, null);
    }

    /**
     * Prints to screen any warnings to be viewed.
     *
     * @param throwable The throwable to print
     */
    public synchronized static void warning(Throwable throwable) {
        warning(null, throwable);
    }

    /**
     * Prints to screen any warnings to be viewed.
     *
     * @param statement The statement to print
     * @param throwable A throwable instance with error information
     */
    public synchronized static void warning(String statement, Throwable throwable) {
        warning(statement, throwable, null);
    }

    public synchronized static void warning(String statement, Throwable throwable, PrintWriter out) {
        clearHourGlass();
        dualPrintln("******************************************************************************************", out);
        dualPrintln(timeStamp(), out);
        if (statement != null) {
            dualPrintln(statement, out);
        }
        printFullTrace(throwable, false, out);
        if (throwable instanceof OutOfMemoryError) {
            dumpMemory(out);
        }
        dualPrintln("******************************************************************************************", out);
    }

    private static void dualPrintln(String string, PrintWriter out) {
        System.out.println(string);
        if (out != null) {
            out.println(string);
        }
    }

    private static void printFullTrace(Throwable throwable, boolean causedBy, PrintWriter out) {
        if (throwable != null) {
            dualPrintln((causedBy ? "Caused by : " : "") + throwable.getMessage(), out);
            throwable.printStackTrace();
            if (out != null) {
                throwable.printStackTrace(out);
            }
            if (throwable.getCause() != null) {
                printFullTrace(throwable.getCause(), true, out);
            }
        }
    }

    public static void dumpMemory(PrintWriter out) {
        System.gc();
        java.text.NumberFormat format = java.text.NumberFormat.getNumberInstance();
        long freeMemory = Runtime.getRuntime().freeMemory();
        long totalMemory = Runtime.getRuntime().totalMemory();
        long usedMemory = totalMemory - freeMemory;
        String statement = "Memory [total, used, free] = [" + format.format(totalMemory) + " , "
                + format.format(usedMemory) + " , " + format.format(freeMemory) + "]";
        variable(statement, out);
    }
}