## CSE 131 Module 4: Input & Output

Important!

Before beginning any work, do a Team...Pull in your repository.

## Extension 1: Create an Instrument (6 points):

Authors
We have seen how sound can be represented as a summation of sine waves. In this extension, you will process a description of an instrument, which specifies the relative intensities of that instruments overtones. You will modify a copy of PlayThatTune so that the sound emitted for each note has the profile of the specified instrument.

#### Warm Up

• Update your repository and locate the instrument package in the extensions folder.
• You will find a copy of PlayThatTune in the instrument package, credited to Sedgewick's book, as this code is adpated from Sedgewick's PlayThatTune.
• Run PlayThatTune and verify that it plays the music files correctly.

#### Overview

• For the purposes of this work, let's define a frequency factor as a multiplicative factor to be applied to a frequency f:
In the example below, let's assume that f is 440 Hz (cycles per second), which is concert A. On a piano, this is the A above middle C:
• a factor of 1 results in the same frequency as f, because 1*f==f.
• a factor of 2 yields a frequency an octave higher than f.

For this example, we obtain 880 Hz, which is the A above high C on a piano:

• a factor of 4 yields a frequency two octaves higher than f.

Here we obtain 1760 Hz, an octave above the A above high C:

• a factor of 3 is between one and two octaves higher, and it turns out to be one octave plus a just (or, pure) fifth above the pitch corresponding to f. Here we obtain the frequency 1320 Hz, which sounds like the E above high C.
The sound is slightly different than on a piano, where the pitches are not perfect but are instead evenly spaced apart from each other. The corresponding note on the piano has a frequency of 1318.51 Hz, slightly flatter than what we get by our frequency factor.
• a factor of 0.75 (ratio of 3:4) yields a note that sounds like an E, but dividing by 4 lowers its pitch by two octaves. With f at concert A, a frequency factor of 3:4 yields a frequency of 330, whichsounds like the E above middle C:
Again, the pitch on a piano is slightly different; in this case it is slightly flatter at 329.63.
• It is thus convenient to specify a frequency factor as the ratio of two integers. In the above examples we see 1:1, 2:1, 4:1, 3:1, and 3:4.
• To build an actual instrument, we must pick the frequency factors we wish to hear, and specify how strong each should be. The table below specifies such an instrument:
Frequency Factor Relative
Numerator Denominator Strength
1 1 1
2 1 0.75
3 2 0.50
The first row is the fundamental frequency. The second is an octave higher, and is 3/4 as strong as the fundamental frequency. The third row specifies a pitch that is a fifth above the fundamental freqnecy, and quieter still at half the strength of the fundamental frequency.

The waveform that results from such an instrument specification is shown below in red, with the three frequency factors shown in black:

• The red solid waveform is literally the sum of the black dotted waveforms. The sound you produce is sampled from the red waveform, and that is the subject of this extension.
• The plot shown above is not the subject of this extension, but is shown to help explain how complex sounds are built from simple ones, as follows:
• The black waveform with the largest amplitude (the tallest black waveform) is the fundamental frequency at relative strength 1. The sample shown is for 1/440 of a second of a 440 Hz concert-A. This is sufficient ot show one full cycle of the fundamental frequency.
• The black waveform with the next largest amplitude has relative strength 0.75. It is an octave higher, so it oscillates twice in the timespan of the fundamental pitch's waveform.
• The black waveform of smallest amplitude (at half the strength of the fundamental frequency) is the 3:2 frequency factor, which sounds like a fifth above the fundamental frequency. As expected, it exhibits 1.5 cycles in the timespan of the fundamental pitch's waveform.
• The sound of the red waveform, which is what you will produce below, is similar to an oboe or a clarinet (in the opinion of my son).

#### Procedure

1. First prompt the user for how many frequency factors the user wishes to specify. In the above example, 3 such frequencies were used.
2. For each frequency factor, prompt the user for its
• Numerator (an int)
• Denominator (an int)
• Relative strength (a double)
The information about the frequency factors must be saved (in arrays) for future use.
3. The code in PlayThatTune, copied with attribution from PlayThatTune, reads in a file and computes a value in a variable called hz that is the fundamental frequency of the tune being played.
The hz value is computed from concert A (440 Hz), taking the specified number of equally spaced chromatic steps above (or below) concert A.

The relevant details, explained in the lecture slides for this module, are not necessary to complete this extension, but please ask if you would like clarification.

4. Your task is to modify the assignment to the sample a[i] in the provided code:
The sine wave sampled and assigned there is for:
• the fundamental frequency (hz, shown in the red box) of the desired pitch
• relative strength 1.0 (the result of the sine function call is implicitly multiplied by 1, shown at the red dot).

