Questions
Modify the "spiral" method in the "DrawDemo" class so that a spiral appears in the center...

Modify the "spiral" method in the "DrawDemo" class so that a spiral appears in the center of the canvas. However, instead of displaying the lines as black, randomize the color of each line between Color.RED, Color.GREEN, and Color.BLUE (each line should be randomized, don't display a single color for the whole spiral).

import java.awt.Color;
import java.util.Random;
import java.awt.Dimension;

/**
* Class DrawDemo - provides some short demonstrations showing how to use the
* Pen class to create various drawings.
*
* @author Michael Kölling and David J. Barnes
* @version 2016.02.29
*/

public class DrawDemo
{
    private Canvas myCanvas;
    private Random random;

    /**
     * Prepare the drawing demo. Create a fresh canvas and make it visible.
     */
    public DrawDemo()
    {
        myCanvas = new Canvas("Drawing Demo", 500, 400);
        random = new Random();
    }

    /**
     * Draw a square on the screen.
     */
    public void drawSquare()
    {
        Pen pen = new Pen(320, 260, myCanvas);
        pen.setColor(Color.BLUE);

        square(pen);
    }

    /**
     * Draw a polygon with the given number of sides.
     * @param n The number of sides.
     */
    public void drawPolygon(int n)
    {
        Pen pen = new Pen(320, 260, myCanvas);
        pen.setColor(Color.MAGENTA);
        polygon(pen, n);
    }

    /**
     * Draw a wheel made of many squares.
     */
    public void drawWheel()
    {
        Pen pen = new Pen(250, 200, myCanvas);
        pen.setColor(Color.RED);

        for(int i=0; i<36; i++) {
            square(pen);
            pen.turn(10);
        }
    }
   
    /**
     * Draw a spiral.
     */
    public void drawSpiral()
    {
        Pen pen = new Pen(320, 260, myCanvas);
        pen.setColor(Color.BLACK);
        spiral(pen);
    }

    /**
     * Draw a square in the pen's color at the pen's location.
     */
    private void square(Pen pen)
    {
        for(int i = 0; i < 4; i++) {
            pen.move(100);
            pen.turn(90);
        }
    }

    /**
     * Draw a polygon with the given number of side
     * in the pen's color at the pen's location.
     * @param sides The number of sides.
     */
    private void polygon(Pen pen, int sides)
    {
        for(int i = 0; i < sides; i++) {
            pen.move(100);
            pen.turn(360 / sides);
        }
    }
   
    /**
     * Draw a spiral in the pen's color at the pen's location.
     */
    private void spiral(Pen pen)
    {       
        // Start in the middle.
        pen.penUp();
        Dimension size = myCanvas.getSize();
        pen.moveTo(size.width / 2, size.height / 2);
        // Face downwards.
        pen.turnTo(90);
        pen.penDown();
    }

    /**
     * Draw some random squiggles on the screen, in random colors.
     */
    public void colorScribble()
    {
        Pen pen = new Pen(250, 200, myCanvas);

        for (int i=0; i<10; i++) {
            // pick a random color
            int red = random.nextInt(256);
            int green = random.nextInt(256);
            int blue = random.nextInt(256);
            pen.setColor(new Color(red, green, blue));
           
            pen.randomSquiggle();
        }
    }
   
    /**
     * Clear the screen.
     */
    public void clear()
    {
        myCanvas.erase();
    }
}

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

/**
* Class Canvas - a class to allow for simple graphical
* drawing on a canvas.
*
* @author Michael Kölling (mik)
* @author Bruce Quig
*
* @version 2016.02.29
*/

public class Canvas
{
    private JFrame frame;
    private CanvasPane canvas;
    private Graphics2D graphic;
    private Color backgroundColor;
    private Image canvasImage;

    /**
     * Create a Canvas with default height, width and background color
     * (300, 300, white).
     * @param title title to appear in Canvas Frame    
     */
    public Canvas(String title)
    {
        this(title, 300, 300, Color.white);
    }

    /**
     * Create a Canvas with default background color (white).
     * @param title title to appear in Canvas Frame
     * @param width the desired width for the canvas
     * @param height the desired height for the canvas
     */
    public Canvas(String title, int width, int height)
    {
        this(title, width, height, Color.white);
    }

    /**
     * Create a Canvas.
     * @param title title to appear in Canvas Frame
     * @param width the desired width for the canvas
     * @param height the desired height for the canvas
     * @param bgClour the desired background color of the canvas
     */
    public Canvas(String title, int width, int height, Color bgColor)
    {
        frame = new JFrame();
        canvas = new CanvasPane();
        frame.setContentPane(canvas);
        frame.setTitle(title);
        canvas.setPreferredSize(new Dimension(width, height));
        backgroundColor = bgColor;
        frame.pack();
        setVisible(true);
    }

    /**
     * Set the canvas visibility and brings canvas to the front of screen
     * when made visible. This method can also be used to bring an already
     * visible canvas to the front of other windows.
     * @param visible boolean value representing the desired visibility of
     * the canvas (true or false)
     */
    public void setVisible(boolean visible)
    {
        if(graphic == null) {
            // first time: instantiate the offscreen image and fill it with
            // the background color
            Dimension size = canvas.getSize();
            canvasImage = canvas.createImage(size.width, size.height);
            graphic = (Graphics2D)canvasImage.getGraphics();
            graphic.setColor(backgroundColor);
            graphic.fillRect(0, 0, size.width, size.height);
            graphic.setColor(Color.black);
        }
        frame.setVisible(true);
    }

    /**
     * Provide information on visibility of the Canvas.
     * @return true if canvas is visible, false otherwise
     */
    public boolean isVisible()
    {
        return frame.isVisible();
    }

    /**
     * Draw the outline of a given shape onto the canvas.
     * @param shape the shape object to be drawn on the canvas
     */
    public void draw(Shape shape)
    {
        graphic.draw(shape);
        canvas.repaint();
    }

    /**
     * Fill the internal dimensions of a given shape with the current
     * foreground color of the canvas.
     * @param shape the shape object to be filled
     */
    public void fill(Shape shape)
    {
        graphic.fill(shape);
        canvas.repaint();
    }

    /**
     * Fill the internal dimensions of the given circle with the current
     * foreground color of the canvas.
     * @param xPos The x-coordinate of the circle center point
     * @param yPos The y-coordinate of the circle center point
     * @param diameter The diameter of the circle to be drawn
     */
    public void fillCircle(int xPos, int yPos, int diameter)
    {
        Ellipse2D.Double circle = new Ellipse2D.Double(xPos, yPos, diameter, diameter);
        fill(circle);
    }

    /**
     * Fill the internal dimensions of the given rectangle with the current
     * foreground color of the canvas. This is a convenience method. A similar
     * effect can be achieved with the "fill" method.
     */
    public void fillRectangle(int xPos, int yPos, int width, int height)
    {
        fill(new Rectangle(xPos, yPos, width, height));
    }

    /**
     * Erase the whole canvas.
     */
    public void erase()
    {
        Color original = graphic.getColor();
        graphic.setColor(backgroundColor);
        Dimension size = canvas.getSize();
        graphic.fill(new Rectangle(0, 0, size.width, size.height));
        graphic.setColor(original);
        canvas.repaint();
    }

    /**
     * Erase the internal dimensions of the given circle. This is a
     * convenience method. A similar effect can be achieved with
     * the "erase" method.
     */
    public void eraseCircle(int xPos, int yPos, int diameter)
    {
        Ellipse2D.Double circle = new Ellipse2D.Double(xPos, yPos, diameter, diameter);
        erase(circle);
    }

    /**
     * Erase the internal dimensions of the given rectangle. This is a
     * convenience method. A similar effect can be achieved with
     * the "erase" method.
     */
    public void eraseRectangle(int xPos, int yPos, int width, int height)
    {
        erase(new Rectangle(xPos, yPos, width, height));
    }

    /**
     * Erase a given shape's interior on the screen.
     * @param shape the shape object to be erased
     */
    public void erase(Shape shape)
    {
        Color original = graphic.getColor();
        graphic.setColor(backgroundColor);
        graphic.fill(shape);              // erase by filling background color
        graphic.setColor(original);
        canvas.repaint();
    }

    /**
     * Erases a given shape's outline on the screen.
     * @param shape the shape object to be erased
     */
    public void eraseOutline(Shape shape)
    {
        Color original = graphic.getColor();
        graphic.setColor(backgroundColor);
        graphic.draw(shape); // erase by drawing background color
        graphic.setColor(original);
        canvas.repaint();
    }

    /**
     * Draws an image onto the canvas.
     * @param image   the Image object to be displayed
     * @param x       x co-ordinate for Image placement
     * @param y       y co-ordinate for Image placement
     * @return returns boolean value representing whether the image was
     *          completely loaded
     */
    public boolean drawImage(Image image, int x, int y)
    {
        boolean result = graphic.drawImage(image, x, y, null);
        canvas.repaint();
        return result;
    }

    /**
     * Draws a String on the Canvas.
     * @param text   the String to be displayed
     * @param x      x co-ordinate for text placement
     * @param y      y co-ordinate for text placement
     */
    public void drawString(String text, int x, int y)
    {
        graphic.drawString(text, x, y);  
        canvas.repaint();
    }

    /**
     * Erases a String on the Canvas.
     * @param text     the String to be displayed
     * @param x        x co-ordinate for text placement
     * @param y        y co-ordinate for text placement
     */
    public void eraseString(String text, int x, int y)
    {
        Color original = graphic.getColor();
        graphic.setColor(backgroundColor);
        graphic.drawString(text, x, y);  
        graphic.setColor(original);
        canvas.repaint();
    }

    /**
     * Draws a line on the Canvas.
     * @param x1   x co-ordinate of start of line
     * @param y1   y co-ordinate of start of line
     * @param x2   x co-ordinate of end of line
     * @param y2   y co-ordinate of end of line
     */
    public void drawLine(int x1, int y1, int x2, int y2)
    {
        graphic.drawLine(x1, y1, x2, y2);  
        canvas.repaint();
    }

    /**
     * Sets the foreground color of the Canvas.
     * @param newColor   the new color for the foreground of the Canvas
     */
    public void setForegroundColor(Color newColor)
    {
        graphic.setColor(newColor);
    }

    /**
     * Returns the current color of the foreground.
     * @return   the color of the foreground of the Canvas
     */
    public Color getForegroundColor()
    {
        return graphic.getColor();
    }

    /**
     * Sets the background color of the Canvas.
     * @param newColor   the new color for the background of the Canvas
     */
    public void setBackgroundColor(Color newColor)
    {
        backgroundColor = newColor;  
        graphic.setBackground(newColor);
    }

    /**
     * Returns the current color of the background
     * @return   the color of the background of the Canvas
     */
    public Color getBackgroundColor()
    {
        return backgroundColor;
    }

    /**
     * changes the current Font used on the Canvas
     * @param newFont   new font to be used for String output
     */
    public void setFont(Font newFont)
    {
        graphic.setFont(newFont);
    }

    /**
     * Returns the current font of the canvas.
     * @return     the font currently in use
     **/
    public Font getFont()
    {
        return graphic.getFont();
    }

    /**
     * Sets the size of the canvas.
     * @param width    new width
     * @param height   new height
     */
    public void setSize(int width, int height)
    {
        canvas.setPreferredSize(new Dimension(width, height));
        Image oldImage = canvasImage;
        canvasImage = canvas.createImage(width, height);
        graphic = (Graphics2D)canvasImage.getGraphics();
        graphic.setColor(backgroundColor);
        graphic.fillRect(0, 0, width, height);
        graphic.drawImage(oldImage, 0, 0, null);
        frame.pack();
    }

    /**
     * Returns the size of the canvas.
     * @return     The current dimension of the canvas
     */
    public Dimension getSize()
    {
        return canvas.getSize();
    }

    /**
     * Waits for a specified number of milliseconds before finishing.
     * This provides an easy way to specify a small delay which can be
     * used when producing animations.
     * @param milliseconds the number
     */
    public void wait(int milliseconds)
    {
        try
        {
            Thread.sleep(milliseconds);
        }
        catch (InterruptedException e)
        {
            // ignoring exception at the moment
        }
    }

    /************************************************************************
     * Inner class CanvasPane - the actual canvas component contained in the
     * Canvas frame. This is essentially a JPanel with added capability to
     * refresh the image drawn on it.
     */
    private class CanvasPane extends JPanel
    {
        public void paint(Graphics g)
        {
            g.drawImage(canvasImage, 0, 0, null);
        }
    }
}

import java.awt.Color;
import java.util.Random;

/**
* A pen can be used to draw on a canvas. The pen maintains a position, direction, color,
* and an up/down state. The pen can be moved across the canvas. If the pen is down, it
* leaves a line on the canvas when moved. (If it is up, it will not draw a line.)
*
* @author Michael Kölling & David J. Barnes
* @version 2016.02.29
*/
public class Pen
{
    // constants for randomSquiggle method
    private static final int SQIGGLE_SIZE = 40;
    private static final int SQIGGLE_COUNT = 30;
   
    private int xPosition;
    private int yPosition;
    private int rotation;
    private Color color;
    private boolean penDown;

    private Canvas canvas;
    private Random random;

    /**
     * Create a new Pen with its own canvas. The pen will create a new canvas for
     * itself to draw on, and start in the default state (centre of canvas, direction
     * right, color black, pen down).
     */
    public Pen()
    {
        this (280, 220, new Canvas("My Canvas", 560, 440));
    }

    /**
     * Create a new Pen for a given canvas. The direction is initially 0 (to the right),
     * the color is black, and the pen is down.
     *
     * @param xPos the initial horizontal coordinate of the pen
     * @param yPos the initial vertical coordinate of the pen
     * @param drawingCanvas the canvas to draw on
     */
    public Pen(int xPos, int yPos, Canvas drawingCanvas)
    {
        xPosition = xPos;
        yPosition = yPos;
        rotation = 0;
        penDown = true;
        color = Color.BLACK;
        canvas = drawingCanvas;
        random = new Random();
    }

    /**
     * Move the specified distance in the current direction. If the pen is down,
     * leave a line on the canvas.
     *
     * @param distance The distance to move forward from the current location.
     */
    public void move(int distance)
    {
        double angle = Math.toRadians(rotation);
        int newX = (int) Math.round(xPosition + Math.cos(angle) * distance);
        int newY = (int) Math.round(yPosition + Math.sin(angle) * distance);
       
        moveTo(newX, newY);
    }

    /**
     * Move to the specified location. If the pen is down, leave a line on the canvas.
     *
     * @param x   The x-coordinate to move to.
     * @param y   The y-coordinate to move to.
     */
    public void moveTo(int x, int y)
    {
        if (penDown) {
            canvas.setForegroundColor(color);
            canvas.drawLine(xPosition, yPosition, x, y);
        }

        xPosition = x;
        yPosition = y;
    }

    /**
     * Turn the specified amount (out of a 360 degree circle) clockwise from the current
     * rotation.
     *
     * @param degrees The amount of degrees to turn. (360 is a full circle.)
     */
    public void turn(int degrees)
    {
        rotation = rotation + degrees;
    }

    /**
     * Turn to the specified direction. 0 is right, 90 is down, 180 is left, 270 is up.
     *
     * @param angle The angle to turn to.
     */
    public void turnTo(int angle)
    {
        rotation = angle;
    }

    /**
     * Set the drawing color.
     *
     * @param newColor The color to use for subsequent drawing operations.
     */
    public void setColor(Color newColor)
    {
        color = newColor;
    }

    /**
     * Lift the pen up. Moving afterwards will not leave a line on the canvas.
     */
    public void penUp()
    {
        penDown = false;
    }

    /**
     * Put the pen down. Moving afterwards will leave a line on the canvas.
     */
    public void penDown()
    {
        penDown = true;
    }

    /**
     * Scribble on the canvas in the current color. The size and complexity of the
     * squiggle produced is defined by the constants SQIGGLE_SIZE and SQIGGLE_COUNT.
     */
    public void randomSquiggle()
    {
        for (int i=0; i<SQIGGLE_COUNT; i++) {
            move(random.nextInt(SQIGGLE_SIZE));
            turn(160 + random.nextInt(40));
        }

    }

}

In: Computer Science

Wilson Car Repair must record information about customer’s vehicles that are coming in for repair. A...

Wilson Car Repair must record information about customer’s vehicles that are coming in for repair. A program is needed to record the customer name, phone number, Type of work done, type of car, the number of labor hours, and the total amount for the parts, and a grand total amount for the repair of the vehicle. A 10% discount will be given if paid in cash. If the customer is a member of the “Wilson Car Repair Savings Club,” they get a 20% discount. You can adjust this project in any way you want. Just make sure you are doing some calculations.

You can adjust this project in any way you want.

You can make it easier or more challenging. Just make sure you are doing some calculations.

Be sure to submit an IPO along with your input screen and your output screen. You can draw screens or use Visio to make them.

In: Computer Science

In python, how do you move the pointer of a doubly linked list to the last...

In python, how do you move the pointer of a doubly linked list to the last node? Also in python, how do you move the current pointer "n" elements ahead (circularly)


def go_last(self):
# moves 'current' pointer to the last node


def skip(self,n:int):
# moves 'current' pointer n elements ahead (circularly)

In: Computer Science

Write a Matlab script which creates two vectors from the table below; pne vector for the...

Write a Matlab script which creates two vectors from the table below; pne vector for the element names and a second for element atomic numbers. Print the statement "[element name] has an odd atomic number: [element atomic number]." for each element with an odd atomic number.

Element Atomic Number
Gold 79
Carbon 6
Hydrogen 1
Oxygen 8
Sodium 11
  • Use a for loop.
  • Use a if statement.
  • Print one statement per line.
  • Use the mod function when testing for odd atomic numbers.

In: Computer Science

Give three examples of functional requirements?

Give three examples of functional requirements?

In: Computer Science

In C# please Exercise #4: Create a two (2) instances of the “Dog” class in your...

In C# please

Exercise #4:

Create a two (2) instances of the “Dog” class in your “Main” method. One will be created using the default constructor and the other should be made using the overloaded constructor. That means that you should pass the overloaded constructor arguments that come from user input.

Print out each of the dog’s three attributes using the accessors. Then call the “UpdateBark” method for both and print out their fields again, but this time through the “ToString” method.

Example (blue is default dog’s attributes, green is the user’s dog’s):

Creating a default dog…

Finished creating a default dog!

Default dog bark sound is Yelp!

Default dog size is 20 inches.

Default dog’s cuteness is cute dog.

Continued on third page…

Please enter the sound of your dog’s bark: “MOOOOOO!”

Please enter the size of your dog: “10”

Please enter the cuteness of your dog: “ugly dog.”

Your dog bark sound is MOOOOOO!

Your dog size is 10 inches.

Your dog’s cuteness is ugly dog.

Both dogs are doing a scary bark! Their cuteness has been affected!

Default dog bark sound is Yelp!

Default dog size is 20 inches.

Default dog’s cuteness is average.

Your dog bark sound is MOOOOOO!

Your dog size is 10 inches.

Your dog’s cuteness is average.

In: Computer Science

You mission is create a C# program with the following. 1. At the top center of...

You mission is create a C# program with the following. 1. At the top center of the page is a title which displays your name - use a label. a. adjust the font size from the default to a bigger size. b. adjust the font color to a different color than the default c. name the label using a naming convention shown in the chapter. Use this same format for all of your objects. 2. Below the title, centered, place a picture of yourself using the picturebox tool explained in the chapter. a. name the picture box with a meaningful name using the naming convention you used in #1. b. size the picture to fit evenly under your title. c. make sure the picture is properly saved in the right location within the C# application or it won't be copied when you submit the assignment. Do not code a complete location like c:/myfiles .... I won't have the same folders as you. It has to reside in the proper images folder which is located with your other program files. 3. Create TWO buttons on the same line (row) as each other. They should be evenly spaced apart from each other..Same space between the left edge, center, and right edge. a. Give each button a meaningful name using the naming convention you used for #1. b. The left button should display (within the button itself), the words - my favorite quote. c. The right button should display (within the button itself), the words - what I do for fun. 4. Double click the left button. You should now be in the code area for the click event for this button. a. Create the code (only takes one line) to display your favorite quote when the button is clicked. 5. Double click the right button. You should now be in the code area for the click event for this button. a. Create the code (only takes one line) to display a statement about what you do for fun. 6. Place another button below the two buttons, centered under the picture. a. Name the button with a meaningful name using the naming convention you used in #1. b. The words inside the button will be - close program c. Double click the button to enter code under the button. d. Enter a line of code which will display something funny about the person leaving your program. e. Enter a second line of code which closes the program. Test, Test, Test! Make sure it works. I will be testing your program!

In: Computer Science

Can't seem to get the program working. I have the same program as a friend, but...

Can't seem to get the program working. I have the same program as a friend, but mine says void getNextWord fuction not found. I need getNextWord fuction Any Help would be great.


#include <iostream>
#include <fstream>
#include <string>

using namespace std;
bool isPunct(char);
bool isVowel(char ch);
string rotate(string pStr, string::size_type len);
string pigLatinString(string pStr);

void getNextWord(ifstream& inf, char& ch, string& word);
//global declaration
int main()
{
   string str;
   //declaration

   char ch;

   ifstream infile;
   ofstream outfile;

   //input
   infile.open("Sentence.txt");
   if (!infile) {
       cout << "Cannot open input file. Program terminates." << endl;
       return 1;
   }

   outfile.open("Piglatin.txt");

   infile.get(ch);

   while (infile) {

       while (ch != '\n' && infile) {
           if (ch == ' ') {
               outfile << ch;
               infile.get(ch);
           }
           else {
               getNextWord(infile, ch, str);
               outfile << pigLatinString(str);
           }
       }

       outfile << endl;
       infile.get(ch);
   }
   infile.close();
   outfile.close();

   return 0;
}
bool isVowel(char ch)
{
   cout << "in isvowel()" << endl;
   bool isV = false;

   switch (ch) {
   case 'A': case 'a':
   case 'I': case 'i':
   case 'U': case 'u':
   case 'E': case 'e':
   case 'O': case 'o':
   case 'Y': case 'y':

       isV = true;
       break;
   default:

       isV = false;

   }
   return isV;

}
bool isPunct(char ch)
{
   cout << "in isPunct()" << endl;
   bool isP = false;
   switch (ch)
   {
   case ',':
   case '?':
   case '.':
   case ';':
   case ':':
   case '!':
       isP = true;
       break;
   default:
       isP = false;
   }
   return isP;
}

string rotate(string pStr, string::size_type len)
{
   cout << "in rotate()" << endl;
   string rStr;

   rStr = pStr.substr(1, len - 1) + pStr[0];

   return rStr;
}

string pigLatinString(string pStr)
{
   string::size_type len = pStr.length();
   bool foundVowel; //done = false;

   bool isPunctuation = isPunct(pStr[len - 1]);
   char puncMark;


   string::size_type counter;//loop counter

   if (isPunctuation) {
       puncMark = pStr[len - 1];
       len -= 1;

   }

   if (isVowel(pStr[0])) {
       pStr = pStr.substr(0, len) + "-way";
   }
   else
   {
      
       pStr = pStr.substr(0, len) + '-';
       pStr = rotate(pStr, len);
       len = pStr.length();
       foundVowel = false;

       for (counter = 1; counter < len - 1; counter++)
       {
           if (isVowel(pStr[0]))
           {
               foundVowel = true;
               break;

           }
           else {
               pStr = rotate(pStr, len);
           }
       }
       cout << "line 157: " << pStr;
       if (!foundVowel) {
           pStr = pStr.substr(1, len) + "-way";
       }
       else {
           pStr += "ay";
           //pStr = pStr + "ay";
       }
       cout << "line 165: " << pStr << endl;
   }
   if (isPunctuation) {
       pStr = pStr + puncMark;
   }
   cout << "line 170: " << pStr << endl;
   return pStr;
  
}

In: Computer Science

Q: Assistance in understanding and solving this example from Data Structure & Algorithms (Computer Science) with...

Q: Assistance in understanding and solving this example from Data Structure & Algorithms (Computer Science) with the steps of the solution to better understand, thanks.

##Using R studio language and code to use provided below, thanks.

In this assignment, we will implement a function to evaluate an arithmetic expression. You will use two stacks to keep track of things. The function is named ‘evaluate’, it takes a string as input parameter, and returns an integer. The input string represents an arithmetic expression, with each character in the string being a token, while the returned value should be the value of the expression.

Examples:

• evaluate ('1+2*3') ➔ 7

• evaluate ('1*2+3') ➔ 5

##This is the code provided to use

"""Basic example of an adapter class to provide a stack interface to

Python's list."""

class ArrayStack:

"""LIFO Stack implementation using a Python list as underlying

storage."""

def __init__ (self):

"""Create an empty stack."""

self._data = [] # nonpublic list instance

def __len__ (self):

"""Return the number of elements in the stack."""

return len (self._data)

def is_empty (self):

"""Return True if the stack is empty."""

return len (self._data) == 0

def push (self, e):

"""Add element e to the top of the stack."""

self._data.append (e) # new item stored at end of

list

def top (self):

"""Return (but do not remove) the element at the top of the stack.

Raise Empty exception if the stack is empty.

"""

if self.is_empty ():

raise Empty ('Stack is empty')

return self._data [-1] # the last item in the list

def pop (self):

"""Remove and return the element from the top of the stack (i.e.,

LIFO).

Raise Empty exception if the stack is empty.

"""

if self.is_empty ():

raise Empty ('Stack is empty')

return self._data.pop () # remove last item from list

class Empty (Exception):

"""Error attempting to access an element from an empty container."""

pass

if __name__ == '__main__':

S = ArrayStack () # contents: [ ]

S.push (5) # contents: [5]

S.push (3) # contents: [5, 3]

print (len (S)) # contents: [5, 3]; outputs 2

print (S.pop ()) # contents: [5]; outputs 3

print (S.is_empty ()) # contents: [5]; outputs False

print (S.pop ()) # contents: [ ]; outputs 5

print (S.is_empty ()) # contents: [ ]; outputs True

S.push (7) # contents: [7]

S.push (9) # contents: [7, 9]

print (S.top ()) # contents: [7, 9]; outputs 9

S.push (4) # contents: [7, 9, 4]

print (len (S)) # contents: [7, 9, 4]; outputs 3

print (S.pop ()) # contents: [7, 9]; outputs 4

S.push (6) # contents: [7, 9, 6]

S.push (8) # contents: [7, 9, 6, 8]

print (S.pop ()) # contents: [7, 9, 6]; outputs 8


In: Computer Science

What is the difference between cost variance and schedule variance? Describe the four performance indexes mentioned...

  1. What is the difference between cost variance and schedule variance?
  2. Describe the four performance indexes mentioned ?
  3. Define control schedule process, list the control schedule inputs, and list the control schedule tools and techniques

please good answer

In: Computer Science

two techniques for implementing a top-down parser: a recursive descent parser and a table-driven parser. a.What...

two techniques for implementing a top-down parser: a recursive descent parser and a table-driven parser.

a.What are the advantages of writing a recursive descent parser instead of a table-driven parser?

b.What are the disadvantages of recursive descent?

In: Computer Science

10)A famous example of illustrating the importance of looking beyond the mean (or average) of a...

