Sunday, August 21, 2011

How do reset the administrator password in Mac OS X without installation disk?

Let's say you forgot your password on the Mac. Or have just purchased a Macintosh from hands, and the former owner has locked the computer. There are several elegant solutions to this problem without the installation DVD-ROM with Mac OS X. 
Perhaps this topic has been bored, but it affects the important question that people ask constantly. I do not want to think that any user, once next to your computer can theoretically obtain access to it for several minutes. And before you decide that the Mac OS X has a serious vulnerability, I hasten to you "good news": any operating system, whether Windows, Linux or Mac can be hacked for a couple of minutes, if you know what to do. A hacker sitting at your computer, can circumvent any security measures.

Reset the password in Mac OS X 10.6 Snow Leopard
  1. Turn on or restart your Mac.
  2. At the time greeting (or gray screen), hold down the keyboard Command + S to boot into single user mode. 
  3. Step is optional, but it is useful to go through, because this way you check for errors on your hard drive. In the prompt, type fsck-fy and press Enter. Wait until the end of the disk check.
  4. Write mount-uw / and press Enter.
  5. Next launchctl load /System/Library/LaunchDaemons/com.apple.DirectoryServices.plist and press Enter.
  6. Type ls /Users and press Enter. The command will list all users on a computer - useful if you do not know or do not remember.
  7. In line dscl . -passwd /Users/username password Replace "username" with your user name (see above), and instead of "password" enter the code combination of characters and press Enter.
  8. To reboot execute the command reboot.
Reset Password on Mac OS X 10.4 Tiger
  1. Turn on or restart your Mac.
  2. At the time greeting (or gray screen when you turned it off), hold down the keyboard Command + S to boot into single user mode.
  3. Write to the line sh /etc/rc and press Enter.
  4. Type passwd username and replace "username" for a short user name of the account, which are going to reset your password.
  5. Enter the desired password and press Enter.
  6. To reboot execute the command reboot.
Cheating and creating a new Mac user
  1. Turn on or restart your Mac.
  2. At the time greeting (or gray screen when you turned it off), hold down the keyboard Command + S to boot into single user mode.
  3. Step is optional, but it is useful to go through, because this way you check for errors on your hard drive. In the prompt, type fsck-fy and press Enter. Waituntil the end of the disk check.
  4. Write mount-uw / and press Enter.
  5. Then rm /var/db/.AppleSetupDone and press Enter.
  6. Now shutdown-h now and press Enter.
The third method requires some explanation.
Instead replace the password in the first two methods, it is in its own way, cheating of the operating system. The trick makes the system think that it still did not run. This means that when you restart the Mac, you have to re-take all the steps in setting and registration. Do not worry, all information on mac in safe and sound. Walk through the steps, but in the end give up the migration of data on your Mac.

Then log on Mac under a new administrator account and go to Settings Panel -> User Accounts. Perhaps, before making any changes need to unlock the padlock in the bottom left corner. In the left column you should see the original(s) account. Click on the desired unchecked and turn it into a standard account (uncheck the "Enable. This user to administer computer") and change your password. Now you can go to the computer under that account and get access to all your files and programs. You can go back under the Administrator account and check checkbox "Allow. this user to administer computer "in System Preferences to give administrative rights to the user.

As always, remember that a combination of single-user mode (single-user mode or superuser) and the terminal is extremely dangerous and can lead to big problems in the event of your mistakes.

If you have a password in the Keychain (Keychain Access), is likely to be reset as well. Do this by choosing the "input" under a bunch of keys on the left and click Delete from the Edit menu. You will lose all the keys and add them again.

Arrays vs ArrayLists vs Vectors vs LinkedLists

The question is which one to use and when? Which one is more efficient? Lets look into each one of them.

An array is basically a fixed size collection of elements. The bad point about an array is that it is not resizable. But its constant size provides efficiency. So arrays are better to use when you know the number of elements available with you.