In place of that value, you must compute the sum of sine wave samples, one for each frequency factor, as follows:

• a[i] is initially zero.
• For each frequency factor fk, add to a[i] a sample obtained as follows:
• The value passed to the sine function must be multiplied by the frequency factor. This means multiplying the red-boxed hz by the ratio of the numerator and denominator of the frequency factor.
• The value returned from the sine function must be multiplied by the relative strength of the frequency factor. This happens at the red dot.
5. Test your program on the A.txt file first, which is a single note. Then try Ascale.txt and some other songs.
When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
• Commit and push all your work to your repository.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 4.1
 Last name WUSTL Key Propagate? (NOT your numeric ID) Do not propagate lower case only e.g. Smith j.smith 1

Acknowledgements and assertion of integrity

 You must select one of the options below The work submitted here was performed in accordance with this course's policy on collaboration. On your honor, you have neither given nor received any unauthorized aid on this assignment. However, the following TAs, students, or professors were supportive in completing this assignment. Their help was also in accordance with course policies. Thanks to (leave blank if appropriate): In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment. You would like to be contacted by an instructor to facilitate staying on track in this course. Comments about this: You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment. You would like to be contacted by an intructor to faciliate staying on track in this course. Comments about this:

TAs double check!
• This demo box is for extension 4.1
• The student has committed and pushed the work, and verified that it appears at bitbucket.
TA: Password:

## Extension 2: Draw a Sound Wave (10 points):

Authors

#### Warm Up

To understand this extension, you should first be familiar with the extension in which an instrument's sound is produced as the sum of sine waves.

You will modify your program further in this extension to produce the sine-wave plots that depict how sine-wave addition occurs.

The details of this assignment are not completely specified so that you must think through what is needed to produce meaningful plots. Ask for help as needed!

#### Procedure

• An example of a plot is shown below:
• The black waveform with the largest amplitude (the tallest black waveform) is the fundamental frequency at relative strength 1. The waves shown are for 1/440 of a second of a 440 Hz concert-A. This is sufficient ot show one full cycle of that fundamental frequency.
• The black waveform with the next largest amplitude has relative strength 0.75. It is an octave higher, so it oscillates twice in the timespan of the fundamental pitch's waveform, at 880 Hz.
• The black waveform of smallest amplitude (at half the strength of the fundamental frequency) is 660 Hz: the 3:2 frequency factor, which sounds like a fifth above the fundamental frequency. As expected, it exhibits 1.5 cycles in the timespan of the fundamental pitch's waveform.
• The red waveform is the sum of the black ones.
• Each of the frequency factors incorporated into an instrument is shown separately by plotting dots of the curve as the values are computed.
• With frequencies on the order of hundereds or thousands of cycles per second, we must limit the time of the plot so that we can see one or two cycles clearly.
Think about how many samples you need to capture to show one complete cycle at 440 Hz.

One way to reason about this is to use the units of the various computations and multiply or divide them to obtain the property you seek.

• Plot the individual waveforms using black dots, as shown above.
• Plot the summation waveform using red connected line segments, as shown above.
When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
• Commit and push all your work to your repository.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 4.2
 Last name WUSTL Key Propagate? (NOT your numeric ID) Do not propagate lower case only e.g. Smith j.smith 1

Acknowledgements and assertion of integrity

 You must select one of the options below The work submitted here was performed in accordance with this course's policy on collaboration. On your honor, you have neither given nor received any unauthorized aid on this assignment. However, the following TAs, students, or professors were supportive in completing this assignment. Their help was also in accordance with course policies. Thanks to (leave blank if appropriate): In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment. You would like to be contacted by an instructor to facilitate staying on track in this course. Comments about this: You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment. You would like to be contacted by an intructor to faciliate staying on track in this course. Comments about this:

TAs double check!
• This demo box is for extension 4.2
• The student has committed and pushed the work, and verified that it appears at bitbucket.
TA: Password:

## Extension 3: Loud or Graphics-ful Bouncing Balls (2 points):

Authors

### Extension points available for Lab 4

Trevor Larsen and Tyler Spinks submitted this video for your amusement, as a demo of this extension. It is based on the John Cena Prank Call video.

If you have added sound or pictures to your solution for Lab 4, demo those to a TA and receive points for this extension.

When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
• Commit and push all your work to your repository.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 4.3
 Last name WUSTL Key Propagate? (NOT your numeric ID) Do not propagate lower case only e.g. Smith j.smith 1