10)A famous example of illustrating the importance of looking beyond the mean (or average) of a data set to understand the data is ______ .


A) Exploratory data analysis


B) Anscombe's quartet


C) Infographics


D) Visualization of Napoleon's march on Moscow

please provide the reason why you are choosing an option to be right. its for my understanding . and also why other options are not right

expecting an early response.will rate your answer. thankyou

In: Computer Science

Car class Question Design a class named car that has the following fields: YearModel: The yearModel...

Car class Question

Design a class named car that has the following fields: YearModel: The yearModel field is an integer that holds the car's year model. Make: The make field references a string that holds the make of the car. Speed: The speed field is an integer that holds the car's current speed. In addition, the class should have the following constructor and other methods: Constructor: The constructor should accept the. car's year model and make as arguments. The values should be assigned to the object's yearModel and make fields. The constructor should also assign 0 to the speed field. Accessors: Design appropriate accessor methods to get the values stored in an object's yearModel, make, and speed fields. Accelerate: The accelerate method should add 5 to the speed field each time it is called. Brake: The brake method should subtract 5 from the speed field each time it is called. Next, design a program that creates a car object, and then cals the accelerate method fibe times. After each call to the accelerate method, get the current speed of the car and display it. Then call the brake method 5 times. After each call to the brake method, get the current speed of the car and display it..........

