Using API Flickr with jQuery

I built an script for my personal website, it chooses a random picture from my uploaded gallery on flickr.

I hope the comments on the code are enough for you to understand

		var flickr_APIkey = '3b68835445aa2001d41724b2f58943cd';      // get yours at: http://www.flickr.com/services/api/
		var flickr_UserId = '8847785%40N07'                          // GerManson
	
		// defining REST API URLs
		var flickr_getContactPhotos = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key="+ flickr_APIkey +"&user_id="+ flickr_UserId +"&lang=en-us&format=json&jsoncallback=?";
		var flickr_getPhotoInfo = "http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key="+ flickr_APIkey +"&lang=en-us&format=json&jsoncallback=?&photo_id=";
		
		// getting a jquery object for the body of the page, be sure to add and id to your body tag 
		var body = $("#body");
	
		$.getJSON(flickr_getContactPhotos, function(data) {
	
			// selecting a random item from the images array
			var rnd = Math.floor(Math.random() * data.photos.photo.length);
			var image = data.photos.photo[rnd];
			
			flickr_getPhotoInfo += image.id;
			
			$.getJSON(flickr_getPhotoInfo, function(info) {
				image.osecret = info.photo.originalsecret;
				image.ext = info.photo.originalformat;
				
				// building the image_url http://www.flickr.com/services/api/misc.urls.html
				var image_url = "http://farm" + image.farm + ".static.flickr.com/" + image.server + "/" + image.id + "_" + image.osecret + "_o." + image.ext; 
			
				body.css("background-image", "url("+image_url+")");
			});
			
		});

Installing a LAMP Stack on your Mac

Installing Apache, PHP5 and MySQL5 on your MacOSX is in fact a very easy task using MacPorts

1.- First of all download and install macports

2.- Make sure you have the latest port tree
Open your terminal and type

sudo port selfupdate

3.- Tell macports to install PHP MySQL and Apache

sudo port install php5 +apache2 +mysql5-server 
the "+" sign before the app names is because we will want this servers to run when starting up the system.

This process will take a while, because macports will download sources and then compile, so go grab a pizza, call your mom or play some xox 360, and be back in around 30 minutes.

4.- Once everything is installed is now time for configuration (yeah i already know you love that part)

Remember that your mac came out of the box with an apache instance installed, we need to make sure it is deactivated in order to avoid conflicts with the macports one. For doing this go to:

 System Preferences -> Sharing -> Web Sharing -> Turn Off
Init MySQL database
sudo /opt/local/lib/mysql5/bin/mysql_install_db --user=mysql
If you want to, you can change your default root password (default is empty)
/opt/local/lib/mysql5/bin/mysqladmin -u root password 'new-password'
I highly recommend you to change your default root password

5.- To start apache and mysql when your system boots do the following

sudo launchctl load -w /Library/LaunchDaemons/org.macports.apache2.plist
sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql5.plist

6.- You need to load PHP module on Apache and tell it how to handle .php files, go to the apache config file /opt/local/apache2/conf/httpd.conf and add these lines at the very bottom of the file

LoadModule php5_module modules/libphp5.so
AddType application/x-httpd-php .php
Restart apache to apply changes
sudo /opt/local/etc/LaunchDaemons/org.macports.apache2/apache2.wrapper start
sudo /opt/local/etc/LaunchDaemons/org.macports.mysql5/mysql5.wrapper start

Done!

Your web sharing folder will be at: /opt/local/apache2/htdocs/

and you will be able to open your webserver at http://localhost

If you have experience playing with apache before, remember the config file is located at /opt/local/apache2/conf/httpd.conf

Polymorphism in C#

Another primary concept of object-oriented programming is Polymorphism. It allows you to invoke derived class methods through a base class reference during run-time. This is handy when you need to assign a group of objects to an array and then invoke each of their methods. They won't necessarily have to be the same object type. However, if they're related by inheritance, you can add them to the array as the inherited type. Then if they all share the same method name, that method of each object can be invoked. This lesson will show you how to accomplish this.

A Base Class With a Virtual Method: DrawingObject.cs
using System;

public class DrawingObject
{
    public virtual void Draw()
    {
        Console.WriteLine("I'm just a generic drawing object.");
    }
}

The code shows the DrawingObject class. This will be the base class for other objects to inherit from. It has a single method named Draw(). The Draw() method has a virtual modifier. The virtual modifier indicates to derived classes that they can override this method. The Draw() method of the DrawingObject class performs a single action of printing the statement, "I'm just a generic drawing object.", to the console.

Derived Classes With Override Methods: Line.cs, Circle.cs, and Square.cs
using System;

public class Line : DrawingObject
{
    public override void Draw()
    {
        Console.WriteLine("I'm a Line.");
    }
}

public class Circle : DrawingObject
{
    public override void Draw()
    {
        Console.WriteLine("I'm a Circle.");
    }
}

public class Square : DrawingObject
{
    public override void Draw()
    {
        Console.WriteLine("I'm a Square.");
    }
}

The code shows three classes. These classes inherit the DrawingObject class. Each class has a Draw() method and each Draw() method has an override modifier. The override modifier allows a method to override the virtual method of its base class at run-time. The override will happen only if the class is referenced through a base class reference. Overriding methods must have the same signature, name and parameters, as the virtual base class method it is overriding.

Program Implementing Polymorphism: DrawDemo.cs
using System;

public class DrawDemo
{
    public static int Main( )
    {
        DrawingObject[] dObj = new DrawingObject[4];

        dObj[0] = new Line();
        dObj[1] = new Circle();
        dObj[2] = new Square();
        dObj[3] = new DrawingObject();

        foreach (DrawingObject drawObj in dObj)
        {
            drawObj.Draw();
        }

        return 0;
    }
}

The Code shows a program that uses the classes defined in Listing 9-1 and Listing 9-2. This program implements polymorphism. In the Main() method of the DrawDemo class, there is an array being created. The type of object in this array is the DrawingObject class. The array is named dObj and is being initialized to hold four objects of type DrawingObject.

Next the dObj array is initialized. Because of their inheritance relationship with the DrawingObject class, the Line, Circle, and Square classes can be assigned to the dObj array. Without this capability, you would have to create an array for each type. Inheritance allows derived objects to act like their base class, which saves work.

After the array is initialized, there is a foreach loop that looks at each element of the array. Within the foreach loop the Draw() method is invoked on each element of the dObj array. Because of polymorphism, the run-time type of each object is invoked. The type of the reference object from the dObj array is a DrawingObject. However, that doesn't matter because the derived classes override the virtual Draw() method of the DrawingObject class. This makes the overriden Draw() methods of the derived classes execute when the Draw() method is called using the DrawingObject base class reference from the dObj array. Here's what the output looks like:

Output:

I'm a Line.
I'm a Circle.
I'm a Square.
I'm just a generic drawing object.

Facebook-Like Leave a Comment Script with jQuery


We can easily create Facebook-Like textbox for leaving comments in an easy and cool way using jQuery, I am leaving an example below.

You can see an implementation working here

HTML

<textarea class="comment_empty">Write a comment</textarea><br /> <input type="submit" id="submit" value="Submit" style="display: none" />

jQuery

$(document).ready(function(){
    var submit = $("#submit");

    $("textarea").blur(function() {
        if ($(this).val() == "") {
            $(this).val("Write a comment")
                   .removeClass("comment_filled")
                   .addClass("comment_empty");
            submit.hide();
        }
    }).focus(function() {
        if ($(this).val() == "Write a comment") {
            $(this).val("")
                   .removeClass("comment_empty")
                   .addClass("comment_filled");
            submit.show();
        }
    });
});

CSS

.comment_empty {
   color: gray;
   height: 30px;
}

.comment_filled {
   color: black;
   height: 100px;
}

Javascript: The this keyword

One of the most powerful JavaScript keywords is this. Unfortunately it is hard to use if you don't exactly know how it works.

Below I explain how to use it in event handling.

Owner

The question that we'll discuss for the remainder of the page is: What does this refer to in the function doSomething()?

 
function doSomething() {
   this.style.color = '#cc0000';
}

In JavaScript this always refers to the "owner" of the function we are executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript. An onclick property, though, is owned by the HTML element it belongs to.

This "ownership" is the result of JavaScript's object oriented approach.

 
------------ window --------------------------------------
|                                          / \           |
|                                           |            |
|                                          this          |
|   ----------------                        |            |
|   | HTML element | <-- this         -----------------  |
|   ----------------      |           | doSomething() |  |
|               |         |           -----------------  |
|          --------------------                          |
|          | onclick property |                          |
|          --------------------                          |
|                                                        |
----------------------------------------------------------

If we execute doSomething() without any more preparation the this keyword refers to the window and the function tries to change the style.color of the window. Since the window doesn't have a style object the function fails miserably and produces JavaScript errors.