Acknowledgements and assertion of integrity

 You must select one of the options below The work submitted here was performed in accordance with this course's policy on collaboration. On your honor, you have neither given nor received any unauthorized aid on this assignment. However, the following TAs, students, or professors were supportive in completing this assignment. Their help was also in accordance with course policies. Thanks to (leave blank if appropriate): In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment. You would like to be contacted by an instructor to facilitate staying on track in this course. Comments about this: You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment. You would like to be contacted by an intructor to faciliate staying on track in this course. Comments about this:

TAs double check!
• This demo box is for extension 4.3
• The student has committed and pushed the work, and verified that it appears at bitbucket.
TA: Password:

## Extension 4: Magic 8 Ball (7 points):

Authors
• A video demonstrating my solution can be found here.
• Your work for this assignment should be done in the eightball package in the extensions folder.

You will need to create a new class there.

The Magic Eight Ball is an autoresolution device. A question of boolean type is posed, the Magic Eight Ball is turned over, and it then displays its advice in a murky window. It has resurfaced in other guises over the ages, most recently perhaps as The Magic Conch Shell in the Club SpongeBob episode of SpongeBob SquarePants.

To receive credit for this extension, your implementation of the Magic 8 Ball must:

• Repeatedly prompt the user for a question using ArgsProcessor.
• Dramatically cause the answer to emerge in a (StdDraw) display, over a 2-5 second period, as follows:
• Display the result in a triangular shape, such as shown here. (Your solution will be much more dramatic as you include the following.) Your triangle need not rotate.
• Your rendering must fade the image from black to showing the triangle with text in a continuous manner, as the answer emerges.
• Your rendering of the answer must cause the text go from blurry to sharp as the answer emerges.
Every semester students ask if the API for drawing text supports creating blurry text. It does not, and you can imagine why support for blurry text was not considered important.

So you have to figure out how to make text look blurry on a screen when there is no simple way to produce blurry text directly.

• Try to have a suitably eerie sound accompany your display. (not necessary for credit, but nice)
When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
• Commit and push all your work to your repository.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 4.4
 Last name WUSTL Key Propagate? (NOT your numeric ID) Do not propagate lower case only e.g. Smith j.smith 1

Acknowledgements and assertion of integrity

 You must select one of the options below The work submitted here was performed in accordance with this course's policy on collaboration. On your honor, you have neither given nor received any unauthorized aid on this assignment. However, the following TAs, students, or professors were supportive in completing this assignment. Their help was also in accordance with course policies. Thanks to (leave blank if appropriate): In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment. You would like to be contacted by an instructor to facilitate staying on track in this course. Comments about this: You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment. You would like to be contacted by an intructor to faciliate staying on track in this course. Comments about this:

TAs double check!
• This demo box is for extension 4.4
• The student has committed and pushed the work, and verified that it appears at bitbucket.
TA: Password:

## Extension 5: Roving Eyes (10 points):

Authors
A video demonstrating my solution can be found here.
This extension has been brought back from the 131 vaults, having originally been conceived by Ken Goldman, formerly a professor in our department and currently at Google. In its new form, it has been rewritten to comform to Sedgewick's API. Also, it does not make use of objects, so it can be offered as an extension at this point in the course.

Although the solution can be quite short (mine weighed in at approximately 50 lines), there are some tricky aspects to this work, and it may be an extension that you work on over several weeks.

You will have to interact with the mouse, perhaps for the first time, both in terms of its location and determining whether the mouse has been pressed and released. It will take patience to get this to work, but most students like the end result.

#### The idea

• Each time the mouse is clicked, an eyeball is deposited on the image.
• Each eyeball consists of two parts:
• An outer filled circle that is white with a thin black border. This part of the eyeball does not move as the mouse moves around the screen.
• An inner filled circle with of some color (mine are red, below). This part of the eyeball does move, so that the eyeball can appear to be looking at something.
• All eyeballs seem to look at the mouse, wherever the mouse moves within the StdDraw window.
 This is the initial image you should draw. The picture can be found as images/ken.jpg in your workspace. Here, I have clicked over the image to deposit my first eyeball. The mouse (not shown) is to the right, so the eyeball is looking that way. Then I clicked a second time to deposit another eyeball, this time over the right eye shown in the image. Both eyeballs are looking at my mouse, which is at the lower right (not shown). Each time I click the mouse, another eyeball is deposited, and all eyeballs continue looking at my mouse, wherever it happens to be.

#### Part 0: Initialize your application