Thanks for the help guys pseudocode and flowchart please

In: Computer Science

c++ 1. write a c++ function that received two doubles that represent the sides of a...

c++

1. write a c++ function that received two doubles that represent the sides of a triangle and an integer that represents the number of triangles of that size. calculate the area of all these triangles. remember area of a triangle is ahalf base times width. and return this value as a double.

In: Computer Science

Write a Java program to convert octal (integer) numbers into their decimal number equivalents (exactly the...

Write a Java program to convert octal (integer) numbers into their decimal number equivalents (exactly the opposite of what you have done in Assignment 4). Make sure that you create a new Project and Java class file for this assignment. Your file should be named “Main.java”. You can read about octal-to-decimal number conversions on wikepedia

Assignment 4 is at the bottom

Objective

Your program should prompt the user to enter a number of no greater than 8 digits. If the user enters a number greater than 8 digits or a value less than 0, it should re-prompt the user to enter a number again*. You do not need to check if the digits are valid octal numbers (0-7), as this is guaranteed.

Instructions

  • Note that the conversion logic should be in a separate method (not the main() method).
  • main() method will take the input from the user and pass it to the conversion() method.
  • The conversion() method will convert the input octal to decimal and print the output.
    • No return value is required.
    • a sample structure is shown below.
  • Use a sentinel while loop to solve the problem.
  • Ideally, you should copy your assignment 4 code here and modify it to serve the new purpose. This will save you time.
  • USE ONLY INTEGER VARIABLES FOR INPUTS AND OUTPUTS.
  • USE ONLY THE TECHNIQUES TAUGHT IN CLASS

main(){

int oct = user input;

conversion(oct);

}

void conversion(int o){

// logic goes here.

print(decimal);

}

Goals

  • more experience in WHILE loop.
  • experience in Java Methods
  • logical thinking

Sample Runs

Sample Program Run (user input is underlined)

Enter up to an 8-digit octal number and I will convert it for you: 77777777

16777215

Sample Program Run (user input is underlined)

Enter up to an 8-digit octal number and I will convert it for you: 775002

260610

Sample Program Run (user input is underlined)

Enter up to an 8-digit octal number and I will convert it for you: 0

0

Sample Program Run (user input is underlined)

Enter up to an 8-digit octal number and I will convert it for you: 55

45

Sample Program Run (user input is underlined)

Enter up to an 8-digit octal number and I will convert it for you: 777777777

Enter up to an 8-digit octal number and I will convert it for you: 777777777

Enter up to an 8-digit octal number and I will convert it for you: 700000000

Enter up to an 8-digit octal number and I will convert it for you: 77

63

Assignment 4:

// Main.java : Java program to convert decimal number to octal

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

int inputNum, convertedNum;

Scanner scan = new Scanner(System.in);

// Input of integer number in decimal

System.out.print("Please enter a number between 0 and 2097151 to convert: ");

inputNum = scan.nextInt();

// validate the number

if(inputNum < 0 || inputNum > 2097151)

System.out.println("UNABLE TO CONVERT");

else

{

int weight=0; // weight of the digit, used for converting to octal

convertedNum = 0; // variable to store the number in octal

int temp = inputNum;

int digit;

// loop that continues till we convert the entire number to octal

while(temp > 0)

{

digit = (temp%8); // get the remainder when the number is divided by 8

// multiply the digit with its weight and add it to convertedNum

convertedNum += digit*Math.pow(10, weight);

temp = temp/8; // remove the last digit from the number

weight++; // increment the weight

}

// display the integer in octal

System.out.printf("Your integer number " + inputNum + " is %07d in octal",convertedNum);

}

scan.close();

}

}

In: Computer Science