The use of grouping in Regular expressions

October 9, 2012 Leave a comment

I was recently asked to parse some responses coming from the CLI of a new device that were working with, instead of writing my own parser i decided to go for a different approach and use Regular expressions to my advantage.

From looking at the output, i noticed that the information is arranged like this:
Hardware revision             2.1             Board revision      M0
Serial number         4279256517            Part number        73-1539-03

As you can see, the general structure of this output is clear… but i am looking for specific data out of this mess.

This is where Regular expression grouping will help me get the information i am looking for.
In order for us to use grouping, we need to enter “()” into our expressions.
For Example:

RegExp = (Hardware revision)\\s+([0-9]+\\.[0-9]+)

This Regular expression will search for patterns that start with the words “Hardware revision” and then some spaces (but at least one), then a number with a dot for example 1.0, 4.3 etc…

If there is a match for this sort of pattern (for example “Hardware revision 2.1″) we will get a matcher that has 3 groups containing our information.
matcher.group(0) = Hardware revision 2.1
matcher.group(1) = Hardware revision
matcher.group(2) = 2.1

Consider the following:

        Pattern hwVerPattern = Pattern
				.compile("("+HW_VER_PARAMETER+")\\s+([0-9]+\\.[0-9]+)");
		Pattern serialNumberPattern = Pattern
				.compile("("+SERIAL_PARAMETER+")\\s+([0-9a-zA-Z]+)");

		List<Pattern> patterns = new LinkedList<Pattern>();
		patterns.add(hwVerPattern);
		patterns.add(serialNumberPattern);

		BufferedReader reader = new BufferedReader(new StringReader(response));
		String currentLine = null;
		Iterator<Pattern> iterator = patterns.iterator();
		try {
			while ((currentLine = reader.readLine()) != null) {
				while (iterator.hasNext()) {
					Pattern pattern = iterator.next();
					Matcher matcher = pattern.matcher(currentLine);

					if (matcher.find()) {
						assignValueToItem(matcher.group(1), matcher.group(2), item);
						iterator.remove();
					}
				}
				if (patterns.size() > 0)
					iterator = patterns.iterator();
				else
					break;
			}
		} catch (IOException e) {
			LOGGER.error("an error has occured while parsing the responce", e);
			return null;
		}

“You Succeed or You Explain”

December 15, 2011 Leave a comment

I would like to share a phrase that has helped me all my life in almost everything I do. If you fully understand that phrase and keep it in your head whenever you work, study or engage in a difficult activity, you will most likely do a sufficient job, almost never fail and possibly be the best. So what is this mysterious phrase? “You Succeed or You Explain”. Yes, it is that simple, try and think back on all the times you either succeeded at something or failed at something, it really doesn’t matter what that “something” was, if you succeeded you probably didn’t have to say anything about what you did, whether it’s a good grade or a good job, the end result spoke for itself and the only feedback you got was a good one. But if you fail at something, most likely the result was, you ended up explaining yourself and why you have failed.

Let us give an example so we will understand how the phrase works.
You are given a task and asked to assess how much time it will take to perform it and execute.
There can be 3 possible outcomes:
1: You will assess the time it takes to complete the task and execute the job within that time limit.

2: You will assess the time it takes to complete the task but eventually unable to complete the task in time

3: Your time assessment does not fit your boss’s expectations and he/she gives you a different time evaluation to complete the task (this can also come in the form of not even asking you for a time assessment and just telling you what to do and how long you have to do it) and like option 2, you are unable to complete the task.

Now let’s review these 3 possible outcomes.

1: this is the best possible outcome you could want, there’s nothing to say but “good job” or nothing. You did what you were given in the time you said you would.

2: In this outcome the explanations begin, it actually doesn’t matter why the task was not completed, it only matters that it wasn’t, it might be that you really didn’t have enough time and you assessed the task wrongly (in that case the blame falls on you), it could be even a very good excuse (sick, domestic problems, someone else was not cooperating with you or whatever), but at the end, WHO GIVES A FUCK, your employer told you to do something and you did not perform. The end result is the same no matter how many good or bad excuses you give.

3: This is the same outcome at the second one; only now the excuse is really good, your boss (or someone else) did not give you enough time, and the excuses can last forever, just look at all the explanations to what went wrong in outcome number 2 and add all the explanations from outcome 3 plus blame yourself for not standing up to your boss in the first place when you knew you won’t have enough time, add them all up and what you get? A big cake of WHO GIVES A FUCK

Indeed these are harsh words I am throwing here, but don’t fool yourselves, they apply everyone everywhere. In variations of the example I have been in countless situations where I needed to explain my failures, and I do sympathize with myself like I do with you, and no one is perfect so everyone needs to explain themselves in some point.

What I want to communicate here is that life is not forgiving and no one cares about excuses, life only cares about results, always remember that wherever you go, if you do, you will understand that explaining is worth exactly nothing, results are worth money.

Now, whenever you do something, think about how to not explain anything at the end.
And remember, this phrase is true for everything (99.9%), every time.
Good Luck.