• Begin by drawing the picture in the image.
• Prompt the user to specify the maximum number of eyeballs that will be drawn. This information is necessary so that you can appropriately provision arrays needed to implement this extension.
This code is included in your repository. Open the extensions folder in which you will find the eyeballs package. Open and run the Eyeballs class.

#### Part 1: Detecting mouse clicks

Most programs that interact with the mouse use a listener model that takes action when the mouse is moved, pressed, released, or clicked (a press and release action).

Unfortunately, in Sedgewick's API, we can only determine the current status of a mouse button as up or down. We must then use logic and iteration to discover whether a mouse has been pressed, released, or clicked. This low-level API for the mouse leads to some mixed feelings about how you are learning to interact with the mouse:

• The code you write will not be typical of how most Java programs interact with the mouse. The reason for this is that your work takes place in an infinite loop, slowed only by the use of StdDraw.pause(n), which consumes resources on your computer even when you are not moving the mouse.
• You are essentially polling the mouse as to whether it is up or down, and then using your own logic to determine whether it has been pressed, released, clicked, or dragged. From a pedagogical perspective, you will learn how this kind of processing takes place at a low level on some computers. You also learn how to track the state of an input device over time, and many applications require this kind of logic.

Following is a description of mouse actions as they are typically used in most applications:

Mouse press
We think of this as a single push-down action on a mouse or trackpad. This action usually initiates some activity in applications.
From an application's point of view, this event happens just once when the mouse is pushed down. Generation of another mouse press action would require the mouse to be released, and then pressed again.
Mouse release
If a mouse has been pressed, then it can be released. Some applications distinguish between the press and release, so that the mouse can move between those actions. This is sometimes called dragging the mouse.
Mouse click
While this is a compound action, consisting of a mouse press followed by a mouse release, it is usually treated as an atomic action that takes place at exactly one coordinate. The release also happens within some reasonable timeframe of the press, if the press and release are to be construed as a click.
The above mouse actions are the logical ones that we wish to implement. Actually, it suffices for this extension to determine only a mouse release, but you are welcome to think about how to discover the other actions.

The Sedgwick API offers only the following interface, which we must use in our application to simulate the above mouse actions.

double mouseX()
returns the x-coordinate of the mouse, expressed in terms of the coordinates of the StdDraw canvas.
double mouseY()
returns the y-coordinate of the mouse, expressed in terms of the coordinates of the StdDraw canvas.
boolean mousePressed()
A better name for this would be boolean isMouseDown(), because this method does not detect a mouse press in the standard view of mouse actions. Instead it simply reports whether the mouse button is currently pressed or not.

Your task is to simulate a mouse-click action using the above API. This will inevitably involve polling the mouse as to whether the button is down or up. Consider the following code:

while (!StdDraw.mousePressed()) {
// do nothing,
// we are waiting for the mouse button to go down
//
// The line below is important, as described below
//
StdDraw.show(50);
}
• Without the pause using StdDraw.show(50), this application would run in a tight loop that would always keep your computer busy, even if you are not interacting with the application. As a result, all of the other applications open on your computer would suffer from not getting sufficient CPU resources to be reponsive. These applications would appear to behave sluggishly.
• Sedgewick uses the pause intervals to hide updates that you make to the drawing canvas. Between calls to show, no updates are shown. At the call to show, the screen is redrawn, and the CPU is released for the specified period of time (50 milliseconds in the above code).
Make sure your eyeballs are depositing properly as you mouse-click before you move on to implement more features.

#### Part 2: Following the mouse movement

A pupil within an eyeball tracks objects using the geometry of similar triangles. The following diagram and discussion may be useful.

• The eyeball is centered at (ex,ey) and is looking at the object (the mouse) at (mx,my). This leads to the following equations:
• mx = ex + dx
• my = ey + dy
• Knowing (ex,ey) and (mx,my), we can solve for dx and dy.
• Knowing dx and dy, we can compute d using the distance formula.
• We know p, because it is the radius of the eyeball minus the radius of the pupil. This may be hard to see, but convince yourself of this by looking carefully at the figure.
• The green triangle is similar to the large triangle.
• Knowing p and d, we can compute their ratio.
• That same ratio describes px:dx py:dy.
• From those ratios we can compute px and py.
• Knowing (ex,ey), px, and py, we can compute the center of the red pupil as (ex+px,ey+py).

#### Putting it all together

Your code is like the bouncing ball code, in that it enacts a sequence of frames. Each frame consists of checking whether and where a new eyeball should be deposited. Moreover, all existing eyeballs must be updated so that they appear to be tracking the mouse as it moves through the window.

Give yourself time for this extension, and develop and test the aspects in the order described above.

