Monthly Archives: May 2012

Perl grep and assign variable from line

While performing read line from file or parsing a line, it is possible to just grab certain string / number pattern and assign to a variable.

open(FILE, "+<$file") or die "Cannot open file";
while(<FILE>){
  my $readline = $_;
  // for example the string is "I am a boy with lots of passion"
  if(/(.*)am(.*)of(.*)/){
    $string1 = $1; // string 1 will have "i"
    $string2 = $2; // string 2 will have "a boy with lots"
    $string3 = $3; // string 3 will have "passion"
  }
}
Advertisements

simple custom hashmap module for perl

HashMap.pm


<perl path>

package HashMap;

use Data::Dumper;
#use strict;
#use warnings;

## Constructor
sub new {
 my $class=shift;
 my $self = {};
 my %hash;
 $self->{HASH} = \%hash;
 bless $self, $class;
 return $self;
}
sub put {
 my($self,$key,$val) = @_;
 $hash = $self->{HASH};
 $hash->{$key} = $val;
}

sub get {
 my($self,$key) = @_;
 my %hash = %{$self->{HASH}};
 return $hash{$key};
}

sub printHash {

my ($self) = @_;
 print Dumper($self->{HASH});
}

1;

Usage:


// Initialize object

my $hashmapObj = new HashMap();

// Insert value to hashmap

$hashmapObj->put(<KEY>,<VALUE>);

// Retrieving value from hashmap

print "Value for $key = ".$hashmapObj->get(<KEY>)."\n";

using perl global variable from main pl file to module files

fileA.pl


our $var = 123;

to use $var from main pl file, simple just use the $main variable

fileB.pm


print $main::var;

Android SMS Receiver

public class SmsReceiver extends BroadcastReceiver {

	private static final String TAG = "AutosendService";
	private static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED";
	private StringBuilder strBuild = new StringBuilder();
	private StringBuilder incomingString = new StringBuilder();

    @Override
    public void onReceive(Context context, Intent intent) {

            //---get the SMS message passed in---
	    if(intent.getAction().equals(SMS_ACTION)){
	    	Bundle bundle = intent.getExtras();

	    	if (bundle != null)
	        {
	            //---retrieve the SMS message received---
	            Object[] pdus = (Object[]) bundle.get("pdus");
	            SmsMessage[] msgs = new SmsMessage[pdus.length];
	            for (int i=0; i<msgs.length; i++){
	                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
	                strBuild.append(msgs[i].getOriginatingAddress());
	                strBuild.append(" : ");
	                strBuild.append(msgs[i].getMessageBody().toString());
	            }

	            Log.i(TAG, "smsReceive: "+strBuild);
	        }
	    }
    }
}

AndroidManifest.xml

 <uses-permission android:name="android.permission.RECEIVE_SMS"/>

<receiver android:name=".SmsReceiver">    
     
            <intent-filter>
            	<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>          
        </receiver>

Android Camera Intent

private void startCameraIntent() {
		Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		file = new File(<folder>,<filename>);
		cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		startActivityForResult(cameraIntent, <CAMERA_REQUEST_CODE>);
	}

Android Facebook SDK post photo

public void postPhotoToFB(){
                Bundle params = new Bundle();
		params.putString("message", <your message>);
		params.putByteArray("picture", <picture byte array>); // check my other blog on how to convert image to byte array
		params.putString("caption", <your caption>);
		fbSyncRunner.request("me/photos", params, "POST",null);
}

Android getting address from Geocoder

private String getAddress(double currentLatitude, double currentLongitude){
        try{
            Geocoder gcd = new Geocoder(context, Locale.getDefault());
            List<Address> addresses = gcd.getFromLocation(currentLatitude, currentLongitude,100);
            StringBuilder result = new StringBuilder();
            if (addresses.size() > 0) {
                    Address address =  addresses.get(0);
                    int maxIndex = address.getMaxAddressLineIndex();
                    for (int x = 0; x <= maxIndex; x++ ){
                        result.append(address.getAddressLine(x));
                        result.append(",");
                    }
                    result.deleteCharAt(result.length()-1);
            }
            return result.toString();
        }
        catch(IOException ex){
           ex.printStackTrace();
           return null;
        }
    }

Android convert image uri to byte array

public byte[] convertImageToByte(Uri uri){
		byte[] data = null;
		try {
		    ContentResolver cr = getBaseContext().getContentResolver();
		    InputStream inputStream = cr.openInputStream(uri);
		    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
		    ByteArrayOutputStream baos = new ByteArrayOutputStream();
		    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		    data = baos.toByteArray();
		} catch (FileNotFoundException e) {
		    e.printStackTrace();
		}
		return data;
	}

Android getting photo orientation

public int getPhotoOrientation(File imageFile){
		ExifInterface exif;
		int degree = 0;
		int rotation = 0; //we will start with 0
		try {
			exifData = new ExifInterface(imageFile.getAbsolutePath());
			degree = exifData.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
		} catch (IOException e) {
			e.printStackTrace();
		}

	   switch(degree) {
	     case ExifInterface.ORIENTATION_ROTATE_270:
	         rotation+=90;
	     case ExifInterface.ORIENTATION_ROTATE_180:
	         rotation+=90;
	     case ExifInterface.ORIENTATION_ROTATE_90:
	         rotation+=90;
	   }

	   return rotate;
	}

Android rotate Bitmap

public Bitmap rotate(Bitmap inBitmap, int inDegrees) {
	    if (inDegrees != 0 && inBitmap != null) {
	        Matrix matrix = new Matrix();
	        matrix.setRotate(inDegrees, (float) inBitmap.getWidth() / 2, (float) inBitmap.getHeight() / 2);
	        try {
	            Bitmap tempBitmap = Bitmap.createBitmap(inBitmap, 0, 0, inBitmap.getWidth(), inBitmap.getHeight(), matrix, true);
	            if (inBitmap != tempBitmap) {
	                inBitmap.recycle();
	                inBitmap = tempBitmap;
	            }
	        } catch (OutOfMemoryError ex) {
	           throw ex;
	        }
	    }
	    return inBitmap;
	}