ArrayList is another collection where the number of elements is resizable. So if you are not sure about the number of elements in the collection use an ArrayList. But there are certain facts to be considered while using ArrayLists.

=> ArrayLists is not synchronized. So if there are multiple threads accessing and modifying the list, then synchronization might be required to be handled externally.
=> ArrayList is internally implemented as an array. So whenever a new element is added an array of n+1 elements is created and then all the n elements are copied from the old array to the new array and then the new element is inserted in the new array.
=> Adding n elements requires O(n) time.
=> The isEmpty, size, iterator, set, get and listIterator operations require the same amount of time, independently of element you access.
=> Only Objects can be added to an ArrayList
=> Permits null elements

If you need to add a large number of elements to an ArrayList, you can use the ensureCapacity(int minCapacity) operation to ensure that the ArrayList has that required capacity. This will ensure that the Array is copied only once when all the elements are added and increase the performance of addition of elements to an ArrayList. Also inserting an element in the middle of say 1000 elements would require you to move 500 elements up or down and then add the element in the middle.

The benefit of using ArrayList is that accessing random elements is cheap and is not affected by the number of elemets in the ArrayList. But addition of elements to the head of tail or in the middle is costly.

Vector is similar to ArrayList with the difference that it is synchronized. It offers some other benefits like it has an initial capacity and an incremental capacity. So if your vector has a capacity of 10 and incremental capacity of 10, then when you are adding the 11th element a new Vector would be created with 20 elements and the 11 elements would be copied to the new Vector. So addition of 12th to 20th elements would not require creation of new vector.

By default, when a vector needs to grow the size of its internal data structure to hold more elements, the size of internal data structure is doubled, whereas for ArrayList the size is increased by only 50%. So ArrayList is more conservative in terms of space.

LinkedList is much more flexible and lets you insert, add and remove elements from both sides of your collection - it can be used as queue and even double-ended queue! Internally a LinkedList does not use arrays. LinkedList is a sequence of nodes, which are double linked. Each node contains header, where actually objects are stored, and two links or pointers to next or previous node. A LinkedList looks like a chain, consisting of people who hold each other's hand. You can insert people or node into that chain or remove. Linked lists permit node insert/remove operation at any point in the list in constant time.

So inserting elements in linked list (whether at head or at tail or in the middle) is not expensive. Also when you retrieve elements from the head it is cheap. But when you want to randomly access the elements of the linked list or access the elements at the tail of the list then the operations are heavy. Cause, for accessing the n+1 th element, you will need to parse through the first n elements to reach the n+1th element.

Also linked list is not synchronized. So multiple threads modifying and reading the list would need to be synchronized externally.

So the choice of which class to use for creating lists depends on the requirements. ArrayList or Vector( if you need synchronization ) could be used when you need to add elements at the end of the list and access elements randomly - more access operations than add operations. Whereas a LinkedList should be used when you need to do a lot of add/delete (elements) operations from the head or the middle of the list and your access operations are comparatively less.

Array vs Collection

I do not understand why do we need both array and collection in Java ? I mean, aren't both of them the same - "a group of objects as a single unit" ? Why do we still need array (to exist) when the collection framework is so much better... giving us so many facilities to manipulate "a group of objects" ?

Arrays and Collections are complementary. Each have their own advantages and drawbacks. In some case, it is better to simply use arrays instead of Collections. For instance, say you want to store a sequence of integer primitives. If we only had collections, we would have to wrap each integer primitive in an java.lang.Integer. Imagine you have to store 2 millions (or more) ints. You would create lots of objects for nothing. Arrays further provide type safety. You know that an array declared as

Item[] item = new Item[21];

will only contain objects whose type is Item or a subclass thereof. You don't have that guarantee will Collections (yet, see JSR 14: Add Generic Types To The JavaTM Programming Language).     Collections are generic, that is, everything you get out of them will be an Object that you will have to cast to the correct type. Frankly, choosing between Collections and Arrays is not always a piece of cake, your application may suffer from bad choices. Check out Java tutorial: What are the Benefits of a Collections Framework? to see what advantages the Collections framework provide.

public class ArrayTest {

    static int size = 10000;
    static long temp;
    static long start;
    static long finish;
    
    int[] iArr = new int[size];
    ArrayList iArrayList = new ArrayList();
    LinkedList iLinkedList = new LinkedList();
    
    Integer item =  new Integer(1);

    public static void main(String[] args) {
        ArrayTest class1 = new ArrayTest();

        start = System.currentTimeMillis();
        class1.createArray();
        finish = System.currentTimeMillis();
        temp = finish - start;
        System.out.println("Array:");
        System.out.println("start " + start + " finish " + finish);
        System.out.println("time: " + temp+" milliseconds");

        start = System.currentTimeMillis();
        class1.createArrayList();
        finish = System.currentTimeMillis();
        temp = finish - start;
        System.out.println("ArrayList:");
        System.out.println("start " + start + " finish " + finish);
        System.out.println("time: " + temp+" milliseconds");

        start = System.currentTimeMillis();
        class1.createLinkedList();
        finish = System.currentTimeMillis();
        temp = finish - start;
        System.out.println("LinkedList:");
        System.out.println("start " + start + " finish " + finish);
        System.out.println("time: " + temp+" milliseconds");

    }

    public void createArray() {
        for (int i = 0; i < size; i++) {
            iArr[i] = item;
        }
    }

    public void createArrayList() {
        for (int i = 0; i < size; i++) {
            iArrayList.add(item);
        }
    }

    public void createLinkedList() {
        for (int i = 0; i < size; i++) {
            iLinkedList.add(item);
        }
    }
}

10 000 iterations - Integer

1.1 


1.2


1 000 000 iterations - Integer

1.1


1.2


10 000 iterations - int

1.1


1.2


1 000 000 iterations - int

1.1


1.2


Summary:
Array at least 6 times faster than Collection!

Beware of SQL Injection


SQL injection is one of the simple but very powerful security threat, that is also very common in various sites.


Let us say we have a website, and we want to let only the registered users to login by asking for username and password. Let us say we store the username and password in the database.

To check whether the user is valid or not, we use the following query.


select * from users where username='abcd' and password='xyz'


If the result contains atleast 1 row, we say the user name password matches.

A typical Java code will be,

String username = "abcd"; // or get from the user.
String password = "xyz";  // or get from the user.

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(
                      "select * from users
                      where username='"+username+"'"
                      and password='"+password+"'"
               );
if(rs.next()){
 // user is logged in.
}else{
 // login failed.
}


As we are simply concatenating the string, we don't have a clue what the user will type for the username and password fields.

What happens if the user types ' or ''=' including the quotes?
Then, the SQL query will be

select * from users where username='abcd' and password='' or ''=''

This will succeed irrespective of the username or password the user types. This will clearly be a security threat.

How to fix this?
Should we check for the input string whether it contains any single quote and ignore if any? That will be very difficult to check for each and every field.
A simple technique is, use PreparedStatement.

That is the code will then be,
String username = "abcd"; // or get from the user.
String password = "xyz";  // or get from the user.

PreparedStatement stmt = con.prepareStatement("select * from users
                      where username='?'
                      and password='?'"
               );
stmt.setString(1,username);
stmt.setString(2,password);

ResultSet rs = stmt.executeQuery();

if(rs.next()){
 // user is logged in.
}else{
 // login failed.
}

When the user types the password as before, it wont allow the user to login as the prepared statement takes care of escaping the characters, there by guaranteeing the expected behavior.

Conclusion:
Always try to use PreparedStatement instead of String concatenations in all places.

ArrayList vs Vector

