Tuesday, December 3, 2013

Does science exist, if God doesn't?

Scientists have always been believed to have a distinct attribute - reasoning. 

A couple of days ago, I was exploring the ways to prove something scientifically. Proof by induction, by contradiction, direct proofs. For the sake of curiosity, I started digging in deep to find out if there's something that has been accepted but not yet proven. My findings turned out to be shocking. Let me introduce a few examples first:

When studying system of Numbers, we have established that numbers exists, like Natural numbers. Then we further devise certain rules to make them usable. Like Rule A: 1 is a Natural number. Rule B: adding 1 to a Natural number gives us a Natural number. But is there a mathematical proof that  N + 1 = N? A common mind would call this a senseless question, claiming that it is obvious. But mathematics doesn't function on how correct something feels. It demands complete proof to declare something "obvious".

The answer is that there is no proof because we assume these rules to be true. This is not the only assumption we make. In primary arithmetic, x + (y - z) = (x + y) - z is also assumed to be true, same applies to trigonometry, algebra, calculus and other branches of mathematics. Such assumptions are called axioms and all mathematics is built upon these axioms. This leads us to another question: "why do we accept them to be true if there is no absolute proof?". Simply, because there is no proof that these axioms are false. Because they appeared to be true for every known number that could be applied on them.

Another, somehow complicated example is from complexity theory. Theorists believe that all the P-type problems (problems that can be solved in polynomial time) are a subset of NP-type problems, meaning that a polynomial time solution exists for non-deterministic machines, if it exists for deterministic machines. But there is no absolute proof that this postulate will be true for each and every problem.

The deeper we go, the more we learn that these axioms have no basis other than that they are self-proving and that all science exists on these assumptions.

Let us now devise an axiom that for every ongoing event E, there exists an initiator. This axiom is evidently true for any event that occurs in real life. Now we can further define another rule that if E occurred because of another event D, then there exists an initiator for D as well. Modifying the same a little further, if an object A exists, it exists as a result of an event E, caused by an initiator. This can be proven wrong iff an object is ever observed that was not caused by any event, or an event occurs by itself without any external influence.

Now if the Universe exists, there must have been a mega event that caused it, initiated by an initiator. This is our axiom. If Mathematics - the mother of all Sciences - is built upon axioms that are believed to be true unless proven wrong, then is there any reason to deny the above axiom, especially when we have observed billions of events following the same rules? This isn't a new question. Just another way of asking it. Why is the fashion of accepting axioms not same when it comes to proving existence of God, the Grand designer of the Universe, or even Multiverse?"


Friday, September 13, 2013

5 things to do when you cannot trace a bug

Programming today, is more about fixing existing code than writing new. In most of the cases, bugs are easy to trace, especially when you are using a modern IDEs like Eclipse or Visual Studio. However, it is very likely that you get trapped in situations like a specific button not doing anything, application crashing randomly, or a record not updating for a specific ID. Here are some tips you may find lifesavers if you get jammed too often when debugging your code:

Catching random errors

Remember, there are no random errors unless you are calling a random function. The code is always consistent, if a function calculates compound interest of an amount over a certain period of time -- within an allowed range -- correctly, it will never do it wrong as long as the parameter values are in range. So, the code is consistent. Data, however, may not be. Here is an example:

public boolean saveRecordInDB (int id, String name, float height, float weight) {
// Do something

saveRecordInDB (1, "Owais", 5.6, 52);
saveRecordInDB (1, "Ahmed", 6.2, 78);

If the first method worked fine and the other didn't, it is very clear that this is something to do with the data in arguments. When you'll dig in deep, you might find that the id that goes into database is Primary key-indexed and is therefore throwing back duplication error. Same is true with NULL, values out of range, etc.

Reading stack trace

Stack trace that -- lines and lines of activities that the runtime environment (JRE, CLR, etc.) is generating -- mainly comprises of methods being called from your code and the libraries you're using, writes all activities on console. Whenever there is an uncaught exception, the whole trace is displayed and programmers are often reluctant to read it. However, stack traces -- scary as they look -- are only to help identify the main source of problem. Always start looking from bottom, your eyes should be scanning the words like "Exception", "Error", "Failed". Once you spot an Exception, now you'll read from top to bottom, look for the classes and methods "you" have written, not for the libraries and APIs you're using.
The better your exception handling in your code, the easier the stack traces are to read. Target NullPointerException, IndexOutOfBoundException, IllegalArgumentException and ClassCastException - the most frequently thrown exceptions, and often uncaught.

There are smart ways to avoid these exceptions without the trouble of writing try/catch block (Java):
- To handle NullPointerException
public int getInteger(Object obj) {
 if (obj == null)
 Integer i = Integer.parseInt (obj);
 return i.intValue ();

public boolean isStringEmpty(String str) {
 return ("".equals(str)); // Avoid writing str.equals("")

- To handle ClassCastException
public MyClass objToMyClass (Object obj) {
 if (obj instanceof MyClass)
  return (MyClass) obj;
 return null;

In cases when you find yourself completely out of luck, search the web for the exception you doubt, is causing the issues. But copy-paste the exception is not always a good idea; if you see an exception like:

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.ArrayList at MyClass.main(MyClass.java:34)

Remove "MyClass" part from the search query. Search only for Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.ArrayList at. Because there are strong chances that someone has already encountered similar problem and posted on some developers' forum, but their class and method names will be different. Thus, the search engine may not return any results.

Pinpoint the location

Identify the origination of the bug. Start with which tier it occurs in, the Client (Java/VB script, applet), Presentation (Servlet, JSP, ASP, JavaBean), Controller (Server, Implementation classes, Factories), Data (SQL Engine, Cloud, No-SQL Database). Next is the module or package, is the error generating from client code, a utility, server-side implementation classes, or another libarary? Once you figure this out, then looking for the specific method and line is just a matter of time.

Explain the code to someone else

This is very handy. Explaining your code to some other programmer requires you to go into details and specific, which you probably would've skipped assuming "Oh! That works, I know. Let's move forward". It is then when you find that the bug was actually in the part you overlooked. This has worked for me countless times.

Take a break

Here, you're going to play with your brain's short-term memory. Think of it as cache that gets cleared whenever not in use for long time. When you are writing code, you have a lot in your short-term memory, which tells you "Hey! This part's okay", "Oh! That line's fine. I remember". You cannot debug with so many assumptions about your code's correctness. So in order to clear your short-term memory. Take a break. Read an article in your to-read list. Check your emails, play a game. Don't even throw a glance at your code unless you forget completely about what you were debugging, how is the method call hierarchy, etc.

In the end, bug tracing and fixing is a skill that furnishes with experience and there are no rules of thumb for dealing with bugs. Whenever you feel hopeless, ask for help, there are thousands of professionals on on line forums like StackOverFlow and XDA-Developers.

Please feel free to leave your comments, pointing mistakes and enhancements.

Happy fixing.

Tuesday, February 12, 2013

4-step configuration of SSL encryption on Tomcat in Ubuntu Linux using Self-Signed Certificate

First things first, the title makes it clear that the user is expected to know about terms SSL, Tomcat and Linux, so getting straight to the topic. The simple steps below can save hours of your time if you followed them sequentially.

So, you have a web application ready to deploy and you want your communication to be entrypted and make sure that you are talking to the right server. Configuring SSL on your web server and application will do both the jobs for you in 4 steps below:

  1. Creating dummy certificate
    - Run: cd /usr/lib/jvm/java-6-openjdk-i386/jre/bin/
    - Run: keytool -genkeypair -alias MyCertificate -keyalg RSA -keystore "/home/myhome/MyCertificate.cert"
    Here, we used Java's keytool application to generate a self-signed certificate.
    Enter all the information asked further: password, name, organization, etc.
    This will generate a SSL certificate file, containing encrypted text.

  2. Enabling SSL on your tomcat server
    - Run: nano /var/lib/tomcat6/conf/server.xml
    - Search for commented block for configuring SSL HTTP connector (by default, it's on port 8443)
    - Uncomment the block and you should see:
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
                   maxThreads="150" scheme="https" secure="true"
                   clientAuth="false" sslProtocol="TLS" />
    - Set protocol="org.apache.coyote.http11.Http11NioProtocol":
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" SSLEnabled="true"
                   maxThreads="150" scheme="https" secure="true"
                   clientAuth="false" sslProtocol="TLS" />
    - Next, provide the password and file path of the Certificate you created:
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" SSLEnabled="true"
                   maxThreads="150" scheme="https" secure="true"
                   clientAuth="false" sslProtocol="TLS" 
                   keystorePass="mysslcertificatepassword" />
    - Save the file and exit the editor
    - Run: service tomcat6 restart

  3. Test if it works
    - Open your browser and try: https://localhost:8443
    - The browser should warn you that the website is untrusted source. Ignore and proceed, you may add the website as an exception.

  4. Next step is to configure your web application to talk only to HTTPS enabled tomcat server
    - Open your web app's web.xml in any editor
    - Add the following lines at the bottom of your web.xml, just before </web-app> tag closure

    <!-- This block makes sure that all the resources are accessed via HTTPS -->
    <!-- This block overrides the previous for certain resources and enables them on both HTTP and HTTPS -->

Now your application and web server are both ready to talk on a secure channel.