lundi 18 juillet 2011

Rotating an image in Processing

Just taking the basic example LoadDisplayImage and letting the images rotate independent of each other:

http://www.contrechoc.com/crosslab/applet/rotateDisplayImage.html



PImage a; // Declare variable "a" of type PImage
float theta = 0;//rotating angle in degrees
void setup() {
size(200, 200);
a = loadImage("jelly.jpg"); // Load the image into the program
}
void draw() {
// Displays the image at its actual size at point (0,0)
pushMatrix();//used to get an independent rotation
translate(width/2, height/2);
rotate(radians(theta));
translate(-a.width/2, -a.height/2);
image(a, 0, 0);
popMatrix();//sort of boundaries for a rotation translation
pushMatrix();//start another rotation
translate(width/4, height/4);
rotate(radians(-2*theta));
translate(-a.width/4, -a.height/4);
image(a, 0, 0, a.width/2, a.height/2);
popMatrix();//
theta+=1;
}

samedi 18 juin 2011

Playing with text() and pixels

 Two excellent examples using text, the first takes a picture and a text on top, and makes the letters bigger where the picture is brigther, a fine start for more experiments:

http://www.learningprocessing.com/exercises/chapter-17/exercise-17-7/

The second example is using textWidth:

x += textWidth(message.charAt(i));


So you can get the pixelNumber where your letter starts. In this way you can use letters of different sizes in the same bit of text.

jeudi 16 juin 2011

Input textfield, sliders, buttons etc

Well for these fancy objects, which are not easy to program from scratch, you can use this library:

http://www.sojamo.de/libraries/controlP5/

Example code:

http://www.openprocessing.org/visuals/?visualID=20726

as usual download the library, unzip, and pu this folder in the folder libraries inside the Processing folder with your sketches. In this folder there are lots of examples, buttons sliders....

mardi 14 juin 2011

Searching......

Just a few downloads to wonder about all the data floating around....

http://www.contrechoc.com/crosslab/dataBaseStuff.zip

with and extra example adding to the last post ( database_patterns_6.pde )



with examples searching the NYT, Google and Twitter

for the nyt API you need your own key, and insert it into this line:
TimesEngine.init(this,"get your own API key"); // http://developer.nytimes.com/
this line of code becomes something like:

TimesEngine.init(this,"87238269346827638476283764827638476287364872638576"); //fake key!

as indicated in the script, you can get your key here: http://developer.nytimes.com/

also, the right libraries are added (JSON). You have to put these libraries in the folder libraries inside the Processing folder containing your sketches.

And then a few links:


http://searchenginewatch.com/article/2066257/What-People-Search-For-Most-Popular-Keywords

Or search for: youtube professor Hans Rosling.....
http://www.youtube.com/watch?v=YpKbO6O3O3M&feature=relmfu

http://lowfrequency.org/interactivity/wiki/index.php?title=Google_API_In_Processing


The google Image API is also not too difficult and can be exciting for designers:
http://lowfrequency.org/interactivity/wiki/index.php?title=GoogleJSONSearchDrawImage
You need the JSON library, but when you have the nyt examples (above) running, this library is included.

This link gives an example with 1 image, but displaying 4 images can be done like this:

in the declarations, instead of one image take an array

PImage myImg[] = new PImage[4];


in setup() load for images:

for(int i=0; i<4 ; i++){ myResult = getFirstSearchResult("bullet cluster",i); PImage getImage = new PImage(); getImage = loadImage(myResult); println( "------------>"+ str(i) + " " + myResult );
myImg[i] = getImage;
}


this to add in the draw:


for(int i=0; i<2 ; i++) for(int j=0; j<2 ; j++){ iCounter++; image(myImg[iCounter], i*width/2, j*height/2, width/2, height/2); }


and this works with a minor change in the function:

String getFirstSearchResult(String query, int imageNumber)
{


this leaves one line in this function to get more than result one:


URL url = new URL(baseURL + "?start="+str(imageNumber)+"&rsz=large&v=1.0&q=" + query);


You can find this script in this download:

http://www.contrechoc.com/crosslab/dataBaseStuff.zip

four images of the search for "bullet cluster"




















All about the Google API's can be found here:
http://code.google.com/apis/maps/index.html

jeudi 9 juin 2011

A few Processing Examples

Here you can find some simple examples: http://www.contrechoc.com/crosslab/databaseSamples.zip
have fun!

Basically these examples build from simple text on a screen, color changing, to text and image, interactively displayed (on mouseDrag and mousePressed);




lundi 23 mai 2011

Making and using a simple Object

Although you can do a lot of nice things just programming around (called "knitting") sometimes you meet things like objects and classes.
Some basic knowledge of Object Orientated ( "OO" ) programming may be useful.
In this post I present a simple example of a class, with which you can make objects.
A class is a black box. With this black box you can produce your own "things", for instance records of a name and an amount of payment.
So we have a name, "Beam" and we have a payment "1.75". In a so called constructor these are tied together. Later on we can get these data out again.

A class can save these data, but can also have functions. Like the data, these functions are also tailor made.
In your main sketch you can make the TestClass object like this:
TestClass record = new TestClass( "Beam", 1.75 );


In the class the format of the parameters must be specified, like String and float.
A whole bunch of records can be made like this:
TestClass[] namePayArray = new TestClass[20];


but these are empty objects at the moment, you can fill these objects using a for loop:

for (int i = 0; i<20 ; i++)


//making an object:
TestClass newtest = new TestClass("Beam" + str(i) , 2.5 + random(10) ); 
//putting this object in an array:
namePayArray[i] = newtest; 
}

First we make an object, then we fill in the object in the array.

The Processing example can be found here:
http://www.contrechoc.com/crosslab/objectExample.zip
The results are printed in the debug window.

An example of a useful object is the timer, a few post ago:
http://flashscriptingwonders.blogspot.com/2011/05/timer-considerations.html

Then a more elaborate class example is this interesting circle script from a few blog posts ago:
http://flashscriptingwonders.blogspot.com/2011/04/circle-packing-scripts.html


Here we already use the circle class.
The question is....what to do when you want to see more hives (circle packings) at different positions?
So the whole script of the circlepacking is placed in a different class, (and for convenience in a different tab).
What is left is a simple main sketch with the constructor of the Hive's and the draw and the mousePressed (etc) functions:

Hive testme1;
Hive testme2 ;
Hive[] hiveArray = new Hive[20]; //the array is filled with "empty" objects


void setup(){
size(1000,1000);
testme1 = new Hive(250,250);
testme2 = new Hive(550,550);


for (int i = 0; i<20 ; i++){ 

Hive newtest = new Hive( int( 50 + random(1000)) , int(50 + random(1000)) ); hiveArray[i] = newtest; }
}


void draw(){
background( 255 );


testme1.draw();
testme2.draw();


for (int i = 0; i<20 ; i++){ 

hiveArray[i].draw(); 
}
}


void mousePressed() {
for (int i = 0; i<20 ; i++){ hiveArray[i].myMousePressed(); } }


void mouseDragged() {
for (int i = 0; i<20 ; i++){ hiveArray[i].myMouseDragged(); } }


void mouseReleased() {
for (int i = 0; i<20 ; i++){ hiveArray[i].myMouseReleased(); } }



You can find the sketch here: http://www.contrechoc.com/crosslab/hiveCircleClassExample.zip

lundi 16 mai 2011

Using a PVector making a field

A vector is a point with a property of an added direction. In short: an arrow.
Nice drawings can be made using arrows over the whole plane. But doing this by hand is tedious. So we do it by code.
In Processing the thing to look at is a PVector.

There is a nice tutorial about PVectors:
http://processing.org/learning/pvector/

Vector on a plane (or in space) - when the vectors are ordered, that is vary in a "physical" way - form a so called vector field. The vectors are like hair being combed.

One way to imagine a vector field is to think of magnets, the field lines, so beautifully made visible by iron dust:
http://www.openprocessing.org/visuals/?visualID=21418

Another way is to look at fluids, waves:
http://www.openprocessing.org/visuals/?visualID=12569

This is also a nice example:
http://www.openprocessing.org/visuals/?visualID=6707

Or look at this one:
http://www.openprocessing.org/visuals/?visualID=27653

With color:
http://www.openprocessing.org/visuals/?visualID=1036

search on keyword "field" in OpenProcessing.org

Google search API in Processing

When you want to get a google search inside your Processing sketch:

http://lowfrequency.org/interactivity/wiki/index.php?title=Google_API_In_Processing

On this page there is an example:
http://lowfrequency.org/interactivity/wiki/index.php?title=GoogleJSONSearch_Example


which worked right away!

(be careful, look at the dates of the link you find, for instance, this link:
http://users.design.ucla.edu/~tatsuyas/tools/google/index.htm
is from 2005 and the libraries don't work anymore.....)

But that is because I already had a json.jar
If you don't have a json.jar download this zip, which has a json.jar in the folder code in the sketch folder. Put this folder inside the Processing folder and restart Processing before running it.
http://www.contrechoc.com/crosslab/googleSearch.zip

samedi 7 mai 2011

Timer considerations

This links shows how easy everything becomes in Object Oriented Programming:
http://www.learningprocessing.com/examples/chapter-10/example-10-5/

But this example when used with mousePressed (for example) has a flaw: the timer.isFinished() is always true when the timer is not started immediately.

So we added a stop() function for the timer, and now timer.isFinished() is also false so long as the timer is not started.

You can find the sketch here: http://www.contrechoc.com/crosslab/timerOO/applet/timerOO.html

When you click in the sketch square you see the background change after 3 seconds.


This is a good example to see the power of objects.

jeudi 28 avril 2011

Extended circle packing script

Here you can download a script with more properties of the circle class:

http://www.contrechoc.com/crosslab/creativeDatabase.zip

The circles also have an image attached, which can be found in the datafolder of the sketch.
Also a sound is associated with the circles, also in the datafolder.

There is more interactivity:
clicking on the circles plays the sound and enlarges the circle, for 3 seconds, and the keyboard 1,2,3,4,5 etc are active the same way.

lundi 11 avril 2011

Circle packing scripts

For datavisualization you need some nice examples to start coding on:

http://www.cricketschirping.com/processing/CirclePacking1/ is certainly a nice one!
 as can be read in the script, here is an explanation:
http://wiki.mcneel.com/developer/sdksamples/2dcirclepacking

The example file has to be modified a bit, the noc library is deprecated and you can replace it with PVector:

PVector v = new PVector(); // instead of   Vector3D v = new Vector3D();

The circles have a random radius, you can change this in: ArrayList createRandomCircles(int n) .....

float myRadius = 30;//this was 10 + random (30)
Circle c = new Circle(random(width), random(height), myRadius);

The radius is chosen for all the circles which are put in the arraylist (the return of this function)
So here you can make the link between an array with data (for instance from the NYTimes Api examples).

With
text( "hello", (int)x, (int)y ); 



in the circle class:
  public void draw() {
    fill(myColor);
    stroke(myColor);
    strokeWeight(3);
    ellipse((int)x, (int)y, (int)radius*2, (int)radius*2);
    text( "hello", (int)x, (int)y );
  }



you can add a text to the circles. This text is static at the moment, but could come from an array of names of countries...

Here is this modified version of the script:
http://www.contrechoc.com/crosslab/circlePacking.zip

(Thx to Martijn, who found this script.)



other circle scripts can be found here:
http://www.openprocessing.org/visuals/?visualID=11727

lundi 4 avril 2011

Processing XML example

Working with XML is not too difficult if you know how to handle this format. To study here a simple example:

A XML is constructed and is read in the sketch.
You can follow the tree structure easily. More elaborate XML files are in principle the same.

This is the xml file:


/*
the xml file can be found in the link and is situated in the sketch folder
*/

XMLElement xml;

void setup(){

//loading the file

xml = new XMLElement(this, "xmlExample.xml");

//printing: look at the file structure


println( xml );


//get the first part of the upper branch


XMLElement myChannel = xml.getChild(0);

println( myChannel );

//now we will look at all the parts of the upper branch

int childCount = xml.getChildCount();

for (int i=0; i< childCount ; i++ ){
XMLElement countPart = xml.getChild(i);
println( countPart );
}



//we will print the text parts, but these are still xml elements


for (int i=0; i< childCount ; i++ ){
XMLElement countPart = xml.getChild(i);
XMLElement insidePart = countPart.getChild(0);//this is still inserted between text tags
println( insidePart );
}


//to get the text itself we have to ask for the content:

for (int i=0; i< childCount ; i++ ){
XMLElement countPart = xml.getChild(i);
XMLElement textPart = countPart.getChild(0);//you see that this can also be an array
String insidePart = textPart.getContent();

println( insidePart );
}
}
void draw(){
}





download this project as a sketch: http://www.contrechoc.com/crosslab/xmlExample.zip

dimanche 3 avril 2011

Processing NYTimes API and JSON

Ok, just when you think you know XML, there is an API using JSON.
This is always so sad! But luckily some people have compassion and solved our problems:
http://blog.blprnt.com/blog/blprnt/processing-json-the-new-york-times

Following this blogpost, we can extract numbers from articles, and there is even a simple way to visualize the data.

Analyzing the JSON String:

when we get the full JSON file we see these parts:

{"body" : "Music CITY HALL COFFEE HOUSE The \"Rockin' the Courtroom\" musical series kicks off with Scott E. Moore, singer and guitarist, and Frank Bango, singer. Friday at 7 P.M. Tickets: $5. Next week, Caren Belle and Happy Boy. Hoboken City Hall, 94 Washington Street, Hoboken. (201) 420-2207. CLUB BENE Female impersonators take the stage in \"Boys Will Be" , "date" : "19951231" , "title" : "ON THE TOWNS" , "url" : "http:\/\/www.nytimes.com\/1995\/12\/31\/nyregion\/on-the-towns-050180.html"}

and other pieces that start with "body".

We also see that \" is used for quotes, and inside the body the main text is seperated from the date by a comma.

So we can use some String functions to extract the text from the results like this:

String request = baseURL + "?query=O.J.+Simpson&begin_date=19940101&end_date=19960101&api-key=" + apiKey;

String result = join( loadStrings( request ), "");

//println( result );

String[] resultList = split(result, "body");

for (int i = 0;i< resultList.length;i++){
//remove 5 front chars
String removeFrontSpaces = resultList[i].substring(5, resultList[i].length() );
//search for date and stop the string in front
int dateIndex = removeFrontSpaces.indexOf("date");
String resultWithoutDate = removeFrontSpaces.substring( 0, max ( dateIndex - 2, 0) );
//println (resultList[i] );// has " : " in front
//println (removeFrontSpaces );
println( resultWithoutDate );
println ("------------------------------");
}

Looking at the text, you can see "byline" as an indicator, this can be removed (if you want to) in the same way as date. You could also start the splitting at date and get the date out.

Here are the first few results:

------------------------------
Music CITY HALL COFFEE HOUSE The \"Rockin' the Courtroom\" musical series kicks off with Scott E. Moore, singer and guitarist, and Frank Bango, singer. Friday at 7 P.M. Tickets: $5. Next week, Caren Belle and Happy Boy. Hoboken City Hall, 94 Washington Street, Hoboken. (201) 420-2207. CLUB BENE Female impersonators take the stage in \"Boys Will Be" ,
------------------------------
They have sportcoats, E-mail and no suntan. Northwestern will not be playing its look-alike in the Rose Bowl; Harvard isn't eligible. The Wildcats are here for the first time in a half-century, thanks to either running back Darnell Autry or their longtime alum, Moses. A year ago this week, one of their leading tacklers was giving Penn State a" , "byline" : "By TOM FRIEND" ,
------------------------------
and so on...

Remark, often running the sketch, you get a NullPointerException, the request is not returned. This happens even if you use try catch structures. Just try a few times, the API must be very busy!

Roxane Torre has made this pdf with very useful info and exmples:
http://crosslabminor.files.wordpress.com/2011/04/dag32.pdf

samedi 2 avril 2011

Twitter XML structure

If we want to get the tweets from the twitterrequest we have to understand the structure of the XML twitter is sending us.
Here is an example of a "live" xml: http://api.twitter.com/1/statuses/user_timeline.xml?user_id=111370674

This is one XML request saved: user_timeline.xml

Processing reference: http://processing.org/reference/XMLElement.html

Referring back to the processing script in one of the former posts we see this:


XMLElement xml = new XMLElement(this, "http://twitter.com/statuses/user_timeline/8138312.rss");

//we can dive into the XML tree with the getChild();

XMLElement myChannel = xml.getChild(0);

//with getChild you can count the "nodes"

XMLElement[] tweets = myChannel.getChildren("item");

/*
with getChildren , you can search on the "name" of the t
ag, getting back an array: XMLElement array, for this you have to know the name of the array. In this case the name is "item" .

Then you get the node 0 of this "item", and ask for the content:
tweets[i].getChild(0).getContent();

(which are the tweet texts) these are Strings, so pieces of text.

*/



Remark, you can only do 150 request an hour to get tweets from one client (say a computer) So real time twitter streaming, showing new tweets immediately is not possible. Also gaming with extracting commands from tweets is too slow now.

Processing Twitter update

See the post about twitter.

We would like to put the XML inside the draw function, to get fresh tweets and do something with these tweets. The problem is the request rate: if you exceed the limit of 150 an hour (on a computer, called the client) you get an error:

<hash>
<request>/1/statuses/user_timeline.xml?user_id=111370675</request>

<error>
Rate limit exceeded. Clients may not make more than 150 requests per hour.
</error>
</hash>

So 2 times a minute should be possible?
Which means steering something around using tweets is too slow.

dimanche 20 mars 2011

Text research

In database visualisation we can have a dataset which consists of numbers or of text.
In case of numbers we can easily do some graphics. Text is more versatile, but coding properties of text requires a bit of knowledge of the functions around Strings.
A wonderful text and string tutorial is found here:

http://processing.org/learning/text/

possibly we also need to know the pixel position of a word in a piece of text:
we start searching the position of the word, indicating the character number, if the word is found,
String myText = "we always cry out for love";
int lovePosition = myText.indexOf("love");//indexOf is the JAVA function

then to have the word "love" made special, colored or bold, we can use the tricks mentioned in this link using textWidth, looping through the string, with charAt.

samedi 5 mars 2011

String functions

Loaded data, from a file or a spreadsheet can be in numbers, or in text.
When working with text you have to know about the functions which can manipulate text.
Say we have the text

String hString = `Hello world and especially during carnaval`


And we want to have the seperated words in a list

String hString = "tester and rester";
String[] StringElements = split(hString, " ");
for (int i =0; i< StringElements.length ;i++) println( StringElements[i] );


we have the function split this gives an array which as elements the words if you use the space as a delimiter.

String hString = "tester";
println( hString.length());


To find a specific word the function indexOf is used

String hString = "tester";
println( hString.indexOf("ster"));


This can be useful extraction words from a twitterstream and doing something with these special words.
 

Reading data from an excell document

Lots of data are given in a spreadsheet.

To read a excell sheet we use a library, which comes from a third party
XlsReader-0.1.0, http://bezier.de/processing/libs/xls/
You have to download this library and put it in the right spot, so that Processing can find it.
This is the folder libraries in the Processing folder. In MACOS you have to select the Processing application and ask for the folders contained in it.
Rename the folder in the folder libraries: XlsReader.
Then you can try out an example in the example folder in this folder XlsReader.



import de.bezier.data.*;

XlsReader reader;

int c = 0;

PFont fontA;

void setup ()
{
size (300,100);
reader = new XlsReader( this, "workbook.xls" ); // assumes file to be in the data folder

fontA = loadFont("LucidaBright-Demi-18.vlw");
textFont(fontA, 32);

frameRate(3);
loop();
}

void draw(){
c++;
fill(0,36);
text( reader.getString( 1 + c%3, 0 ) , 10 + random(150), 50 + (c%3)*20 );
println( reader.getString( 1 + c%3, 0 ) );
stroke(155);
if ( c>5 ) { fill(200); rect(0,0,300,100);c=0; }
}


This sketch uses a .xls sheet having three words: ship, u-boat and ufo

reader.getString(x,y ) just reads the value in the cell, x y. 
For a number use: reader.getInt(x,y ) or reader.getFloat(x,y )
That is all there is!


 Of course numbers in the spreadsheet can be used to position an image, or move an image around.

Loading data into arrays

This time we will look at how to load external data into our Processing sketch.
Look at the example LoadFile1 in menu->examples->topics FileIO

FileIO means input / output of files.

A text file is a collection of text, chars, numbers.
To read a file automatically we need to know how the data in the file is formatted.

Seperation can be newline, space, comma.

We will explore different techniques to get the numbers out of the file.

Maybe we can read the data in, but have to store them in a special way. Then we make our own "class". The class being an abstract structure.

An example Class can be a record of a name and an age.


class Record {
String name;
int age;
}

every time we do

Record person1 = new Record ( "Karel de Grote", 44 );

So we store age and name in this "record".
We can also make arrays of these Records:

Record[] persons = new Record [50];

Now we can store 50 of these persons.

Much more complex Classes can be made the same way.

The most used way nowadays to format data is XML.
Processing has an datastructure called XMLElement.
See this page:

http://processing.org/reference/XMLElement.html

With XML we can get the data from for instance twitter and display the tweets as text.

See this former post about that:
http://flashscriptingwonders.blogspot.com/2011/01/processing-and-twitter.html 

A minimal XML example can be found here:
http://www.learningprocessing.com/tutorials/simpleML/ 

This is a library for doing yahoo searches:
http://www.learningprocessing.com/tutorials/yahoo/

samedi 19 février 2011

Data in Array - basics

We will expand our drawing capabilities, and meet lots of tricks on the way. First two ways to make a list of data. With a list, called an array, we avoid having to give names to each data individually. We kan collect the data in the array and get them in our drawing by calling an element: data[elementNumber]. Mind the square brackets. Also do remember the first element is 0 (zero) and not one.

There are two ways of declaring an array, without, or with the elements.

Main example:

//---------------------------------
//-------declarations-----------
//---------------------------------
int numberOfElements = 10;
int[] data1 = new int[numberOfElements];//making data automatically
int[] data2 = { 7,3,6,34,2,34,5,6,87,33 };//making data by hand
//---------------------------------
//------setup------------
//---------------------------------
void setup() {
size(320, 240);
background(176);
stroke(10);
line(5,5, 315, 5);
line(315, 5, 315, 235);
line(315, 235, 5, 235);
line(5 , 235, 5,5);
//---------------------------------
//making data automatically (could also be loading the data from an external source)
for (int i = 0; i < numberOfElements; i++) 


data1[i] = i*10; 


//--------------------------------- 
//--------draw------------- 
//--------------------------------- 
void draw() { 
for (int i = 0; i < numberOfElements; i++ ) 

//-----------data1---------------- 
strokeWeight(1);//make a thin line 
stroke(0); 
line(i*20, 160, i*20, 160 - data1[i] ); 
//----------data2----------------- 
strokeWeight(4);//make a thick line 
stroke(100);//grey colored 
line(i*20, 160, i*20, 160 + data2[i] );



Then we add some tricks, like making different drawing on keyinput, using a "showmode variable" and keypressed, see former post.

Then we add some images to the drawing of the data, for instance as a background, or accompanying the individual data using:

PImage b;
b = loadImage("someBackground.jpg");
image(b, 0, 0);


Then we add some typography, to indicate the individual data or to give our masterpiece a title:
For this we create a font in our sketchfolder using menu->tools->create font.

You can get the whole example here:
www.contrechoc.com/crosslab/data2_arrays.zip

Tutorials about Processing are very abundant, this one i came across looking for the rotation of a text:
http://www.learningprocessing.com/examples/chapter-17/example-17-5-rotating-text/
But this one rotates the whole canvas.
To rotate only a bit of the text you have to separate the textbit from the rest of the canvas by


pushmatrix();
rotate(.01);//parameter in radians
textFont(f);
popmatrix();


The pushmatrix and the popmatrix isolate the bit within from the canvas as a whole.

jeudi 17 février 2011

Array wonders

We start with the ARRAYS from the section learning of the Processing tutorials.
We slightly modify the example:

// Example: 2D Array
size(400,400);
int cols = 5;
int rows = 5;
// Declare 2D array
int[][] myArray = new int[cols][rows];
int cellWidthHeight = 80;

int showMode = 0;//see later on
//
void setup(){
// Initialize 2D array values RANDOM
for (int i = 0; i < cols; i++) 

{
for (int j = 0; j < rows; j++)
{
myArray[i][j] = int(random(255));
}
}
}
//
void draw(){
// Draw points
for (int i = 0; i < cols; i++)
{
for (int j = 0; j < rows; j++)
{
fill(myArray[i][j]);
rect(i*cellWidthHeight, j*cellWidthHeight,cellWidthHeight,cellWidthHeight); point(i,j);
}
}
}


But we see only one representation, 2D, we would like to see more perspectives, for instance on a line, or on a circle.
For this we make showModes, and depending on a showmode the view should change.
We make the keys of the keyboard interactive and use keypressed to choose a mode:

void keyPressed() {
 if ( key == 1 ) showMode = 1;
 if ( key == 2 ) showMode = 2;
 
if ( key == 3 ) showMode = 3;
}

like that we can swith between "perspectives" of the same data.

void draw(){
if ( showMode == 1 ){
// Draw points
for (int i = 0; i < cols; i++)
{
for (int j = 0; j < rows; j++)
{
fill(myArray[i][j]);
rect(i*cellWidthHeight, j*cellWidthHeight,cellWidthHeight,cellWidthHeight); point(i,j);
}

}
if ( showMode == 2 ){
 //do something else
}

if ( showMode == 3 ){
 //do something else
}
}

Now we can play around in diffeent primitive visualisations of the data.
source code: http://www.contrechoc.com/crosslab/array.pde

dimanche 13 février 2011

Starting with Processing

Dude, Where's the Timeline? This Sucks… / Awesome! A Flash Killer!

We're not targeting the same audience Flash. If we wanted to make a Flash killer, we'd have set out to do that and our stated purpose would have been more specific.....

see: http://wiki.processing.org/w/FAQ

So we will explore PROCESSING.....
http://www.processing.org/

take a look at the tutorials, under the tab learning, explore
Coordinate System and Shapes
the array examples in the Processing Programming Window
then
Two-Dimensional Arrays
and start with learning to draw
Overview

then start programming yourself!

Since we have collected data this week, we need to know what an array is and how to plot this array using the most simple techniques of making a line......

This is my very first masterpiece: landscaping by lines:

void setup() {
size(320, 240);
background(176);
stroke(10);
line(5,5, 315, 5);
line(315, 5, 315, 235);
line(315, 235, 5, 235);
line(5 , 235, 5,5);
}

void draw() {
for (int i = 5; i < 315; i+=6) 


float cosWave = 50* cos(float(i)/20*PI); 
line(i, 160, i, 160 - i/3 ); 
line(i+ 2, 80, i+2, 80 + i/3 ); 
line(i+ 4, 80, i+4, 160 -cosWave ); 

}

lundi 31 janvier 2011

Processing and Twitter

Of course, just when twitter is working in Flash, somebody wants it in Processing.

http://tinkerlondon.com/now/2010/09/14/oauth-twitter-and-processing/
http://twitter4j.org/en/index.html#download

The most difficult thing is to get the Processing lib right (wrong?). 

But do we really need this?
Couldn't we call the same PHP file we used in the last FLASH script?

Better still, there is XMLElement in Processing:


XMLElement xml;

void setup() {
size(800, 480);
xml = new XMLElement(this, "http://twitter.com/statuses/user_timeline/111370674.rss");
}

void draw() {

println( " number of xml children " + xml.getChildCount() );

XMLElement myChannel = xml.getChild(0);
println( " number of xml children " + myChannel.getChildCount() );

XMLElement[] tweets = myChannel.getChildren("item");

for (int i = 0; i < tweets.length; i++) { fill(0); textSize(9);

println(i + " " + tweets[i].getChild(0) ); 
text( tweets[i].getChild(0).getContent() , 10, 20 + i*30); 
} noLoop(); 
}

dimanche 16 janvier 2011

Twitter in FLASH (using OAUTH)

Twitter and Flash, twitter in your FLASH movie, getting the tweets, catching some significant words and provoke a FLASH movie reaction to your tweets....

Getting your twitter timeline is just using the rssfeed of your twitter account, for example contrechoc tweets:
http://www.contrechoc.com/crosslab/twitterRSS/twitter.php

a PHP file which consists of:
$twitterFeed = 'http://twitter.com/statuses/user_timeline/111370674.rss';
$outputFeed = @file_get_contents($twitterFeed);
print $outputFeed;

so the most important line is
http://twitter.com/statuses/user_timeline/111370674.rss

everyone can do this, you can get your twitter number here:
http://api.twitter.com/1/users/show.xml?screen_name=contrechoc
instead of contrechoc, put your own twittername.
or use:
http://idfromuser.com to get your twitter unique key.
Then you see the number above the name line. (This page is also a nice example of XML.)
This page gives simple examples how to use twitter data on your site using php:
http://www.problogdesign.com/wordpress/how-to-get-your-twitter-follower-number-in-plain-text/

More difficult is making a tweet.

Some special twitter vocabulary:
Sending a tweet is called "Updating status". Getting the tweets is called: "Getting Timeline". Then there is: "Sending and receiving direct messages".

For these acctions to be programmed we need to log in into our twitter account, which was rather easy some time ago. The script for this, often done by a programmer, needed to incorporate the login and password. But this was giving your credentials away, letting your password lying around on a desk of somebody else.

Nowadays the script can be made without giving away your credentials using OAUTH. But this security makes life much more complex.

We have to know a little bit about OAUTH, which cannot be done using FLASH. We need a PHP library as an intermediate between the "database" Twitter and our FLASH movie.

What is OAUTH?
 http://dev.twitter.com/pages/oauth_faq

On this page there is an example illustrating the steps to get an app functioning with OAUTH:
http://blogs.sitepoint.com/2010/08/17/oauth-explained-with-foursquar/

Go to http://foursquare.com/ and experience how this looks.

This is a nice graphical representation of this OAUTH authentication process:
http://developers.new.digg.com/authentication

The PHP library we use is the lib of Abraham Williams, which you can get here:
https://github.com/abraham/twitteroauth

Then you need your sercret key and token as described in the documentation at
http://dev.twitter.com/pages/auth
and change the files using your own secret key.

At this lib I added a simple PHP file, which after logging in just writes an update Status:
echo $connection->post('statuses/update', array('status' => $statusText.' at '.date(DATE_RFC822)));


http://www.contrechoc.com/crosslab/abrahamTwitter/writeStatusShort.php?statusText=hello world

From this last line Hello World can be twittered.... (if you are logged in...see OAUTH description).

So putting the things together gives a movie, getting the last tweets, and being able to submit a tweet:
http://www.contrechoc.com/crosslab/abrahamTwitter/twitterFlashWithInput.html

of course as an example this is giving contrechoc's tweets (rssfeed)- submitting tweets is only possible when logged in...the redirection page has to be altered.

FLASH

Then we return to FLASH scripting, to get a media response to a tweet, we will search for a string in a bit of text (tweet = text):

for this we need a RegExp object:
var myPattern:RegExp = /bestseller/gi;

then we can search a String for this RegExp : (
var bitOfText: String = "when the sea of inspiration is empty, all fishing for new ideas is in vain, unless you are a bestseller";
//coming from a tweet for example
if ( bitOfText.search(myPattern1) != -1 )
             {
                 trace ("found ", myPattern );
//do something with it!
             }

When we have found "bestseller", then we can use the media template to show an image, or start a video, sound etc.

We need the FLASH movie also to get updates itself. For this we use a timer:

var myTimer: Timer;
myTimer = new Timer(500);
myTimer.addEventListener("timer", timerHandler);
myTimer.start();

function timerHandler(event:TimerEvent):void {
   //function to get rssfeed from twitter and go to search for certain words
}

The file for this last example can be found here:
http://www.contrechoc.com/crosslab/twitter_media_Example.zip
When the FLASH movie is not the right version, you can take the script from the textfile in the folder, take a new FLASH file and copy this script inside the actions window. To get your own tweets inside a flash, you should alter the rssFeedURL inside the script.

To write yourself tweets from your FLASH, as told, you need the whole bunch of PHP files and get yourself secret keys etc from twitter.

This is an example of FLASH with OAUTH, which won't really work for you, because it is works only when I log in....
http://www.contrechoc.com/crosslab/abrahamTwitter/twitterFlashWithInput.html

Extra:
search a word in all tweets:
http://search.twitter.com/search.atom?q=hello

dimanche 9 janvier 2011

Database excercizes

Email
We practiced making a table. Now look at email as a database-table, find all the necessary fields (and what is missing or not working for a single table?)

Twitter
Look at twitter as database, the same questions. Get to your twitter account, see how the twittering works from the database side. Look here:
In class links are shown for flash showing tweets, and submitting new tweets.

Layar
database, how to do this yourself
now  we understand what we did at hoppala:
http://augmentation.hoppala.eu/
we can find the MYSQL code to make the layar database on our own free server without the hoppala tag:
http://layar.pbworks.com/w/page/30832324/First%20Layar%20Tutorial%20-%20Create%20a%20simple%20layer
make this table on your server!
See this post:
http://crosslabminor-layar.blogspot.com/2010/09/make-layar-layer-hard-way.html

insert
Inserting records in a table from a html page makes life easier:
A link will be shown in class (fearing database injections!) which inserts records in my layar database.
http://www.contrechoc.com/XXX/xxx

Second Life....
Nice 3D world. In fact, it is just a database visualisation. We have put a microphone somewhere, which records what is said in it's neighbourhood. The microphone is illustrating that everything in this world is recorded. The owner didn't want to be reminded of this fact!
http://www.nuggetkidd.byethost11.com/sl/loadToFlash_Nugget_Kidd.php
gives the raw data, which can be shown in a (undesigned) flash movie:
http://www.nuggetkidd.byethost11.com/minorCourse/loadDB_Nugget_Kidd.html

The World
Is our world just a database?

http://rop.gonggri.jp/?p=442

Check this out:
http://www.online-tech-tips.com/google-softwaretips/use-gmail-as-an-online-database-with-super-fast-search/