Another awesome appsumo raffle. Spotify Premium for life

December 1, 2011 Leave a comment

http://appsumo.com/~s-rN

Contest ends at December 16th, 11:59PM CST.

Better sign in while you still can.

Good luck.

Categories: Uncategorized

Getting started: Sqlite on Android

October 12, 2011 Leave a comment

I am writing this tutorial with some hesitation, i really don’t want to make another copy of this android SQLite tutorial That is wondering around the net. So this tutorial is a part or a series, after this “getting started” one, a more interesting one on how to implement some design patterns to work with your application and SQLite database.

Building a Database on an android system is not a very pleasant job but from some point of view it has its advantages. If you have worked with a database element manager like phpmyadmin visual studio or any other, you know its the easiest way to build a database, easy to modify and see the big picture, your able to insert data and edit the database content easily and the most important… it saves TIME. With sqlite on android you do not really have any way of visualizing your database, you will need to create it when your application runs for the first time. Thous who love the scripting business will disagree with me. I personally like getting things done (when i am not trying to study how things work and gain experience). However the idea of having all of your code (as well as the databases) in the same place is a good practice and simplifys things when developing.

Note: There are some ways of visualizing and edit your database with an external editor and inject it into your application but its not what this tutorial will be about. here we will see how to create a database for the android system use the method “GOD” intended. Then we will see how we can go about simplifying the solution so we will have a good and robust code what will be easy to manage and enlarge.

Lets create our Chocolate Database.
What were going to do is build a wrapper class that will extend SQLiteOpenHelper (A helper class for managing database creation and version management.). It will hold all the code necessary to create, delete, update and maintain the Database.

public class ChocolateDbHelper extends SQLiteOpenHelper {

public static final int dbVersion = 1; //dbVersion is used by SQLiteOpenHelper to know if an upgrade/downgrade is needed for the existing db

public static final string CHOCOLATE_TABLE_NAME = “chocolate_table”; public static final string CHOCOLATE_ID_COL = “chocolate_id”; public static final string CHOCOLATE_TYPE_COL = “chocolate_type”; public static final string CHOCOLATE_QUANTITY_COL = “chocolate_quantity”;

public static String dbCreateString = “CREATE TABLE ” + CHOCOLATE_TABLE_NAME  + ” ( ” + CHOCOLATE_ID_COL  + ” INTEGER PRIMARY KEY AUTOINCREMENT, ” + CHOCOLATE_TYPE_COL + ” INTEGER NOT NULL, ” + CHOCOLATE_QUANTITY_COL + ” REAL)” ;

public ChocolateDbHelper (Context context) {

super(context, dbName , null, dbVersion);

 }

@override
public void onCreate(SQLiteDatabase db) {

try{

db.execSQL(dbCreateString);

} catch (SQLException e) {

//throw some logs here.

}

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

try {

db.execSQL(“DROP TABLE IF EXISTS ” + CHOCOLATE_TABLE_NAME ); onCreate(db);

} catch (SQLException e) {

//produce some logs here

}

}

public long EnterNewChocolate(Chocolate chocolate) {

SQLiteDatabase db = null; long rowId = -1; try {

db = this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(CHOCOLATE_TYPE_COL , chocolate.getChocolateType()); cv.put(CHOCOLATE_QUANTITY_COL , chocolate.getQuantity()); rowId = db.insert(CHOCOLATE_TABLE_NAME , null, cv);

} finally {
return rowId;
}

}

About onCreate(SQLiteDatabase db):

This function will be called when the database is created for the first time.
The creation of tables/triggers and population of the database should happen here.

Variables:
db – The database.

About onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion):

This function is called when the version of the database has changed to grater than the previous version (there’s also the onDowngrade).
When this function if called, oldVersion < newVersion.

There is no right or wrong way to manage this function, if you have a static database and need to upgrade it, just delete the old one and create the new one instead.
If you want to add to an existing database with out deleting it just post your SQL Statement there and hope you know what your doing.

Variables:
db – the database.
oldVersion – the old version of the database.
newVersion – the new version of the database.

The basics is right here, in fact you don’t need any more to effectively manage a small database.

Thanks for reading, i am working on the next chapter in the SQLite database tutorial.

Categories: Android, Java Tags: , , , ,

Love DropBox

October 6, 2011 Leave a comment

Hi guys… i love this awesome product. please help me with this contest, i’ll be forever grateful
besides you might win too… :)

pro drop box for life. sign in with this link

http://appsumo.com/~Vh0n

Categories: Uncategorized

Creating a successful Enum with Java

Enum is basically a dictionary to work with, that gives the programmer a better representation of data through out the application, while maintaining the consistency of the data through different modules.

So what is a successful Enum… the best way to explain is to give a little demonstration on how to upgrade your basic Enum to something more useful.
Application <—> Database is a powerful and common situation to work with.

First of all, an Enum is a class like any other, thus having contructors, members and functions like any other class, and we can use them to our advantage.

Lets begin with a simple week days Enum

