Android - Communication with Services

Tuesday 9 December 2014



As defined by the developer.android site a Service is a application component that can perform long running tasks in the background without an user interface. It can run on a separate process or on the same process as the Activity that started the Service and it will continue to run in the background even if the user switches to another application. Additionally a component can bind to a service to interact with it or even perform inter process communication. We will look into how to make this work but first we must understand the two forms a Service might take:
Bound form - In bound form an application component binds to the Service and allows Components and Service to interact with each other.
Started Free Form - Once started a service can run if free indefinitely or till the task completes depending or restart itself with a null or the same intent depending upon the use.

Creating the Service:

We can create a Service by extending the Service class of Android and overriding the callback methods. Also we need to declare the service in the Manifest file of the application. To have a clear idea of the running have a look at what might be the life cycle of a Service in Android in both bound and started form.

Once running, a service can notify the user of events using Toast Notifications or Status Bar Notifications.For a detailed understanding you can go through the examples in the developer site : http://developer.android.com/guide/components/services.html

Bound Service and Communication:
There are three cases that we will discuss which are enumerated below:
1. When the Service and the Application both belong to the same process then by implementing a binder they can communicate by calling public methods of the Service [TODO]
2. Implementing a Messenger to handle IPC requests
3. Implementing AIDL to allow the operating system to pass the message between boundaries.

In this post we will handle only case one after which we will follow up on the other cases in the upcoming posts. In our example we call a Activity that fires up a service if it is not running which then which then fires up the activity based on a boolean value present in the activity.The code along with the explanation in comments is given below.

//MainActivity.java
package com.example.activityservicecommunication;

import com.example.activityservicecommunication.MyService.MyBinder;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends Activity {
 
 private final String serviceName = "com.example.activityservicecommunication.MyService";
 private boolean isRanging = false;
 
 MyService myservice; //stores the current instance of the Service
 boolean isBound = false; //value to check if the current instance is present
 
 /**
  * This connection is given which assigns our service class with the instance of the 
  * running service when the activity binds to the service and sets the value of the bound
  * variable as true.
  */
 private ServiceConnection myConnection = new ServiceConnection(){

  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
   MyBinder binder = (MyBinder) service;
   myservice = binder.getService();
   isBound = true;
  }

  @Override
  public void onServiceDisconnected(ComponentName name) {
   isBound = false;
  }
  
 };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(isMonitoringServiceRunning()){
         //donot fire up
         Toast.makeText(getApplicationContext(), "Service already running", Toast.LENGTH_SHORT).show();
        }else{
         //fire up the service
         Toast.makeText(getApplicationContext(), "Starting Service", Toast.LENGTH_SHORT).show();
         Intent serviceIntent = new Intent(getApplicationContext(),MyService.class);
         bindService(serviceIntent,myConnection,Context.BIND_AUTO_CREATE);
        }
        //simulate the changing values of the variables
        new Handler().postDelayed(new Runnable(){

   @Override
   public void run() {
    isRanging = true;
    if(isBound){
     Toast.makeText(getApplicationContext(), "You should get Notifcation now", Toast.LENGTH_SHORT).show();
     myservice.setRanging();
    }
    new Handler().postDelayed(new Runnable(){

     @Override
     public void run() {
      isRanging = false;
      if(isBound){
       Toast.makeText(getApplicationContext(), "You should get Notifcation now", Toast.LENGTH_SHORT).show();
       myservice.unsetRanging();
      }
     }
     
    }, 5000);
   }
         
        }, 5000);
    }
    

 @Override
 protected void onStop() {
  super.onStop();
  if(isBound){
   unbindService(myConnection);
   isBound = false;
  }
 }




 private boolean isMonitoringServiceRunning(){
     ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
     for(RunningServiceInfo service:manager.getRunningServices(Integer.MAX_VALUE)){
      Log.d("MESSAGE",service.service.getClassName());
      if(serviceName.equals(service.service.getClassName())){
       return true;
      }
     }
     return false;
    }
}



package com.example.activityservicecommunication;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {
 
 private final IBinder mbinder = new MyBinder();
 private boolean isRanging = false;
 private boolean prevValue = false;
 private NotificationManager notificationManager;
 private static final int NOTIFICATION_ID = 123;
 
 public class MyBinder extends Binder{
  MyService getService(){
   return MyService.this;
  }
 }

 @Override
 public IBinder onBind(Intent intent) {
  return mbinder;
 }

 @Override
 public void onCreate() {
  notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  new Thread(){

   @Override
   public void run() {
    while(true){
     if(isRanging!=prevValue){
      postNotification("Rabging Value Changed");
      prevValue = isRanging;
     }
    }
   }

   
  }.start();
  super.onCreate();
 }
 
 public void setRanging(){
  isRanging = true;
 }
 
 public void unsetRanging(){
  isRanging = false;
 }
 
 private void postNotification(String msg) {
     Intent notifyIntent = new Intent(MyService.this, MyService.class);
     notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
     PendingIntent pendingIntent = PendingIntent.getActivities(
       MyService.this,
         0,
         new Intent[]{notifyIntent},
         PendingIntent.FLAG_UPDATE_CURRENT);
     Notification notification = new Notification.Builder(MyService.this)
         .setSmallIcon(R.drawable.beacon_gray)
         .setContentTitle("Notify Demo")
         .setContentText(msg)
         .setAutoCancel(true)
         .setContentIntent(pendingIntent)
         .build();
     notification.defaults |= Notification.DEFAULT_SOUND;
     notification.defaults |= Notification.DEFAULT_LIGHTS;
     notificationManager.notify(NOTIFICATION_ID, notification);
   }

}  

Put in some xml layout according to the code and register the service in the manifest. You should see two notifications coming up according to when the activity changes the isRanging value in the Service via the public methods.

Largest Contiguous Subarray Sum in O(n) : Kadane's Algorithm

Saturday 6 September 2014



Another important algorithm that is commonly used for finding the largest contiguous subarray sum in linear time is Kadane's algorithm. The pseudocode for the algorithmm is given below:

msf = 0
meh = 0
for each element in the array
    meh = meh + A[i]
    if meh < 0:
        meh = 0
    if msf < meh:
        msf = meh
return msf

Russian Peasant Multiplication

Saturday 30 August 2014
Following is an algorithm to multiply two numbers without using the multiplication operator.Although there are other ways of doing this like using bit-wise operators this method is particularly mentioned because it is named the Russian Peasant Multiplication.

int res = 0;
while(b>0){
    if(b&1==0)
        res = res + a;
    a = a << 1;
    b = b >> 1;
}
return res; 

XOR Linked List

Saturday 9 August 2014
It is a doubly linked list with an advantage of storage requirements than the previous by storing only one pointer. The pointer stores the XOR of the previous and the next node.
 ...  A        B         C         D         E  ...
         <–>  A⊕C  <->  B⊕D  <->  C⊕E  <-> 
For traverisng the list in the forward direction i.e. if you are in C and you need the address of D you can XOR the location of C with the location of B giving you the location of D.Similarly in the case of moving backward to get the location of B we can XOR the location of C and D. Notice however that we always need two locations to start traversing. Hence even though the storage requirements are reduced a number of fallbacks exist between this and the doubly linked lists.

The disadvantages of using a XOR linked list include :
1. Less space requirement increases code complexity
2. Garbage collection schemes wont work with data structures that donot contain literal pointers
3. XOR of pointers is not defined in some context as in C hence need to convert them to integers and store
4. Ability to delete a node knowing only the address of the node is not present
5. Ability to insert a node knowing only its address is not present

The program below shows a doubly linked list using a single pointer to the next node with add and display functions.
 
#include<iostream>
#include<cstdlib>
using namespace std;

struct Node {
 int data;
 unsigned int next;
}*start,*end,*newNode;

typedef struct Node NODE;

int menu(){
 int choice;
 cout << "1. Add" << endl;
 cout << "2. Display" << endl;
 cout << "3. Exit" << endl;
 cin >> choice;
 return choice;
}

void add(){
 newNode = (NODE *)malloc(sizeof(NODE));
 newNode->next = 0;
 cout << "Enter nodes data:" ;
 cin >> (newNode->data);
 if(start==NULL){
  start = end = newNode;
 }else{
  newNode->next = (unsigned int)end ^ 0;
  end->next = (end->next^0)^(unsigned int)newNode;
  end=newNode;
 }
}

void display(){
 NODE *temp,*curr,*prev;
 prev = curr = temp = NULL;
 for ( curr = start; curr != end ; temp = prev ,\
    prev = curr , curr = ( NODE * ) ( curr -> next ^ (unsigned int)temp ) )
       cout << curr -> data << endl;
    cout << curr -> data << endl;
}

int main()
{
 int choice;
 while(1){
  choice = menu();
  if(choice==3)
   break;
  switch(choice){
  case 1: add();break;
  case 2: display();break;
  }
 }
 return 0;
} 

Getting the next largest palindrome

Thursday 31 July 2014
For a given number n we need to find the numerically larger number that is a palindrome. The simple approach which is not good for large numbers is to check if the number is palindrome and increment by 1 till we find the next number which is  a palindrome.

A smarter algorithm is as follows :
1. Split the string into the left and right halfs
2. Compare the last digit in the left half and the first digit in the right half.
     a. If right is greater than the left, increment the left and stop
     b. If right is less than the left, stop
     c. If right is equal to the left, then continue the step 3 with the next the previous digit and so on
3. Take the left half and append the reverse to it.

Now complications may arise when the number is odd length and when the new palindrome is of greater length than the current number.So for this we check if our new palindrome is less than the given number. If so than we start increasing our middle digit by 1 and mirroring it  to the other digits. If the middle digit is a 9 than we need to change it to zero and update the next digit by 1 or make it zero if it is a 9 until we reach a number that is not 9. Else we need to add 1 to the start of the number.The C code for the procedure is given below:

                cin >> str;
  s = str;
  int inc,dec;
  inc = s.size()/2;
  dec = inc;
  if(s.size()%2==0)
   dec--;
  for(int i=inc,j=dec;i<s.size() && j>=0;i++,j--)
   s[i] = s[j];
  while(s<=str && s.size()<=str.size()){
   int i=dec,j=inc;
   while((s[i]-'0')==9 && i>=0 && j<=s.size()){
    s[i] = s[j] = '0';
    i--;
    j++;
   }
   if(i<0){
    s = '1' + s;
    int l = s[s.size()-1] - '0';
    l++;
    s[s.size()-1] = (l+'0');
   }else{
    int l = s[i] - '0';
    l++;
    s[i]=s[j]=(l+'0');
   }
  }
  cout << s << endl;

Reverse Polish Notation : Expression Transformation

Tuesday 29 July 2014
Reverse Polish notation (RPN) is a mathematical notation in which every operator follows all of its operands, in contrast to Polish notation, which puts the operator in the prefix position. It is also known as postfix notation and is parenthesis-free as long as operator arities are fixed. The description "Polish" refers to the nationality of logician Jan Ɓukasiewicz, who invented (prefix) Polish notation in the 1920s.In computer science, postfix notation is often used in stack-based and concatenative programming languages. It is also common in dataflow and pipeline-based systems, including Unix pipelines.

The C code for converting an expression into RPN format as required in SPOJ problem 4 is done using one stack to store the members and one integer to denote the opening brackets. The function printRPN takes a string expression and prints the RPN  equivalent.

void printRPN(string s){
 stack<string> members;
 int opening_brackets = 0;
 for(int i=0;i<s.length();i++){
  if(s[i]==' ')continue;
  else
  if(s[i]=='(')opening_brackets++;
  else
  if(s[i]==')'){
   opening_brackets--;
   string op1 = members.top();members.pop();
   string op2 = members.top();members.pop();
   string op3 = members.top();members.pop();
   op3.append(op1);
   op3.append(op2);
   members.push(op3);
  }else
  members.push(string(1,s[i]));
 }
 cout << members.top() << endl;
}

Substring Matching Algorithms

Substring matching is an important part of any algorithmic problem. There are different complexities to consider about like the size of the string, the size of the pattern, the running time etc. Considering all these we list down some of the approaches which is used in solving the substring problem.

Naive Brute Force approach :

In the naive approach we iterate over all the elements of the text and start matching for each character of the pattern.If it doesnot match we advance the start of the match of the text by one character and again check for the presence of the pattern. Since for each character of the text we match the next characters for the pattern the worst case time complexity if n is the length of the pattern and m is the length of the text is O(mn). The code is mentioned below :

void naiveBruteForce(string a,string b){
 bool isMatched = true;
 int i=0;
 for(i=0;i<=a.length() - b.length();i++){
  isMatched = true;
   for(int j=0;j<b.length();j++){
    if(a[i+j] != b[j])
     isMatched = false;
   }
  if(isMatched)
   break;
 }
 cout << isMatched << " offset :" <<  i << endl;
}

Rabin Karp Algorithm :

In the Rabin Karp method we try to eliminate the two inner loop computation of the naive algorithm in which we try to match two strings. Instead of matching two strings we assign a value by using a hash of the characters. We precompute the hash of the pattern and we only check the if the hash of the substring of the text matches the pattern's hash value. Again problem will arise if the number of characters is big or the length of the string is big in which case we can use a modular hash function. But in this two strings may have the same value even if they do not match, thus the modulus M should be taken a large number. A sample code in which we have taken squares of the ascii value of the characters as a hash value is given below:

void rabinKarp(string a,string b){
 int hashsub = 0,tmp,tmp1,hash = 0;
 for(int i=0;i&ltb.length();i++){
  tmp = b[i];
  tmp1 = a[i];
  hashsub += tmp * tmp;
  hash += tmp1 * tmp1;
 }
 for(int i=b.length();i&lta.length();i++){
  if(hash==hashsub)
   cout << "offset :" << i - b.length() << endl;
  tmp = a[i - b.length()];
  tmp1 = a[i];
  hash -= (tmp * tmp);
  hash += (tmp1 * tmp1);
 }
}

Knuth-Morris-Pratt Algorithm:

In KMP algorithm we use the fact that if a substring match fails then we know by precomputing the pattern that we can certainly shift by a certain amount in which the substring wont match. The precomputing is done by finding the longest substring of the pattern that is a prefix as well as a suffix. This can be done in the following way- Consider a string in the pattern b1b2...bk...bj. Sup pose we know that the longest substring that is a prefix as well as a suffix is the substring upto k. Then F[j] = k, and if k+1th character is equal to the j+1th character then F[j+1] = F[j] + 1. Else there would be some other substring smaller than bk that would be initial and terminal substring then it would also be a border string of b1...bk. Hence if the above condition is false then we check for the string F[F[j]] for the initial and terminal and this check continues until we find a border or there is no border at all in which case we inialize it to  . The pseudocode is as follows:
Prefix-Compute-Function(Pattern):
F[1] = 0;
for j from 1 to m-1 do:
    i = F[j];
    while(bi+1 != bj+1 and i>0) i=F[i]; //reduce the search space
    if(i==0 and bi+1 != bj+1) F[j+1] = 0;
    else
    F[j+1] = i+1;

The C implimentation is given below :

int* KMP_Preprocess(string pattern){
 int *pre = (int *)malloc(sizeof(int)*pattern.length());
 memset(pre,0,pattern.length());
 for(int i=1;i<pattern.length();i++){
  pre[i] = pre[i-1];
  while(pattern[i] != pattern[pre[i]]){
   if(pre[i] == 0){
    pre[i] = -1;
    break;
   }else{
    pre[i] = pre[pre[i] - 1];
   }
  }
  pre[i] = pre[i] + 1;
 }
 return pre;
}

void KMP_Match(string a, string b){
 int *pre = KMP_Preprocess(b);
 for(int i=0,j=0;i<a.length();){
  while(a[i+j] == b[j]){
   ++j;
   if(j==b.length()){
    cout << "Match offset :" << i << endl;
    break;
   }
  }
  if(j>0){
   i+=(j-pre[j-1] > 1)?(j-pre[j-1]):1;
   j = pre[j-1];
  }else{
   ++i;
  }
 }
}

Floating Point Representation Basics

Sunday 27 July 2014
The details in this post are acquired from IEEE 764 floating point standards. Usually a real number in binary will be represented in the following format- ImIm-1…I2I1I0.F1F2…FnFn-1 where Im and Fn will be either 0 or 1 of integer and fraction parts respectively.

A finite number can also be represented by four integer components :  a sign (s), a base (b), a significand (m), and an exponent (e). Then the numerical value of the number is evaluated as (-1)s x m x be.In the binary32 format the floating point numbers are stored in the single precision format. In the single precision format there are 23 bits for the significand 8 bits for the exponent and 1 bit for the sign.

For example, the rational number 9÷2 can be converted to single precision float format as following,
9(10) ÷ 2(10) = 4.5(10) = 100.1(2)
The result said to be normalized, if it is represented with leading 1 bit, i.e. 1.001(2) x 22. Omitting this implied 1 on left extreme gives us the mantissa of float number.

In other words, the above result can be written as (-1)0 x 1.001(2) x 22 which yields the integer components as s = 0, b = 2, significand (m) = 1.001, mantissa = 001 and e = 2. The corresponding single precision floating number can be represented in binary as shown below,

Where the exponent field is supposed to be 2, yet encoded as 129 (127+2) called biased exponent.

One of the goals of the IEEE floating point standards was that you could treat the bits of a floating point number as a (signed) integer of the same size, and if you compared them that way, the values will sort into the same order as the floating point numbers they represented.
If you used a twos-complement representation for the exponent, a small positive number (i.e., with a negative exponent) would look like a very large integer because the second MSB would be set. By using a bias representation instead, you don't run into that -- a smaller exponent in the floating point number always looks like a smaller integer.

A bias of (2n-1 – 1), where n is # of bits used in exponent, is added to the exponent (e) to get biased exponent (E). So, the biased exponent (E) of single precision number can be obtained as
E = e + 127
The range of exponent in single precision format is -126 to +127. Other values are used for special symbols.

Double Precision Format:

Precision:
The smallest change that can be represented in floating point representation is called as precision. The fractional part of a single precision normalized number has exactly 23 bits of resolution, (24 bits with the implied bit). This corresponds to log(10) (223) = 6.924 = 7 (the characteristic of logarithm) decimal digits of accuracy. Similarly, in case of double precision numbers the precision is log(10) (252) = 15.654 = 16 decimal digits.

Accuracy:
Accuracy in floating point representation is governed by number of significand bits, whereas range is limited by exponent. Not all real numbers can exactly be represented in floating point format. For any numberwhich is not floating point number, there are two options for floating point approximation, say, the closest floating point number less than x as x- and the closest floating point number greater than x as x+. A rounding operation is performed on number of significant bits in the mantissa field based on the selected mode. The round down mode causes x set to x_, the round up mode causes x set to x+, the round towards zero mode causes x is either x- or x+ whichever is between zero and. The round to nearest mode sets x to x- or x+ whichever is nearest to x. Usually round to nearest is most used mode. The closeness of floating point representation to the actual value is called as accuracy.

Special Bit Patterns:
The standard defines few special floating point bit patterns. Zero can’t have most significant 1 bit, hence can’t be normalized. The hidden bit representation requires a special technique for storing zero. We will have two different bit patterns +0 and -0 for the same numerical value zero. For single precision floating point representation, these patterns are given below,

0 00000000 00000000000000000000000 = +0
1 00000000 00000000000000000000000 = -0

Similarly, the standard represents two different bit patters for +INF and -INF. The same are given below,
0 11111111 00000000000000000000000 = +INF
1 11111111 00000000000000000000000 = -INF

All of these special numbers, as well as other special numbers (below) are subnormal numbers, represented through the use of a special bit pattern in the exponent field. This slightly reduces the exponent range, but this is quite acceptable since the range is so large.

An attempt to compute expressions like 0 x INF, 0 ÷ INF, etc. make no mathematical sense. The standard calls the result of such expressions as Not a Number (NaN). Any subsequent expression with NaN yields NaN. The representation of NaN has non-zero significand and all 1s in the exponent field. These are shown below for single precision format (x is don’t care bits),
x 11111111 1m0000000000000000000000
Where m can be 0 or 1. This gives us two different representations of NaN.
0 11111111 110000000000000000000000 _____________ Signaling NaN (SNaN)
0 11111111 100000000000000000000000 _____________Quiet NaN (QNaN)
Usually QNaN and SNaN are used for error handling. QNaN do not raise any exceptions as they propagate through most operations. Whereas SNaN are which when consumed by most operations will raise an invalid exception.

Overflow and Underflow:
Overflow is said to occur when the true result of an arithmetic operation is finite but larger in magnitude than the largest floating point number which can be stored using the given precision. Underflow is said to occur when the true result of an arithmetic operation is smaller in magnitude (infinitesimal) than the smallest normalized floating point number which can be stored. Overflow can’t be ignored in calculations whereas underflow can effectively be replaced by zero.


 


Segmented Sieve of Eratosthenes

If you have enough space to store all primes upto sqrt(b) then you can sieve for primes in the range a to b using additional space O(b - a) :

To do this let us take an example of the #SPOJ problem 2 : PRIME1 where we are given the upper limit as 1000000000 which is quite big if we want to store all the numbers in an array although we can store them by reducing them to array where each bit of a number stores whether the corresponding number is a prime or not i.e. if there are 64 numbers in the sieve we need two integers of 32 bits to store information of whether the number is prime or not.

Another method is if you have space to store upto square root of upper limit using sieve of eratosthenes then we can calculate the sieve of b-a from the sieve already present. The way to do it is mentioned below :

1. First get the sieve upto the square root of upper limit which in this case is  1000000000.  For 1000000000 the square root comes near 31625. Hence we create an array pre_sieve[31625] and fill it with the values:


pre_sieve[31265] = {1};
for(int i=2;i<=177;i++)
{
    if(pre_sieve[i] == 1)
    {
         for(int j = i*i;j< = 31264; j+=i)
             pre_sieve[j] = 0;
    }
} 
vector<int> primes;
for(int i=2;i<=31264;i++)
if(pre_sieve[i] == 1)
    primes.push_back(i);
 
Now for a range [a,b] we need to find the closest number that is in the range and is a composite number of the prime p. To do this we can divide the start of the range by p and take the floor and then multiply the resulting by p.We can then iterate in the sieve to get the primes.

for(int i=0;i<primes.size();i++)
{
     int *arr = (int *)malloc(sizeof(int)*(b-a+1));
     memset(arr,1,b-a+1);
     int prime = primes[i];
     int low = a/prime;
     low = low * prime;
     for(int j = low * 2;j<=b;j+= prime)
             arr[j] = 0 
}

Again you can reduce the space further by only sieving the odd number.

Autotools Linux : Served On The Platter #2

Monday 10 March 2014
Autotools are a great way of packaging binary applications in Linux.The autotools need to be installed by installing the auto-tools-dev and other dependencies.It uses the old Makefile way for compiling the program and checking dependencies. Here in this we take a sample C program depending on wxWidgets and openGL and build the install scripts using Autotools.Note that the directory structure is as follows :
|___Canvas
           |____src [ the source folder ]
           |         |__paint.cpp
           |____res [ the resources and data ]

Autotools uses a predefined directory for installing files and these directories are named in the autotools site.For eg. $PREFIX stands for /usr/local/ hence when you write your program make sure to use these locations.

Autoscan: We use an automated tool to generate the initial configure.scan script. In the root directory run 'autoscan' command.This will generate a configure.scan and a report there by traversing through all the directories for dependencies. Now rename this to 'configure.ac' and edit it as follows.
 
#                                               -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.

AC_PREREQ([2.69])
AC_INIT([canvas], [1.0], [saswat.cs11@iitp.ac.in])
AM_INIT_AUTOMAKE([-Wall foreign])
AC_CONFIG_SRCDIR([src/paint.cpp])
AC_CONFIG_HEADERS([config.h])

# Checks for programs.
AC_PROG_CXX

# Checks for libraries.
AM_OPTIONS_WXCONFIG
reqwx=2.4.0
AM_PATH_WXCONFIG($reqwx, wxWin=1)
if test "$wxWin" != 1; then
 AC_MSG_ERROR([
  wxWidgets must be installed on your system.
 
  Please check that wx-config is in path, the directory
  where wxWidgets libraries are installed (returned by
  'wx-config --libs' or 'wx-config --static --libs' command)
  is in LD_LIBRARY_PATH or equivalent variable and
  wxWidgets version is $reqwx or above.
  ])
fi
 
CPPFLAGS="$CPPFLAGS $WX_CPPFLAGS"
CXXFLAGS="$CXXFLAGS $WX_CXXFLAGS_ONLY"
CFLAGS="$CFLAGS $WX_CFLAGS_ONLY"
LIBS="$LIBS $WX_LIBS -lGL -lGLU -lglut `wx-config --gl-libs`"

# Checks for header files.

# Checks for typedefs, structures, and compiler characteristics.
AC_CHECK_HEADER_STDBOOL

# Checks for library functions.
AC_FUNC_MALLOC


AC_OUTPUT(Makefile src/Makefile res/Makefile)
 
Now notice the Macros in the section.AC_INIT initialize the package name and version and bug to send mail.AC_PROG_CXX checks for C++ in the system.We then check for wxWidgets in the system.This is present in their wiki for code above.Next add the FLAGS for compilation of librariesAC_OUTPUT checks for the Makefiles that should be generated as mentioned in brackets.Each must have a Makefile.am ready in them.

MAKEFILES: Each makefile.am should be as follows.In the source directory the Makefile is as follows:


bin_PROGRAMS = canvas
canvas_SOURCES = paint.cpp


The bin_PROGRAMS specifies the following binaries to be compiled and stored in the $PREFIX/bin directory.The _SOURCES specify the sources of the binaries.For the data directory the makefile should be as follows:

resdir = $(datarootdir)/@PACKAGE@
res_DATA = canvas.png chk.png crop.png curve.png erase.png ...


 We define a data directory according to the one used in the binary and the data files will be written to it.

COMMANDS: Once these files are ready run the following commands in order:
* aclocal
* automake --add-missing
* autoconf
* autoreconf -fvi
You will get your scripts.Run configure and make install to install.This project can be found in my github account :  https://github.com/saswatraj/Canvas

Objects in Javascript : Served on the Platter

Sunday 9 March 2014
The simple types of javascript are : numbers , booleans , strings , null and undefined. All other types are objects in javascript. Hence a detailed knowledge is required for manipulating objects in javascript. Remember : Objects in javascript are class free. They are basically name value pairs surrounded by curly braces.Objects are always passed around by reference.

Initialization :

var empty_object = {}; 
var exobj = {
        'name':'saswat',
        'occupation':'student'
       };

Retireval :

exobj['name'] //returns 'saswat'
exobj.name    //preferred and more cleaner
exobj.status  // not present hence returns undefined
 

For filling in default values for undefined objects use the '||' operator.Attempting to retrieve values from undefined will throw a TypeError exception.

Updation :

Updation can be done by the assignment operator. If the object does not have the property name then it is augmented to the property names present with the value that is assigned.

Prototype :

Every object in javascript inherits properties from some other object. All objects created directly inherit from the Object.prototype an object that comes along with javascript.

If we try to retrieve a value from an object and that property is not present javascript tries to retrieve the property from the obejcts prototype and then from the prototype of the prototype and so on till it reaches the Object.prototype. If it is found nowhere in the chain then it is undefined.This is called delegation in javascript.

A detailed description on Prototype will be provided in the next few platters of  inheritance in javascript.However for now we can use Object.create function which takes a prototype from which to derive the new Object. One can also assign the protoype property with an object . i.e.
 
exobj.prototype = new User() ; //user as prototype object
exobj.prototype = Object.create(User.prototype);

The difference between the two is that in Object.create the constructor is not called hence the object remains uninitialized.

If we add a new property to the prototype then the new property will show in each object derived from that prototype.

But then how do we know whether the property belongs to the object or to the prototype chain.This can be known by using the hasOwnProperty which does not look into the property chain.For example:

exobj.hasOwnProperty('name') //true
exobj.hasOwnProperty('constructor') //false


