Thursday, August 23, 2012

HTML5 Data Attributes: data-*

Data attribute provides to define custom data attributes in HTML5. Data attribute format is "data-*" that "*" means desired custom attribute name. This useful data attribute has very simple usage.

Example: If you need row index number of a table.
<table>
  <tr>
    <td>Foo</td>
    <td><a href="#" class="to-see" data-row-index="23"> Check index </a></td>
  </tr>
  <tr>
    <td>Bar</td>
    <td><a href="#" class="to-see" data-row-index="25"> Check index </a></td>
  </tr>
</table>
jQuery(document).ready(function() {   
    $(".to-see").click(function(e) {
        e.preventDefault();
        var index = $(this).data("row-index"); 
        if (index < 25) {
            $(this).hide();
        }
    });
});
It would be before clicking check index:
After clicking check index, it would look like:

Thursday, August 2, 2012

jQuery plugins-2: icanhaz

The second part of useful jQuery plugins is icanhaz.

icanhaz: Icanhaz simple and powerful client-side templating.
Example: template part
<script type="text/html" id="sampleLine">
    <tr>
 <td>{{shape}}</td>
 <td>{{color}}</td>
    </tr>
</script>
Example: main part
<input type="button" value="Populate" />
<table id="sampleTable">
    <thead>
        <tr>
     <th>Shape</th>
     <th>Color</th>
 </tr>
    </thead>
    <tbody id="itemContainer">
    </tbody>
</table>
jQuery(document).ready(function() {
    var dynamicContentObject = { };
    var result;
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "samplePopulate.php",
        async:false,
        success: function( data ) {
            result= data;
        } 
    });
 
    dynamicContentObject['shape'] = result.shape;
    dynamicContentObject['color'] = result.color;
  
    var line = ich.sampleLine(dynamicContentObject); 
        $("tbody#itemContainer").append(line); 
});
It would be before clicking Populate button:
After clicking Populate button, it would look like:

icanhaz website is: icanhaz

Wednesday, July 18, 2012

jQuery plugins: timeago, stepy, datepicker

Here some useful jQuery plugins that I use in my projects.

timeago: timeago jQuery plugin provides convert timestamp values to relative time.
Example:
<abbr class="timeago" title="1995-09-20T015:04:23Z">September 20, 1995</abbr>
jQuery(document).ready(function() {
    jQuery("abbr.timeago").timeago();
});
It would look :
If you want to support timestamps in the future, you can set it like:
    $.timeago.settings.allowFuture = true;
Then it would look :

stepy: stepy jQuery plugin provides create custom wizard that based on FormToWizard.
Example:
<form id="form_stepy"> 
    <fieldset title="Step1">
        <legend>Description of step 1</legend>
    </fieldset>
    <fieldset title="Step2">
        <legend>Description of step 2</legend>
    </fieldset>
</form>
jQuery(document).ready(function() {
    $('#form_stepy').stepy({
        block:        true,
        titleClick:   true
    });
});
It would look :

datepicker: datepicker jQuery plugin provides to use a popup calendar input fields.
Example:
<p>Date:<input type="text" id="mydatepicker"> </p>
jQuery(document).ready(function() {
    $(function() {
        $( "#mydatepicker" ).datepicker();
    });
});
It would look :
plugins websites are: timeago stepy datepicker

Friday, January 6, 2012

K-means clustering algorithm in R

Cluster analysis in other terms unsupervised learning, is the process of placement a set of object into groups. These groups called clusters, so that objects in the same group are more similar to each other than other groups. The objective of the clustering is to determine the essential grouping a set of unlabeled data. Clustering algorithms can be classified according to their cluster model. These base models are connectivity, centroid, distribution, density, subspace and group models. Some famous clustering algorithms of these cluster models are hierarchical clustering (connectivity based), k-means clustering (centroid based), Expectation-Maximization algorithm (distribution based) and DBSCAN (density based).
K-means algorithm is one of the most popular basic clustering algorithm. The main idea is to define k centroids, one for each group and then to take each point belonging to a data set and associate it to the nearest centroid. After that re-calculate k new centroids provided by a loop, centroids of the clusters resulting from the previous stage. K-means algorithm implemented in R language is here. Note that this algorithm implementation is made example by Programming Collective Intelligence book.
The cluster function returns a list of list that each list consists of instances of each cluster.

kcluster <- function(data_matrix,k){
  numOfRow <- nrow(data_matrix)
  numOfCol <- ncol(data_matrix)
  #minVal is a vector that contains min values in columns
  minVal <- apply(data_matrix,2,min)
  minVal <- as.vector(minVal)
  #maxVal is a vector that contains max values in columns
  maxVal <- apply(data_matrix,2,max)
  maxVal <- as.vector(maxVal)
  #difference is a vector that contains difference between 
  # min and max values in columns
  difference <- as.vector(maxVal - minVal)
  ClusterList <- list()
 
  #Create k randomly placed centroids
  for (j in 1:k){
    #multiply each differences to element of uniform dist on (0,1)
    randed_diff <- as.vector(difference * runif(numOfCol,0,1))
    randed_diff <- as.vector(randed_diff + minVal)
    ClusterList[[j]] <- randed_diff
  }
  for (i in 1:100){
    #print(paste('Iteration', i))
    bestMatches <-rep(list(list()),k)
  
    #Find which centroid is the closest for each row
    for(j in 1:numOfRow){
      CurrentRow <- c(data_matrix[j,])
      bestMatch <- 1
      for(i in 1:k){
        dist_1 <- sqrt(sum((ClusterList[[i]] - CurrentRow) ** 2))
        dist_2 <- sqrt(sum((ClusterList[[bestMatch]] -CurrentRow) ** 2))
        if(dist_1 < dist_2)
        bestMatch <- i
      } 
      bestMatches[[c(bestMatch,j)]] <- j
    }
    #Move the centroids to the average of their members
    for(i in 1:k){
      avgs <- matrix(0,1,numOfCol)
      temp <-c()
      if(length(bestMatches[[i]]) > 0){
        for(i in bestMatches[[i]]){
          temp <- append(temp,i)
        }
        for(index in temp){
          avgs <-avgs+data_matrix[index,]
        }
        avgs<- avgs/length(temp)
        ClusterList[[i]] <- avgs 
      }
    }
  }
  return(bestMatches) 
}

Reference: Segaran,T., Programming Collective Intelligence, 2007, O'Reilly Media.