This is one of the famous questions that a Java beginner has in his mind. This is also a famous question asked in interviews. Following are the differences between ArrayList and Vector.

1. Vectors and Hashtable classes are available from the initial JDK 1.0. But, ArrayList and HashMap are added as a part of new Collections API since JDK 1.2.

2. Vectors and Hashtable are synchronized where as ArrayList and HashMap are unsynchronized.

When to use Vector? When to use ArrayList? 
1. ArrayList is faster when compared to Vector since ArrayList is unsynchronized. So, if the List will be modified by only one thread, use ArrayList. If the list is a local variable, you can always use ArrayList.



2. If the List will be accessed by multiple threads, always use Vector, otherwise you should take care of synchronization manually.

To visualize the problem with synchronization, try the following code.
There is a Producer class that adds 5000 elements to the List (ArrayList/Vector). Another class, Consumer class removes 5000 elements from the same list. There are around 10 producer threads and 10 consumer threads.



class Producer implements Runnable {

  private List list;

  public Producer(List pList) {
    list = pList;
  }

  public void run() {
    System.out.println("Producer started");
    for (int i = 0; i < 5000; i++) {
      list.add(Integer.toString(i));
    }
    System.out.println("Producer completed");
  }

}


class Consumer implements Runnable {
  private List list;

  public Consumer(List pList) {
    list = pList;
  }

  public void run() {
    System.out.println("Consumer started");
    for (int i = 0; i < 5000; i++) {
      while (!list.remove(Integer.toString(i))) {
        // Just iterating till an element is removed
      }

    }
    System.out.println("Consumer completed");
  }
}


public class ListTest {

  public static void main(String[] args) throws InterruptedException {
    //   List list = new Vector();
    List list = new ArrayList();

    for (int i = 0; i < 10; i++) {
      Thread p1 = new Thread(new Producer(list));
      p1.start();
    }

    for (int i = 0; i < 10; i++) {
      Thread c1 = new Thread(new Consumer(list));
      c1.start();
    }
    Thread.yield();

    while (Thread.activeCount() > 1) {
      Thread.sleep(100);
    }

    System.out.println(list.size());

  }

}

Try running the program with ArrayList. You can see a number of ArrayIndexOutOfBoundException, Consumer threads will still keep waiting for more elements which wont be added because the Producer has terminated after throwing the Exception.

Now, change the line,
List list = new ArrayList();

to
List list = new Vector();

and run the program.

Now you can see a proper result.

This clearly explains why you should use Vector class when there are multiple threads in the system.

In this program, even if you remove the Consumer class and Consumer thread, you can see that the Producer will themselves throw Exception.
 
This is because, while adding an element to the ArrayList, it checks for the size of the Array. If the array size is not sufficient, a new array will be created, the elements will be copied to the new array. If the context switching if Threads happen at this place also, we will get ArrayIndexOutOfBoundException, or sometimes, you may not get any Exception, but some elements will be missing, and many unexpected behaviors.

So always use Vector if there are multiple threads. The same rule applies to HashMap vs Hashtable, StringBuilder vs StringBuffer.

Summary:
1. Use Vector if there are multiple threads and ArrayList if there is only a single thread.
2. Use Hashtable if there are multiple threads and HashMap if there is only a single thread.
3. Use StringBuffer if there are multiple threads and StringBuilder if there is only a single thread.

StringBuilder vs StringBuffer


StringBuilder was introduced in JDK 1.5. What's the difference between StringBuilder and StringBuffer? According to javadoc, StringBuilder is designed as a replacement for StringBuffer in single-threaded usage. Their key differences in simple term:
  • StringBuffer is designed to be thread-safe and all public methods in StringBuffer are synchronized. StringBuilder does not handle thread-safety issue and none of its methods is synchronized.
  • StringBuilder has better performance than StringBuffer under most circumstances.
Criteria to choose among String, StringBuffer and StringBuilder
  1. If your text is not going to change use a string Class because a String object is immutable.
  2. If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
  3. If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.

Introduction

Concatenation of String is very easy in Java - all you need is a '+'. It can't get any easier than that, right? Unfortunately there are a few pitfalls. One thing you should remember from your first Java lessons is a small albeit important detail: String objects are immutable. Once constructed they cannot be changed anymore.
Whenever you "change" the value of a String you create a new object and make that variable reference this new object. Appending a String to another existing one is the same kind of deal: a new String containing the stuff from both is created and the old one is dropped.
You might wonder why String are immutable in first place. There are two very compelling reasons for it:
  1. Immutable basic types makes things easier. If you pass a String to a function you can be sure that its value won't change.
  2. Security. With mutable String one could bypass security checks by changing the value right after the check. (Same thing as the first point, really.)

The performance impact of String.concat()

Each time you append something via '+' (String.concat()) a new String is created, the old stuff is copied, the new stuff is appended, and the old String is thrown away. The bigger the String gets the longer it takes - there is more to copy and more garbage is produced.
Creating a String with a length of 65536 (character by character) already takes about 22 seconds on an AMD64 X2 4200+. The following diagram illustrates the exponentially growing amount of required time:
String.concat() - exponential growth
Figure 1: StringBuilder vs StringBuffer vs String.concat
StringBuilder and StringBuffer are also shown, but at this scale they are right onto the x-axis. As you can see String.concat() is slow. Amazingly slow in fact. It's so bad that the guys over at FindBugs added a detector for String.concat inside loops to their static code analysis tool.

When to use '+'

Using the '+' operator for concatenation isn't bad per se though. It's very readable and it doesn't necessarily affect performance. Let's take a look at the kind of situations where you should use '+'.
a) Multi-line String:
String text=
    "line 1\n"+
    "line 2\n"+
    "line 3";
Since Java doesn't feature a proper multi-line String construct like other languages, this kind of pattern is often used. If you really have to you can embed massive blocks of text this way and there are no downsides at all. The compiler creates a single String out of this mess and no concatenation happens at runtime.
b) Short messages and the like:
System.out.println("x:"+x+" y:"+y);
The compiler transforms this to:
System.out.println((new StringBuilder()).append("x:").append(x).append(" y:").append(y).toString());
Looks pretty silly, doesn't it? Well, it's great that you don't have to write that kind of code yourself. ;)
If you're interested in byte code generation: Accordingly to Arno Unkrig (the amazing dude behind Janino) the optimal strategy is to use String.concat() for 2 or 3 operands, and StringBuilder for 4 or more operands (if available - otherwise StringBuffer). Sun's compiler always uses StringBuilder/StringBuffer though. Well, the difference is pretty negligible.

When to use StringBuilder and StringBuffer

This one is easy to remember: use 'em whenever you assemble a String in a loop. If it's a short piece of example code, a test program, or something completely unimportant you won't necessarily need that though. Just keep in mind that '+' isn't always a good idea.

StringBuilder and StringBuffer compared

StringBuilder is rather new - it was introduced with 1.5. Unlike StringBuffer it isn't synchronized, which makes it a tad faster:
StringBuilder compared with StringBuffer
Figure 2: StringBuilder vs StringBuffer
As you can see the graphs are sort of straight with a few bumps here and there caused by re-allocation. Also StringBuilder is indeed quite a bit faster. Use that one if you can.

Thursday, July 28, 2011

Android onClickListener

Today I want to talk about Android onClickListener. Android has three way to implement onClick Listener.

First way:
You should create Activity class with implementation onClickListener interface. And override onClick method. Create button object and set parameter setOnClickListenr(this);



Result:


Second way:
Create an anonymous event handler class and override onClick method inside it.

Result:

Third way:
Declare a function public void anyName(View v)  and handle a button click.


In the xml file, specify the value of the button onClick.


Enter the function name that you declare.


Result: