Tuesday, October 9, 2012

Regular expression in iOS

NSRegularExpression class is very handy when comes to matching patterns and replacing some patterns if they match. Even though Apple provides the reference on NSRegularExpression but still it doesn't has sufficient examples which could be helpful to beginners that's why I thought to share some examples.

1. How to find whether a string is matching particular regular expression.
    I will illustrate this with an example, Email validator. Assume, we want to check whether email  
   entered by user is following certain pattern or not. For this we are creating a regular expression
  @"[A-Z0-9a-z._]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
      |--User Name --|---HostName --| -- Domain---------|
  This regular expression checks for:
  a. Having at least a character before @
  b. Having at least a character between  @ and .(dot)
  c. Domain name should be between 2 to 4 characters.

 Now in objective-C we can use following method to check email validation,


-(BOOL)validateEmail:(NSString *)email {
    NSString * regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject: email];
}

2. How to replace occurrence of a pattern with replacement string in a given text string.
  
   Assume we have some patterns and replacement strings like
    Pattern               Replacement string
    :A                      GOTA
    :B                      GOTB
    :C                      GOTC

    :D                      GOTD
    :E                      GOTE
    :F                      GOTF
    :G                     GOTG



    Text string : @"this is pattern1 :A and this is pattern2 :B and again :A"
    after replacement we want result like this : @"this is pattern1 GOTA  and this is pattern2 GOTB and  
    again GOTA"

   It can be done by following lines of code:


  -(NSString*)replaceStringWithRegularExpression:(NSRegularExpression*)regex dictionary:(NSDictionary*)dict string:(NSString*)string
{
    NSArray  *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
    
    for (NSTextCheckingResult* b in matches) // Loop through matches
    {
        
        NSString* url = [string substringWithRange:b.range]; // get the actual pattern matched
        if([dict valueForKey:url]) // check if value present in dictionary
        {
            string=[string stringByReplacingOccurrencesOfString:url withString:[dict valueForKey:url]];
            return [self replaceStringWithRegularExpression:regex dictionary:dict string:string];
         // using recursion to avoid iteration when text contains same pattern multiple times
        }
    }
    return string;

}

Call above method like this:

 NSDictionary * dict=[[NSDictionary allocinitWithObjectsAndKeys:@"GOTA",@":A"@"GOTB",@":B",@"GOTC",@":C",@"GOTD",@":D",@"GOTE",@":E",@"GOTF",@":F",nil]; //Create dictionary of patters and replacement strings
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@":A|:B|:C|:D|:E|:F" options:0 error:NULL]; //create regular expression 
    NSString *str = @"this is pattern1 :A and this is pattern2 :B and again :A"; //Text string which needs to be replaced    NSString * result=[self replaceStringWithRegularExpression:regex dictionary:dict string:str];    NSLog(@"result:%@",result);


Monday, March 21, 2011

Programming Robocup server agent in Erlang?

I am planning to build an application for demonstrating the usefulness/applicability of Erlang(functional language) in Multi-agent Systems(MAS). For more information go to MAS and Multiagent Systems: A Survey.
I am implementing Robocup Soccer Simulator agents in Erlang. The architecture is taken from this paper.

----
Note: The motive behind this post is to share information with all people who are interested in Erlang and to get a feedback regarding my approach & coding style.

I will update this post as frequently as possible.

Thanks for reading the post.

Monday, August 30, 2010

Is Erlang feasible option for Robotic applications?

The answer to this question is not straight forward(yes or no). It involves a lot of study about Erlang constructs, key features and current applications. I am currently working in this area and my work is to figure out some robotic application areas where Erlang certainly can be a good option than imperative programming languages(C, C++, Java).

Here I am writing some points which I observed. comments and suggestions are welcome
1. Erlang being a concurrent language helps in creating multiples processes. The communication model of Erlang is message passing which lets us write concurrent applications without worrying about deadlock, race condition etc.For more see this.

2. On the above property we can make a robotic application where multiple robots are performing a task in co-operative centralized environment. Each robot has its own logic which is controlled by an Erlang server. Some examples are swarm robotics, multiple robots cleaning a room or picking a heavy object.
Let us look at why Erlang will be a good option.
In case of languages which use native threads(C,C++ and Java), there will be a cluttered code having shared memory, loops, process synchronization etc but in Erlang we can use message passing system and other OTP feature to achieve same task in more efficient manner.

3. Erlang's functional nature makes program compact(approx 1/5 times) and readable. This increases productivity also because we can implement a product in less time and push the product before our competitor(less reasonable but true).

