Friday, March 7, 2014

Detecting if a string has unique characters: comparing my solution to “Cracking the Coding Interview?”

There are two separate questions here: what's the efficiency of your solution, and what is the reference solution doing? Let's treat each independently.
First, your solution:
public static boolean checkForUnique(String str){
    boolean containsUnique = false;

    for(char c : str.toCharArray()){
        if(str.indexOf(c) == str.lastIndexOf(c)){
            containsUnique = true;
        } else {
            containsUnique = false;
        }
    }

    return containsUnique;
}
Your solution essentially consists of a loop over all characters in the string (let's say there are n of them), checking on each iteration whether the first and last index of the characters are the same. The indexOf and lastIndexOf methods each take time O(n), because they have to scan across all the characters of the string to determine if any of them match the one you're looking for. Therefore, since your loop runs O(n) times and does O(n) work per iteration, its runtime is O(n2).
However, there's something iffy about your code. Try running it on the string aab. Does it work correctly on this input? As a hint, as soon as you determine that there are two or more duplicated characters, you're guaranteed that there are duplicates and you can return that not all characters are unique.
Now, let's look at the reference:
public static boolean isUniqueChars(String str) {
    if (str.length() > 256) { // NOTE: Are you sure this isn't 26?
        return false;
    }
    int checker = 0;
    for (int i = 0; i < str.length(); i++) {
        int val = str.charAt(i) - 'a';
        if ((checker & (1 << val)) > 0) return false;
        checker |= (1 << val);
    }
    return true;
}
This solution is cute. The basic idea is the following: imagine that you have an array of 26 booleans, each one tracking whether a particular character has appeared in the string already. You start with all of them false. You then iterate across the characters of the string, and each time you see a character you look into the array slot for that character. If it's false, this is the first time you've seen the character and you can set the slot to true. If it's true, you've already seen this character and you can immediately report that there's a duplicate.
Notice that this method doesn't allocate an array of booleans. Instead, it opts for a clever trick. Since there are only 26 different characters possible and there are 32 bits in an int, the solution creates an int variable where each bit of the variable corresponds to one of the characters in the string. Instead of reading and writing an array, the solution reads and writes the bits of the number.
For example, look at this line:
if ((checker & (1 << val)) > 0) return false;
What does checker & (1 << val) do? Well, 1 << val creates an int value that has all bits zero except for the valth bit. It then uses bitwise AND to AND this value with checker. If the bit at position val in checker is already set, then this evaluates to a nonzero value (meaning we've already seen the number) and we can return false. Otherwise, it evaluates to 0, and we haven't seen the number.
The next line is this:
checker |= (1 << val);
This uses the "bitwise OR with assignment" operator, which is equivalent to
checker = checker | (1 << val);
This ORs checker with a value that has a 1 bit set only at position val, which turns the bit on. It's equivalent to setting the valth bit of the number to 1.
This approach is much faster than yours. First, since the function starts off by checking if the string has length greater than 26 (I'm assuming the 256 is a typo), the function never has to test any string of length 27 or greater. Therefore, the inner loop runs at most 26 times. Each iteration does O(1) work in bitwise operations, so the overall work done is O(1) (O(1) iterations times O(1) work per iteration), which is significantly faster than your implementation.
If you haven't seen bitwise operations used this way, I'd recommend searching for "bitwise operators" on Google to learn more.
Hope this helps!

ASCII Table



Dec  = Decimal Value
Char = Character

'5' has the int value 53
if we write '5'-'0' it evaluates to 53-48, or the int 5
if we write char c = 'B'+32; then c stores 'b'


Dec  Char                           Dec  Char     Dec  Char     Dec  Char
---------                           ---------     ---------     ----------
  0  NUL (null)                      32  SPACE     64  @         96  `
  1  SOH (start of heading)          33  !         65  A         97  a
  2  STX (start of text)             34  "         66  B         98  b
  3  ETX (end of text)               35  #         67  C         99  c
  4  EOT (end of transmission)       36  $         68  D        100  d
  5  ENQ (enquiry)                   37  %         69  E        101  e
  6  ACK (acknowledge)               38  &         70  F        102  f
  7  BEL (bell)                      39  '         71  G        103  g
  8  BS  (backspace)                 40  (         72  H        104  h
  9  TAB (horizontal tab)            41  )         73  I        105  i
 10  LF  (NL line feed, new line)    42  *         74  J        106  j
 11  VT  (vertical tab)              43  +         75  K        107  k
 12  FF  (NP form feed, new page)    44  ,         76  L        108  l
 13  CR  (carriage return)           45  -         77  M        109  m
 14  SO  (shift out)                 46  .         78  N        110  n
 15  SI  (shift in)                  47  /         79  O        111  o
 16  DLE (data link escape)          48  0         80  P        112  p
 17  DC1 (device control 1)          49  1         81  Q        113  q
 18  DC2 (device control 2)          50  2         82  R        114  r
 19  DC3 (device control 3)          51  3         83  S        115  s
 20  DC4 (device control 4)          52  4         84  T        116  t
 21  NAK (negative acknowledge)      53  5         85  U        117  u
 22  SYN (synchronous idle)          54  6         86  V        118  v
 23  ETB (end of trans. block)       55  7         87  W        119  w
 24  CAN (cancel)                    56  8         88  X        120  x
 25  EM  (end of medium)             57  9         89  Y        121  y
 26  SUB (substitute)                58  :         90  Z        122  z
 27  ESC (escape)                    59  ;         91  [        123  {
 28  FS  (file separator)            60  <         92  \        124  |
 29  GS  (group separator)           61  =         93  ]        125  }
 30  RS  (record separator)          62  >         94  ^        126  ~
 31  US  (unit separator)            63  ?         95  _        127  DEL

http://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

Wednesday, March 5, 2014

Eclipse - Unable to install breakpoint due to missing line number attributes

I had the same error message in Eclipse 3.4.1, SUN JVM1.6.0_07 connected to Tomcat 6.0 (running in debug-mode on a different machine, Sun JVM1.6.0_16, the debug connection did work correctly).
Window --> Preferences --> Java --> Compiler --> Classfile Generation: "add line number attributes to generated class file" was checked. I did a clean, recompile. I did uncheck it, recompile, check it, recompile. I made sure the project did use the global settings. Still the same message.
I switched to ant build, using

Still, same message.
I didn't find out what caused this message and why it wouldn't go away. Though it seemed to have something to do with the running Tomcat debug session: when disconnected, recompiling solves the issue. But on connecting the debugger to Tomcat or on setting new breakpoints during a connected debug session, it appeared again.
However, it turned out the message was wrong: I was indeed able to debug and set breakpoints, both before and during debugging (javap -l did show line numbers, too). So just ignore it :)

MyEclipse 10 autocomplete not working

Turn on Autocompletion by going to Java->Editor->Content Assist->Advanced. Ensure that Java Proposals is selected.
Eclipse Window Preferences

CLUSTERING IN WEBSPHERE APPLICATION SERVER

Clustering is a very critical aspect of any middleware enterprise application. It provides capabilities of high availability by providing fail over and load balancing mechanism.
This post is a sample demonstration of configuring a cluster in WebSphere Application Server Network Deployment 7.0.
Prerequisites:
Deployment Manager Profile created using profile management tools.

Steps:
1. Create Cluster definition.
Log into WAS Admin console — > Servers — > Clusters — > WebSphere application server clusters.
Clustering in WebSphere
Clustering in websphere
Clustering in websphere

2. Create cluster members.
Provide the details about the cluster members.
Clustering in WebSphere

Define the node on which the cluster member would reside.
Also define whether the server would be generated based on a server template.
You can add additional members to the cluster.
Clustering in WebSphere
Cluster-Complete
Once the cluster is created successfully, it would be in stopped state by default.
3. Make sure the node agent is started.
Go to System administration from left panel — > Node agents — > Check the status.

Clustering in WebSphere
Clustering in WebSphere

If the Node Agent is not  started, you can execute the below script to start the same.
WAS_HOME/profiles/YOUR_PROFILE_NAME/bin/startNode.cmd
4. Start the cluster.

Cluster-Start

Further reading:
http://pic.dhe.ibm.com/infocenter/wasinfo/v6r0/index.jsp?topic=%2Fcom.ibm.websphere.nd.doc%2Finfo%2Fae%2Fae%2Ftrun_wlm_cluster.html

Some common issues while configuring a cluster in WebSphere Application Server.
Issues:
1.
Cluster member MyServer1 will not be started because the Node Agent on node Node02 is not active. Cluster members can be started individually from the cluster member collection panel.
Remedy:
Make sure you start the Node Agent.
2.
The node agent on node Node02 must be started to perform the restart operation. Node agents in stopped state cannot be started from the console.
Remedy:
You would need to start the node agent from command line as below.
WAS_HOME/profiles/YOUR_PROFILE_NAME/bin/startNode.cmd

3.

Caused by: com.ibm.websphere.management.exception.AdminException:ADMU7707E: Failed while trying to determine the Windows Service name for server: nodeagent; probable error executing WASService.exe: com.ibm.websphere.management.exception.AdminException: ADMU7709E: Unexpected exception while processing server: nodeagent; exception = java.io.IOException: Cannot run program “D:\Softwares\bin\WASService.exe”: CreateProcess error=740, The requested operation requires elevation.

Remedy:
Check whether the node agent service is present or not. If not create a node agent service as below.

WAS_HOME\bin> wasservice -add Dmgr01_NodeAgent
-servername server1 -profilePath “D:\Softwares\profiles\Dmgr01″
-wasHome “D:\Softwares” -logFile “D:\Softwares\profiles\Dmgr01\logs\nodeagent\startNode.log”
-logRoot “D:\Softwares\profiles\Dmgr01logs\nodeagent” -restart true -startType automatic

4.
The node LTADKAW7Node01 is not synchronized with the master configuration. This may prevent cluster member MyServer1 from starting correctly.
Remedy: Synchronize the node.

Cheers,
Wonders team :-)

How can you find out which process is listening on a port on Windows?

C:\> netstat -a -b
(add -n to stop it trying to resolve hostnames, which will make it a lot faster)
Edit: +1 for Dane's recommendation for TCPView. Looks very useful!
-a Displays all connections and listening ports.
-b Displays the executable involved in creating each connection or listening port. In some cases well-known executables host multiple independent components, and in these cases the sequence of components involved in creating the connection or listening port is displayed. In this case the executable name is in [] at the bottom, on top is the component it called, and so forth until TCP/IP was reached. Note that this option can be time-consuming and will fail unless you have sufficient permissions. -n Displays addresses and port numbers in numerical form.