Enumeration :

For enumerating the properties of the object use the for in construct .This includes the prototype chain properties.Hence we need to filter using typeof and hasOwnProperty. Careful Note :: The elements can come in any order.

for ( property in exobj ){
    if( exobj.hasOwnProperty(property) && typeof exobj[property] == 'string')
      //do something
} 

Deletion : The delete operator can be used to remove a property from object. Deleting may allow the prototype property to be accessible.

HTTP 1.1 headers

Wednesday 29 January 2014
When a browser makes a request to a server it does in the form of requests formatted by some rules so that the server can understand what resource the browser is asking for.A normal REST http header would look like this :

POST /enlighten/rest HTTP/1.1
Host: api.opencalais.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length

licenseID=string&content=string&/paramsXML=string 

The response from the server side would look something like :

HTTP/1.1 200 OK
Content-Type: text/xml;charset=utf-8
Content-Length: length

string
 
Parts of the HTTP Request and their Significance

 Accept: audio/*; q=0.2, audio/basic 

The Accept request-header field can be used to specify certain media types which are acceptable for the response.If no Accept header field is present, then it is assumed that the client accepts all media types.

  Accept-Charset: iso-8859-5, unicode-1-1;q=0.8

The Accept-Charset request-header field can be used to indicate what character sets are acceptable for the response.The special value "*", if present in the Accept-Charset field, matches every character set (including ISO-8859-1) which is not mentioned elsewhere in the Accept-Charset field

  Accept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0

The Accept-Encoding request-header field is similar to Accept, but restricts the content-codings  that are acceptable in the response.

  Accept-Language: da, en-gb;q=0.8, en;q=0.7

Accept-Lnguages tells about the language that is preferred in the response of the output.

  Accept-Ranges: bytes

The Accept-Ranges response-header field allows the server to indicate its acceptance of range requests for a resource.This is what the internet download manager looks for to tell whether a particular resource is resumable or not.

  age-value = delta-seconds

The Age response-header field conveys the sender's estimate of the amount of time since the response (or its revalidation) was generated at the origin server. A cached response is "fresh" if its age does not exceed its freshness lifetime.Age values are non-negative decimal integers, representing time in seconds.

  Allow: GET, HEAD, PUT

The Allow entity-header field lists the set of methods supported by the resource identified by the Request-URI. The purpose of this field is strictly to inform the recipient of valid methods associated with the resource. An Allow header field MUST be present in a 405 (Method Not Allowed) response.

  Authorization  = "Authorization" ":" credentials

A user agent that wishes to authenticate itself with a server-- usually, but not necessarily, after receiving a 401 response--does so by including an Authorization request-header field with the request. The Authorization field value consists of credentials containing the authentication information of the user agent for the realm of the resource being requested.

  Cache-Control   = "Cache-Control" ":" 1#cache-directive

The Cache-Control general-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain. The directives specify behavior intended to prevent caches from adversely interfering with the request or response.

 The following Cache-Control response directives allow an origin server to override the default cacheability of a response:
public
Indicates that the response MAY be cached by any cache, even if it would normally be non-cacheable or cacheable only within a non- shared cache. (See also Authorization, section 14.8, for additional details.)
private
Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache. This allows an origin server to state that the specified parts of the

response are intended for only one user and are not a valid response for requests by other users. A private (non-shared) cache MAY cache the response.
Note: This usage of the word private only controls where the response may be cached, and cannot ensure the privacy of the message content.
no-cache
If the no-cache directive does not specify a field-name, then a cache MUST NOT use the response to satisfy a subsequent request without successful revalidation with the origin server.

  Connection: close

The Connection general-header field allows the sender to specify options that are desired for that particular connection and MUST NOT be communicated by proxies over further connections.

  Content-Length: 3495 

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

  Content-MD5   = "Content-MD5" ":" md5-digest
  md5-digest   = <base64 of 128 bit MD5 digest as per RFC 1864>

The Content-MD5 entity-header field, as defined in RFC 1864 [23], is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.)

For more headers information check RFC section for HTTP headers.

Copyright @ 2013 code-craft. Designed by Templateism | MyBloggerLab