4. We can also program "robots with artificial intelligence" using ERESYE which is an additive advantage of Erlang over other languages like C, C++ and Java.

Why process creation time in Erlang is less than Java and C#?

Below are the key points collected by me from stackoverflow, Joe Armstrong's PHD thesis and other web resources.
1. First thing to notice about Erlang is that the word "process" is used because processes do not share data and other resources while threads do share resources and memory(except stack). But still process creation is less expensive in Erlang, how? The answer to this question is that Erlang has the concept of so called "Light weight Process".

2. A newly spawned Erlang process uses 309 words of memory in the non-SMP emulator without HiPE support. Link This includes 233 words for heap and stack memory which can be increased by garbage collector as needed. While in case of Java it varies from 32Kb - 512Kb means at least 100 times more than Erlang.

3. The thread model of Java and C# is OS dependent means that when we create thread in these languages they are mapped onto native threads in someway or the other. But in case of Erlang, processes belong to language not OS, operating system sees only one process which is Erlang Run Time System(ERTS). All process creation, deletion and scheduling is done by ERTS which removes the dependency on underlying OS.

4. The above point is important because it creates a lot of difference between Erlang and other languages. In Java there is certain limit(usually some thousands) on the # threads we can create because of underlying OS but In Erlang we can create millions of threads(I have tested it).

Wednesday, August 4, 2010

How to enable wireless in ubuntu 10.04?

Enabling wireless in windows is quite easy. Here I am suggesting easy way of enabling wireless in ubuntu 10.04(lucid).

Go to system -> administration -> synaptic package manager
then install following packages
bcmwl-kernel-source
b43-fwcutter
bcmwl-modaliases


reboot and everything should work fine. If these packages are already installed then reinstall them.
There may be an exception but this works for me.

Tuesday, June 29, 2010

How to enable USB to SERIAL port(FT232R) in linux....


I am currently developing a robot. This robot has to be controlled using wireless module zigbee. I am using usb to serial converter chip FT232R for this purpose. It is easy to configure this device in windows based platform...you have to just download respective driver from this website..http://www.ftdichip.com/Drivers/VCP.htm but when it comes to Linux it is quite troublesome task. After going through so many website I found one easy way of doing this.


steps

1) First plug the device in usb port and type "dmesg" in terminal...u will see lot of stuff but don't worry..just dump the output in a file.. $ dmesg > out and see the out file..u will find a line like

usb 3-1.3: new full speed USB device using uhci_hcd and address 5

this means device has recognised by system.
2) "unplug" the device and type "lsusb" command... output will look like this

Bus 003 Device 003: ID 413c:8161 Dell Computer Corp.
Bus 003 Device 002: ID 0a5c:4500 Broadcom Corp. BCM2046B1 USB 2.0 Hub (part of BCM2046 Bluetooth)
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 004: ID 0c45:63ee Microdia

then "plug" the device again and type "lsusb" again in terminal and see the output...u will see one additional line is there...

Bus 003 Device 003: ID 413c:8161 Dell Computer Corp.
Bus 003 Device 002: ID 0a5c:4500 Broadcom Corp. BCM2046B1 USB 2.0 Hub (part of BCM2046 Bluetooth)
Bus 003 Device 002: ID 4313:6001 FTDI 232r usb to serial....
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 004: ID 0c45:63ee Microdia

In this line 4313 is vendor id and 6001 is product id. just type following line in terminal

sudo modprobe usbserial vendor=0x4313 product=0x6001

type "dmesg" again and u will see something like this in last line of output..

usbserial_generic 3-1:3.0: generic converter detected
usb 3-1: generic converter now attached to ttyUSB0
usbcore: registered new interface driver usbserial

3) type this on terminal:- sudo gedit /etc/modules and add line "usbserial vendor=0x4313 product=0x6001" without quotes.
this will enable linux to automatically detect device...

4) Verification:
type "cd /dev" in terminal and check output...u will find ttyUSB0 there..means u r done...

cheers........

Saturday, March 13, 2010

How to restore Grub in Ubuntu

Boot up your live CD
In the desktop, open terminal (Applications -> Accessories -> Terminal).

sudo grub

This will set it to grub mode

find /boot/grub/stage1

This will locate your boot partition. If you already know the location, you can ignore this step.

root (hd0,0)

Replace the (hd0,0) by your boot partition number. If your Ubuntu is installed in the second partition, then change it to (hd0,1)

setup (hd0)
quit

Reboot your system. You should be able to access the Grub bootloader now.