enum weekDays
{
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;
}

The first problem with this Enum is that its inconsistent with the week days (ha ha why?), because Sunday is not day 0, but day 1. (with out the philosophical debate, Sunday is the First day of the week, and if you want it to be Monday thats OK too, same rule still applies).
So we want to change the Enum elements values?. In order to do that we need to have a constructor, because when the class loader first loads the Enum it creates an instance for each of the Enums elements, in the code example above the default constructor is called for each of the element and consecutive numbers are given to each element starting with 0.
If we want different values than we will create another constructor.

Now, our Enum should look like this:

enum weekDays
{
Sunday(1) , Monday(2), Tuesday(3), Wednesday(4), Thursday(5), Friday(6), Saturday(7);
private weekDays (int value) { }
}

OK!, this looks more like it… but that too doesn’t help us so much. We have ourselves a small dictionary of the weekdays and we set they’r values to what ever we want them to be but the only problem is that we don’t really have any way of getting that value. if we talked about a calendar database and we have a new calendar entry with weekDays member, we need to have some way of getting that value that corresponds to that Enum element (we might want to insert a new record to the database).
Here is where we make this Enum allot more helpful… if we take into consideration the fact that the class loader instantiates each of the Enum values when the class is read for the first time, we can do the following, and expect to have 7 different immutable’s in the JVM immutable pull, each with a different value according to the values we gave the Enum elements.

enum weekDays
{
Sunday(1) , Monday(2), Tuesday(3), Wednesday(4), Thursday(5), Friday(6), Saturday(7);
private int value;
private weekDays (int value)
{
this.value = value;
}
public int toInt()
{
return this.value;
}
}

So now we can translate from the Enum element to its numeric representation (if you were following this far you probably understand that it could be any representation you want it to be).
if we wanted to insert a new record into the database, getting the numerical representation would be as simple as someWeekDay.toInt();

but what about the other way around… what if we wanted to create an application entities from the data stored in the database… well no problem there.

enum weekDays
{
Sunday(1) , Monday(2), Tuesday(3), Wednesday(4), Thursday(5), Friday(6), Saturday(7);
private int value;

private weekDays (int value)
{
this.value = value;
}

public int toInt()
{
return this.value;
}
public static weekDays fromInt(int value)
{
weekDays retVal = null;
switch (value)
{
case 1: retVal = weekDays.Sunday; break;
case 2: retVal = weekDays.Monday; break;
case 3: retVal = weekDays.Tuesday; break;
case 4: retVal = weekDays.Wednesday; break;
case 5: retVal = weekDays.Thursday; break;
case 6: retVal = weekDays.Friday; break;
case 7: retVal = weekDays.Saturday; break;
}
return retVal;
}
}

By now i think you got the point of making Enums work for you. the point is making the code more understandable and consistent traversing databases application network or any other module or medium that you desire.

if you found this helpful in any way or have something to say about what you have just read. please leave a comment.
Happy coding.

Categories: Java Tags: , , ,

The Motivation

March 5, 2011 1 comment

“If i had a good idea i would be a millionaire”.
I have chosen to start this article with that statement because almost everyone can relate to it.
who doesn’t want to make money… and who doesn’t want a good idea. I will address the issue from a programmers point of view because i am one and i believe that the same principle applies to all elements of life and work.
Today every programmer has a few ideas running around his head, some of them are small and easy to make (lets say if you give them a few hours a day you can make something nice in about a month) but are not worth big money, and some are complex ideas and concepts, that require a massive amount of resources, but can really be something that can make you thous millions that you so desire.
But why aren’t you doing anything?. Is it because when you say “If i had a good idea i would be a millionaire” what you actually want to say is “If i had a good idea i would be a millionaire but i don’t have any good ideas” or “If i had a good idea i would be a millionaire but i don’t have time to invest in it”.
Well if you ask me theres no excuse to not doing anything.
As a programmer you have the ability to do almost anything with a computer, being a programmer gives you the ability to start doing something with little to no effort.
When I think about it, the world has 2 kinds of people, those that DO and those that DON’T (DO).
the “DOers” don’t try to find a solution that would magically make them rich, or would give them the idea that they so want to find. Categorically all the wealthiest people in the world are actually “DOers” (and if they inherited it then they’r father was a “DOer”), they worked hard for what they have, not by sitting in the office and letting the world turn waiting and wishing that the BIG MONEY would magically fall in they’r lap.
Instead when they came home from work they started working. small or big it doesn’t matter. find something that you think can be of use to someone, and DO IT!. Do you have a good idea for some Iphone application?, its so easy not to do anything about it, the excuses will never end, here is just some that hear all the time about making iphone applications (From people that have good ideas): “i don’t have mac”, “i don’t know objective c” , “it wont make money” and the one that i really love is “its already been done”… this one is the kicker, if its been done and people are using it it means that there is a market for it.
So… who would you be?.
Would you sit on your chair and think about how you could have done many things, or would you actually do them. I know what i am doing!.
Cya a the finish line.

Categories: Just an opinion
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: