06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

18.6<br />

for (int i = 0; i < kinglear.length; i + + ) {<br />

if (theword.equals(kinglear[i])) {<br />

<strong>to</strong>tal + + ;<br />

}<br />

}<br />

// Display the text and <strong>to</strong>tal times the word appears<br />

textFont(f);<br />

fill(0);<br />

text(theword,10,90);<br />

text(<strong>to</strong>tal,10,110);<br />

stroke(0);<br />

fill(175);<br />

rect(10,50,<strong>to</strong>tal/4,20);<br />

// Move on<strong>to</strong> the next word<br />

counter = (counter + 1) % kinglear.length;<br />

} fi g. 18.10<br />

Data Input 341<br />

Exercise 18-10: Count the number of times each letter of the alphabet appears in King Lear<br />

Visualize those counts. Here is one possibility (you should be more creative). Note this sketch<br />

will require the use of the charAt( ) function.<br />

Asynchronous Requests<br />

The word “Lear” appears 226<br />

times in the text of King Lear.<br />

As we have seen, the loadStrings( ) function can be used for retrieving raw data from web pages.<br />

Nonetheless, unless your sketch only needs <strong>to</strong> load the data once during setup( ) , you may have a problem.<br />

For example, consider a sketch that grabs the price of AAPL s<strong>to</strong>ck from an XML feed every 5 min.<br />

Each time loadStrings( ) is called, the sketch will pause while waiting <strong>to</strong> receive the data. Any animation<br />

will stutter. Th is is because loadStrings( ) is a “ blocking ” function, in other words, the sketch will sit and<br />

wait at that line of code until loadStrings( ) completes its task. With a local text fi le, this is extremely fast.<br />

Nonetheless, a request for a web page (known as an “ HTTP request ” ) is asynchronous , meaning the web<br />

server can take its time getting back <strong>to</strong> you with the data requested. Who knows how long loadStrings( )<br />

will take? No one, you are at the mercy of the server!<br />

Th e simpleML library (available for download at this book’s web site: http://www.learniningprocessing.<br />

com/simpleML/ ) gets around this problem by executing these HTTP requests <strong>to</strong> web servers in parallel

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!