When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
• Commit and push all your work to your repository.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 4.5
 Last name WUSTL Key Propagate? (NOT your numeric ID) Do not propagate lower case only e.g. Smith j.smith 1

Acknowledgements and assertion of integrity

 You must select one of the options below The work submitted here was performed in accordance with this course's policy on collaboration. On your honor, you have neither given nor received any unauthorized aid on this assignment. However, the following TAs, students, or professors were supportive in completing this assignment. Their help was also in accordance with course policies. Thanks to (leave blank if appropriate): In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment. You would like to be contacted by an instructor to facilitate staying on track in this course. Comments about this: You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment. You would like to be contacted by an intructor to faciliate staying on track in this course. Comments about this:

TAs double check!
• This demo box is for extension 4.5
• The student has committed and pushed the work, and verified that it appears at bitbucket.
TA: Password:

## Extension 6: Roving Eyes; Slow Motion Edition (5 points):

Authors
• We suggest that you wait until you have completed module 5 to do this extension, as the information in module 5 will help.
• A video demonstrating a solution can be found here.
To do this extension, you must first complete the one above and successfully demo it. Then you can earn the points for this extension by causing the eyes to move slowly from where they were looking to where they should be looking.
You are not allowed to do this by slowing the simulation down. Instead, you must smoothly vary where the eyes should look in the normal speed of the simulation.
When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
• Commit and push all your work to your repository.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 4.6
 Last name WUSTL Key Propagate? (NOT your numeric ID) Do not propagate lower case only e.g. Smith j.smith 1

Acknowledgements and assertion of integrity

 You must select one of the options below The work submitted here was performed in accordance with this course's policy on collaboration. On your honor, you have neither given nor received any unauthorized aid on this assignment. However, the following TAs, students, or professors were supportive in completing this assignment. Their help was also in accordance with course policies. Thanks to (leave blank if appropriate): In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment. You would like to be contacted by an instructor to facilitate staying on track in this course. Comments about this: You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment. You would like to be contacted by an intructor to faciliate staying on track in this course. Comments about this:

TAs double check!
• This demo box is for extension 4.6
• The student has committed and pushed the work, and verified that it appears at bitbucket.
TA: Password:

## Extension 7: String theory (2 points):

Authors

#### Overview

The purpose of this assignment is to give you the skills to index and analyze Strings in order to prepare for different web scraping tasks. Once you are able to extract information of interest from a target String, you will be ready to query a webpage, save the raw HTML code, and extract relevant information.

For this assignment, you are working on simple arithmetic expressions as Strings. Your task is to extract the two integer values and the arithmetic operator from the String and save them as variables of their respective type. You will then compute and print the value of the expression.

Do your work for this assignment in the strings package found in your extensions source folder.

#### Example

Given:
String s = "21 + 33";

You must extract 21 and 33 to int variables and + to a char or String variable. Then you will compute and print the expression 21 + 33 = 54

#### Procedure

As previously mentioned, the purpose of this assignment is to prepare you for dynamic web scraping tasks. As such, it is expected that you implement this assignment dynamically. In other words, the only assumption you should have about the String you are analyzing is that it will be in the format (Positive Integer)(Arithmetic Operator) (Positive Integer). This implies your implementation should be able to run effectively on an expression containing positive integers of any length. It should also be able to effectively extract any arithmetic operator (+, -, *, /) and print the proper answer. Lastly, your code should be able to deal with possible spaces in the String.

It is important to note that there are many acceptable ways to implement this assignment. It is up to your discretion which way you choose to implement the procedure as long as it abides by the requirements described above.

1. Begin by extracting the first integer value from the String using the methods described above. Keep in mind that the integer can be multiple digits. You might be extracting 2 or 274539.
2. Implement a similar approach for the operator and second integer.
3. Now that you have the two integers in int variables and the operator in a char or String variable, perform and print the simple arithmetic operation.

#### Demo

Be prepared for your TA to review your code and change the digits and operator in the String you are analyzing to ensure your implementation is dynamic.
When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
• Commit and push all your work to your repository.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 4.7
 Last name WUSTL Key Propagate? (NOT your numeric ID) Do not propagate lower case only e.g. Smith j.smith 1

Acknowledgements and assertion of integrity

 You must select one of the options below The work submitted here was performed in accordance with this course's policy on collaboration. On your honor, you have neither given nor received any unauthorized aid on this assignment. However, the following TAs, students, or professors were supportive in completing this assignment. Their help was also in accordance with course policies. Thanks to (leave blank if appropriate): In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment. You would like to be contacted by an instructor to facilitate staying on track in this course. Comments about this: You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment. You would like to be contacted by an intructor to faciliate staying on track in this course. Comments about this:

TAs double check!
• This demo box is for extension 4.7
• The student has committed and pushed the work, and verified that it appears at bitbucket.
TA: Password:

## Extension 8: Web Scraper (3 points):

Authors

#### Intro

Web scrapers are programs that search websites and scrape off useful data. You will write a web scraper in this assignment that looks for weather information in a zip code of interest. There are two ways to go about this:

• The result of accessing a web URL is a stream of text which you can receive a a Java String. You can scan that String for information of interest. In this approach, you search for features that delimit the area of interest, and trim the String to extract data of interest.
• A library has been developed for Java called jsoup that allows direct interaction with a website's HTML. This library regards a web document in terms of its structure. You use methods from this library to navigate to the part of the web page that is of interest.
URLs and web sites
• Watch this video which demonstrates how URLs are used in the http://www.wunderground.com/ web site.
• We have to reverse engineer how that web site uses URLs to request zip-code-specific weather information.
Reverse engineering skills are useful skills and can serve you well.
• After watching the video, visit the http://www.wunderground.com/ site
• Take a look around for a bit to see what is offered there
• Type into the field Search Locations some zip code of interest to you. Examples might include
• 63130 for Washington University
• 80424 for Breckenridge, Colorado
• 10598 for Yorktown Height, New York
• Observe that when you submit your request, you are taken to a web page whose URL is different from the home page for the site.
• Try editing the URL in your browser to find weather information for a different zip code of interest to you.
• For one or more of the pages you reach, view the source of that web page in your browser, as you saw in the video.
Browsers vary in how they allow you to see the page source. If you are on the web page of interest, try control- (right-) clicking and one option you should see should resemble View Page Source.

If you are lost, try Googling for how to view page source in your browser.

• Try to locate the text within the page source that corresponds to the temperature report. In the video, this was found near the string curTemp in the source.
Simple use of jsoup
• Watch this video which shows how to supply jsoup with a URL within Java.
• The result of that interaction is a String.
In this assignment, you will process the text yourself after getting the document's text using jsoup. You could use methods in jsoup to isolate what you need, but you can explore that on your own.

#### Procedure

• Find and open the Weather class in the scraping project of your extensions folder.
• That code is what you saw on the video, with comments added to direct your work.
• Your task is essentially to isolate the temperature data and some other statistic from the source text of the web page.
• What makes this difficult is that the author of the web page doesn't know you want to find this information.
• You have to look at the web page yourself to find distinguishing features of the page near where you want to extract information.
• Worse still, the author of that web page is not obligated to keep the information you see in future versions of that web page. Scraping is a dodgy effort at best, and you may have to revise your code in response to changes made by the author of the pages you scrape.
• It will be helpful to use some methods from the String class. The following describes some of those methods, assuming they are called on a target String t.
int indexof(String str)
Finds the location of the specified str in t.
String substring(int beginIndex)
Returns a new String that is copied from t, starting at the supplied beginIndex.
String substring(int beginIndex, endIndex)
Returns a new String that is the substring of t, starting at the supplied beginIndex, up to but not including endIndex.

#### Demo

• Complete the code as instructed in the comments.
• Your output must include the current temperature and some other statistic of interest from that same web page.
• Show the output to your TA.
When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
• Commit and push all your work to your repository.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 4.8
 Last name WUSTL Key Propagate? (NOT your numeric ID) Do not propagate lower case only e.g. Smith j.smith 1

Acknowledgements and assertion of integrity

 You must select one of the options below The work submitted here was performed in accordance with this course's policy on collaboration. On your honor, you have neither given nor received any unauthorized aid on this assignment. However, the following TAs, students, or professors were supportive in completing this assignment. Their help was also in accordance with course policies. Thanks to (leave blank if appropriate): In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment. You would like to be contacted by an instructor to facilitate staying on track in this course. Comments about this: You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment. You would like to be contacted by an intructor to faciliate staying on track in this course. Comments about this:

TAs double check!
• This demo box is for extension 4.8
• The student has committed and pushed the work, and verified that it appears at bitbucket.
TA: Password:

## Extension 9: Stock Scraper (5 points):

Authors
It is highly recommended that you complete the String Theory assignment before attempting this assignment.

Additionally, this assignment builds off of the Web Scraper assignment and it is recommended that you complete that assignment prior to attempting this one. If you decide to work on this assignment without having completed the former, it is, however, necessary that you watch the two videos provided in the Web Scraper assignment in order to fully understand this assignment.

#### Overview

Stocks represent equity ownership in a company and can either be rapidly traded for the purpose of profiting from price fluctuations or can be held in the long-term for the purpose of developing a substantial stake in a corporation which grants voting rights and a general "say" in the day-to-day operations of the company, among other things. As such, it can be useful to know the current stock price in real-time in order to track changes and monitor an investment.

In this assignment, you will access the Yahoo! Finance website, store the HTML code of the website in a String, and extract the current stock price of a company, along with some other useful information. You will use the API provided through Jsoup to download and store the HTML code of the website, which you learned how to do through the aforementioned Web Scraper assignment videos. Once you've stored the HTML code of the website in a String, you will then analyze the code to find the relevant information and a corresponding unique identifying String which will allow you to locate and extract it.

#### Procedure

1. Use ArgsProcessor to prompt the user for the stock symbol to look up.
2. For the stock symbol given, use Jsoup to retrieve the HTML code of the Yahoo! Finance webpage and store it as a String, as shown in the aforementioned video.
3. Look at the HTML source code (as described in the previous assignment's videos) and look for unique Strings that will allow you to identify and then extract the relevant stock information.
Specifically, you are looking for three different pieces of information that you will extract and print.
• The full name of the company in question.
• The current price of the stock.
• The percent daily change in stock price. (This is provided as its own element in the HTML code and therefore does not require any computation on your part)
4. Use the unique Strings to locate the information, and then extract and store them to variables.
5. Print out the information in a format similar to the one shown below:

#### Example

Input: INTC

Stock information for Intel Corporation
The current stock price is \$34.94 which is up 1.63% from yesterday.

It will be helpful to use some methods from the String class. The following describes some useful methods, assuming they are called on a target String t:

int indexof(String str)
Returns the location of the specified str in t.
char charAt(int i)
Returns the character at index i in t.

Three particular static methods may also be useful for this assignment. Recall that static methods are not called on a target variable as in the previously described methods, but rather are called on a generic object of that type.

boolean Character.isDigit(char c)
Returns true if c is a digit and false otherwise.
String Character.toString(char c)
Returns the String representation of a character.
int Integer.parseInt(String s)
Returns the int representation of a String.

#### Demo

show your TA the output and run the program with multiple different stock tickers.
When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
• Commit and push all your work to your repository.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 4.9
 Last name WUSTL Key Propagate? (NOT your numeric ID) Do not propagate lower case only e.g. Smith j.smith 1

Acknowledgements and assertion of integrity

 You must select one of the options below The work submitted here was performed in accordance with this course's policy on collaboration. On your honor, you have neither given nor received any unauthorized aid on this assignment. However, the following TAs, students, or professors were supportive in completing this assignment. Their help was also in accordance with course policies. Thanks to (leave blank if appropriate): In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment. You would like to be contacted by an instructor to facilitate staying on track in this course. Comments about this: You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment. You would like to be contacted by an intructor to faciliate staying on track in this course. Comments about this:

TAs double check!
• This demo box is for extension 4.9
• The student has committed and pushed the work, and verified that it appears at bitbucket.
TA: Password:

## Extension 10: Gambler's Ruin with CSV File (2 points):

Authors
• Jarett Gross
• Elie Schramm

#### The Problem

An administrator wants to hire the best secretary out of n applicants each with a rating from 0 to 1. The applicants are interviewed in a random order. During the interview, the administrator can evaluate the applicant among all the applicants interviewd so far, but is oblivious to the quality of applicants that have yet to be seen. If the decision to hire a secretary can be made at the end, this could be solved by simply tracking the maximum rating (and who achieved it) and selecting the overall maximum. The difficulty is that the decision must be made immediately (i.e. after the interview and once rejected the applicant can not be recalled). The question is finding an optimal strategy that maximizes the probability of the best applicant being chosen.

Such a strategy is the stopping rule. For example, consider the first k of n applicants, retaining the highest rank, but rejecting all. Continue from k+1 to n and hire the first applicant who has a rank equal to or greater than the one computed for the first k, choosing the last applicant if it comes to it.

In this extension, your job is to experiment and find the value of k that chooses the best secretary the most.

#### Procedure

1. Create a class in the secretary package of the extensions folder
2. Create an array of N random doubles each ranging from 0 to 1 (utilize Math.random).
3. Implement the stopping rule:
• Iterate over the first k values of the array preserving the max then record the next highest number from the k+1 to N portion.
• Record the maximum of the entire array.
• The best secretary is picked when the max calculated using the stopping equals the overall max
4. To experiment effectively, you should run 100 simulations for each value of K to see how many times the best secretary was picked.
5. Calculate the optimal point-the k where the best secretary was picked the most times
6. To increase accuracy, insert code to compute 100 optimal points and print their average
7. Demo your results to a TA
8. When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
• Commit and push all your work to your repository.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 4.10
 Last name WUSTL Key Propagate? (NOT your numeric ID) Do not propagate lower case only e.g. Smith j.smith 1

Acknowledgements and assertion of integrity

 You must select one of the options below The work submitted here was performed in accordance with this course's policy on collaboration. On your honor, you have neither given nor received any unauthorized aid on this assignment. However, the following TAs, students, or professors were supportive in completing this assignment. Their help was also in accordance with course policies. Thanks to (leave blank if appropriate): In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment. You would like to be contacted by an instructor to facilitate staying on track in this course. Comments about this: You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment. You would like to be contacted by an intructor to faciliate staying on track in this course. Comments about this:

TAs double check!
• This demo box is for extension 4.10
• The student has committed and pushed the work, and verified that it appears at bitbucket.
TA: Password:

## Extension 12: Emersyn the Emote (6 points):

Authors
• Nick Leidenfrost
• Jonathan Wetherbee
• Heather Berlin
• Elie Schramm

#### Overview

Computers have feelings too! In this assignment you create Emersyn the Emote -- an animated face that displays emotions that the user selects. It has 3 slider bars: one for temperature, one for happiness/sadness, and one for an emotion pair of your choice.

Below, you should see a video demonstrating a sample solution.

This assignment has been revived and adapted from a version written by Nick Leidenfrost, Jonathan Wetherbee, and Heather Berlin in 2002, back when CSE131 was CS101! The idea has been kept, but it does not make use of objects.

Your Emote must have these basic features:

• a face
• two eyes
• a mouth
You may incorporate more features for different emotions, such as eyebrows or eyelids. Personalize Emersyn however you like -- ears, hair, nose, etc.

#### Procedure

1. In the extensions folder, find the emote package. You will write your code in the Emersyn class and you can run it with the EmersynController class.
2. Emersyn is created from the following specifications:
• x and y coordinates of the center of the face ( (.5, .5) is the center in the default canvas)
• width and height of the frame for Emersyn to be drawn within. The radius of its face must be less than or equal to the minimum of those two values in order for it to be confined to the frame.
• the degree each emotion is felt (on a scale from -1 to 1 where 0 is neutral). Ex: howHot
3. Using Sedgewick's StdDraw, create Emersyn's basic features in their neutral state. All the locations and sizes must be relative to the specifications listed above. For example: the mouth should always be around or below the center of the face; if you just put it at (.5, .3) then it wouldn't stay on the face at different face coordinates.
4. Hot and cold aren't really emotions, but that doesn't prevent Emersyn from feeling them too. The first slider will make it react to being cold and hot and all the temperatures in between by changing the color of its face. Make yellow the default color and make Emersyn turn progressively more blue for cold and more red for hot as a function of the howHot variable. A value of 1 should correspond to complete red and a value of -1 should correspond to complete blue.
Emersyn will be executed by the EmersynController class and all the animation will happen as a result of dragging the slider, so do not use the "clear" or "show" functions that you may have used in other drawing assignments.
5. Once Emersyn can react to hot and cold, do the same for happy (1) and sad (-1). Keep in mind that you should not change the color of the face for this emotion as it would conflict with the display of temperature. In the video, happy and sad was controlled by the smile/frown, but you could implement it a different way if you like, as long as it's clear what the emotion is and it doesn't overlap with the animations of the other emotions.
6. Choose one more emotional range for the third slider and animate that, such as surprised/bored, tired/alert, disgust/love, etc. This range of emotion should be clearly distinct and independent from the others.
When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
• Commit and push all your work to your repository.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 4.12
 Last name WUSTL Key Propagate? (NOT your numeric ID) Do not propagate lower case only e.g. Smith j.smith 1

Acknowledgements and assertion of integrity

 You must select one of the options below The work submitted here was performed in accordance with this course's policy on collaboration. On your honor, you have neither given nor received any unauthorized aid on this assignment. However, the following TAs, students, or professors were supportive in completing this assignment. Their help was also in accordance with course policies. Thanks to (leave blank if appropriate): In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment. You would like to be contacted by an instructor to facilitate staying on track in this course. Comments about this: You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment. You would like to be contacted by an intructor to faciliate staying on track in this course. Comments about this:

TAs double check!
• This demo box is for extension 4.12
• The student has committed and pushed the work, and verified that it appears at bitbucket.
TA: Password: