Thursday, August 25, 2011

Slowly Moving To Blogger...

If you've commented on any of my posts in the past, they're gone. I'm sorry... this doesn't mean I didn't appreciate the feedback (trust me, I do!!!), I just decided to recently migrate my content over from Wordpress to Blogger.

This also explains why all the posts here all happen to be on the same day ;)

A Few Thoughts On Code & Being an Interpreter

I think somewhere around my sophomore or junior year, the EECS department head had decided to come down and talk to some of us about what he thought would lead us to success upon graduation.

We'd all gathered in the computer lab to hear what the man had to say. The first thing I remember him asking was "do you all know what an inter-per-ner is?"

(Silence from everyone)

"Anyone?... Can anyone tell me what an inter-per-ner is?"

We all gazed at him and each other - our gazes reflecting the fact that we had no idea what that last word was. We all had a difficult time understanding his harsh Indian accent.

Did he say interpreter? He was speaking to a group of young bright Engineering students! Of course we knew what an interpreter was! We were only somewhat certain that this was not the word he had intended to use. If it was however, we wanted to see where he was going with this (a few inner chuckles arose in some of us, since if this was the word the man was trying to use, he clearly needed one. But I digress).

As he continued on, he began to bring up things like innovation, research, and capitalizing on research to drive a business. He began to talk about our need to understand business and that the way we would all be truly successful was to embrace an "inter-per-ner-ial" spirit.

Ahhhh! Entrepreneur! Looking around it was easy to see that we were now on the same page. There was a gulf in understanding for a bit, but with a little more context, we realized he wasn't telling us to go out and be interpreters, he was telling us to go out and be entrepreneurs!

All of the students had a good chuckle about the irony afterwards. We're engineers - we're not well known for our people or communication skills. This reinforced that stereotype.

During my long runs, I reflect on all sorts of experiences such as the one I'd just mentioned. It was during a recent long run that this one popped into my head and I thought to myself "you know - I like the interpreter version a bit better..."

Although it wasn’t what the department head had meant to say, and in no way the direction he’d headed, I think there's truth in the statement that within Computer Science & Engineering one of the key ingredients to success is to be an interpreter.

Every line of code written is an interpretation of intent. High level languages have allowed us to convey this intent more clearly and cleanly. In a very broad sense, when writing code we are communicating our interpretation of a set of solutions to a set of problems which have been communicated to us.

We as developers interpret the problem in a higher domain, devise an algorithm to solve the problem in a higher domain, and communicate, through code, our algorithm.

In most cases this sequence of events isn't straightforward. We bounce back and forth filling in pieces of the high level domain that we don't quite understand or that change frequently. We refine our solution in the high level domain as these gulfs in understanding narrow. We then revise our code - our communication channel to the machine.

Success lies in being able to communicate effectively at every point in the process. This includes person-to-person technical and non-technical communication skills and person-to-machine-to-person technical communication skills.

No - the additional "to-person" appended to person-to-machine was not a typo. Person-to-machine-to-person (I'll shorten this to PMP to make things easier on me) means that as a developer, the code you write is written in such a way that your intent should be communicated so that you and others can read and quickly understand the intent communicated to the machine. PMP means using facilities of the high level language you're developing in to express the intent in a way that is quickly and clearly understood and is as close to "natural" language (Person-to-Person language) as one can make it.

Bob Martin and many others use the analogy of writing a first, second... and so on draft of an English paper in school. In the first draft, we hurriedly get our thoughts together - getting words down quickly to express those thoughts. As we revise, we organize what we’ve written so that our intent is better understood. We have others read our work and critique it so that we can be certain that others can understand our intent. We remove excess and possibly add where needed. We continue this process (sometimes until frustration or exhaustion) until we come to a point where we feel that, although not quite "perfect", our work conveys our intent as best as possible within the constraints of time and energy that we (or others) have allocated for the work.

Success lies in not stopping after that first draft. It lies in revisiting our drafts, opening a dialog with others about these drafts, and refining them so the intent is clearly communicated.

Being a developer is in many ways like being an interpreter. If we're going to be better interpreters we must practice communication at every facet in the development process. We must constantly refine the ways we communicate with one an other, and practice communicating so that we can do so effectively. As a developer, this includes the way we communicate through our code.

I'm sure we have all been within a section of code that consumed a great deal of time in order to understand it. It might even have been a section of code that you wrote ( I know I’ve been in this predicament more than once) - hurriedly, lazily, or long ago. If that section is written in a way that doesn't quickly lead to an understanding of its intent, developer time is wasted. This is true in even simple cases where code can be easily understood, but improving its structure could save developer time later on down the road.

I think the Compose Method example in Joshua Kerievsky's Refactoring to Patterns (p.123)  illustrates my above point well.
Consider the following method - it’s fairly short and straightforward and it’s fairly easy to understand what it's doing.
public void add(Object element){
     if(!readOnly){
          int newSize = size + 1;
          if(newSize > elements.length){
               Object[] newElements = 
                    new Object[elements.length + 10];
               for(int i = 0; i < size; i++)
                    newElements[i] = elements[i];
               elements = newElements;
          }
          elements[size++]=element;
      }
}
now consider the composed method refactoring of the above:
public void add(Object element){
     if(readOnly)
          return;
     if(atCapacity())
          grow();

     addElement(element);
}
Which one took less time to understand? Which one reads more naturally? The code still functions the same way but now some of the more detailed logic has been abstracted away to atCapacity() , grow(), and addElement() so that the codes intent becomes clearer.

Others are now able to interpret this code quickly. The author has done due diligence to interpret the high level intent and communicate this to not only the compiler, but also to others who may have to maintain the work. This is the sort of skill that we as developers must strive for. We should constantly refine our interpretation techniques and our communications skills.

As a closing remark, I'd like to add that everything above is in draft form.  I’m learning to be a better interpreter and learning to refine the ways I communicate everyday. Please comment and critique so that I can learn how to better communicate - and how to better interpret my thoughts into a clearer form.
Thanks!
++dave;

String theory - StringBuilder vs. String + String in the great speed debate!

I had a debate a while back about the efficiency of string concatenation using the '+' operator.
This recently came around again  on a Java forum that I had posted on.

I'd seen some code that had concatenated several strings using StringBuffer.

The code was pre-JDK 5 and we were re-using bits of it for a project I was on. Since StringBuffer wasn't needed
as no synchronization was being performed, the first refactoring prior to migration was changing StringBuffer to StringBuilder.

What struck me as odd was that the (now StringBuilder) object wasn't being used inside of any sort of loop structure or any other programmatic
structure that would warrant the creation of a StringBuilder object.

The code actually looked similar to this:
public String message1(String value1, String value2) {
     StringBuilder messageBuilder = new StringBuilder();
     messageBuilder.append("Value ")
     .append(value1)
     .append(" is greater than ")
     .append(value2);
     return messageBuilder.toString();
}

Since I thought this to be a bit overkill, I refactored the code to now look similar to this:

public String message1(String value1, String value2) {
     return "Value " + value1 + " is greater than " + value2;
}

Let The Debate Ensue!

This started quite the performance debate. Many of my colleagues on the project were under the impression that StringBuilder concatenation
is ALWAYS faster than String concatenation using the + operator. Many of them also thought it bad practice to use anything but StringBuilder
when concatenating multiple Strings and had gotten in the habit of using Builder's for all concatenation in all code to "speed things up".

I will agree that there are certain instances where using StringBuilder performs better than using Strings and +. Loop structures are one such
case. Appending to a String is much faster inside a loop structure with a StringBuilder (provided the builder was created outside the loop
structure where the appending occurs) than using + or +=.

But StringBuilder isn't a one-stop shop for String performance enhancement by any means.

Used in the above code example it does 2 things:
1. Makes the code uglier. Granted, this is my own opinion and I'm sure that some might disagree. I personally feel
that the chained calls to append() are ugly when used like this. I think that in cases like this, using + to concatenate
Strings is less intrusive and makes the code easier to read.

2. IT ACTUALLY HURTS PERFORMANCE! - This is was the core of the above debate. Many had taken the StringBuilder for performance
pattern as gospel and had never looked into when this is applicable and when it isn't.

If you don't believe me, try a simple test of timing the calls of the above methods for yourself ( I recommend using
System.nanoTime() instead of System.currentTimeMillis() ).

If your a bit more curious - take a look at the actual bytecode that is generated from each of the methods using a tool like ASM!
This is where things really get interesting!

GWT: Unterminated string constant

This is another one of those GWT "gotchas" I came across in Internet Explorer.

I have a JSON object with a field that's chocked full o' chars (its a big string :) ) This field is displaying descriptive information on the page in every browser BUT IE (go figure).

When debugging, I got this little bugger:

" com.google.gwt.core.client.JavaScriptException: (SyntaxError): Unterminated string constant number: -2146827273 "

Well that's helpful! So - I snagged the JSON and loaded it up in the first online JSON parser google gave me. Everything looked fine. Ugh! No errors, everything is hunky dory, but in IE, well...

After a long battle with the browsers and looking at the underlying utility class I was using, I saw that the method I was calling was using the native eval().

The method looked a little something like this:
private static native JavaScriptObject evaluate( String json )/*-{
     return eval("(" + json+ ")");
}-*/;

Aha! - this is where the problem was. Turns out that the String being passed (the JSON object) who's very descriptive field was chocked full o chars contained some chars that IE wasn't too happy about.

New line chars! It turns out that if you have any"\r\n" in your JSON, IE tends to get a bit angry and call it quits when eval'ing.

The solution? Well - I threw in some logic to take care of formatting the String for IE. I put the format in its own method in case I have to modify the String in any other way down the road.

Once I popped in the below, everything seemed to work AOK!

public static JavaScriptObject evaluate(String json){
     String formattedJson = formatForCrossBrowserCompatibility(json);
     return evaluateFrom(formattedJson);
}

private static String formatForCrossBrowserCompatibility(String json){
     String formattedJson = json.replace( "\r\n", "\\r\\n" );
     return formattedJson.trim();
}

private static native JavaScriptObject evaluateFrom( String json)/*-{
     return eval("(" + json+ ")");
}-*/;

Pushing Forward

There's a phrase that bothers me quite a bit when I hear it. Lately, I've heard it a lot. I hope that as I continue on in software development, that I can somehow manage to erase this phrase from my use. The phrase I'm referring to is "push back".  I've heard this used numerous times when client requests come in - "we can't do this... we need to push back" , "how did this requirement slip in? Someone's not pushing back on the client" , etc. etc.

When did the relationship between the developer and the client move to the battle field? Take a look at free dictionary's definition of push back. When did the client become the enemy?

I know that we have to protect the business and have to ward off scope creep. I understand these things well. But we also have to protect our environment and our relationships. This is where using phrases like 'push back" do more harm than good.

At the inception of  a project, things tend to be positive. The developer(s) begin(s) to learn about a clients needs and drafts solutions for the client. More often than not, both parties are pretty positive. The client has found a partner to build their dreams! The developer(s) have found problems that need to be solved and are anxious to provide a solution!

Development is an evolutionary process though. We as developers can never fully see into the mind of the client and often only understand small compartmentalized pieces of a much larger puzzle. The client might not fully understand what the developer(s) can provide, and might not fully understand how what they can provide maps to their problem.

-Enter Frustration-

The situation I describe above can lead to (at varying degrees) conflict between the developer(s) and client. The client gets frustrated with the developer(s) for not being able to fully see what is evolving in their mind. The developer(s) get frustrated because as the project evolves, the client desires change that may not have been anticipated.

-Enter a Critical Point-

How we handle the above can make or break a project. There are pros and cons with heading in any direction at critical decision points. Sometimes the client might not know these pros and cons. It is our job as developers to work with the client, guiding where we can, being guided when we don't understand, both openly and honestly.

This does not, and should not mean "pushing back". This should instead be an opportunity for us as a team and as a partnership to PUSH FORWARD.

Pushing back implies that at these critical decision points, we are in conflict. It implies that the client is attempting to guide us in a direction that we must aggressively provide resistance against. It is a negative term that (in my opinion) only leads to negativity seeping into a project.

WE ARE NOT IN CONFLICT WITH A CLIENT. We have a relationship with clients. That relationship should stay positive. We must work with our clients to keep that relationship positive. When we find ourselves at a discussion point with the client , WE MUST GUIDE EACH OTHER. WE MUST PUSH FORWARD into a direction that we both feel comfortable with.

Honesty with each other should guide this. We must be up front with what we know, and what we don't know. We must address these unknowns and identify reasonable action if, while pushing forward, we find ourselves treading on rocky ground.

I know this might seem like silly semantics. Push forward, push back, does it really matter?

I think it does. Relationships stay strong through positive re-enforcement. What we say and how we say it matters.

With that in mind, I'm going to make an honest effort to never use the phrase "push back" in the context of a developer / client relationship ever again. I'd like to replace it with something I see as more positive - pushing forward.

More on Java 7 - Try/Multi-catch!

Rambling on a bit more from my previous post about new Java 7 syntax, I wanted to comment a bit on how happy I am with the spiffy new "multi-catch"!

One thing I REALLY hate to see in code is ugly try catch blocks. What do I mean by ugly? Let me give you an example
try{
     openUserInputStream(DEFAULT_FILENAME);
     parseUserInput();
     closeUserInputStream(DEFAULT_FILENAME);
}catch(GnarlyParseException e0){
     logGnarlyException(e0);
}catch(GnarlySyntaxException e1){
     logGnarlyException(e1);
}catch(IOGnarlyOpenException e2){
     logIOException(e2);
}catch(IOGnarlyCloseException e3){
     logIOException(e3);
}
I've seen a lot of code that looks very similar and in my honest opinion, it's a bit of an eyesore. We have 4 unique catch blocks performing 2 unique actions. Now, since it would appear (from my very contrived example) that we're doing nothing more that logging here, there are several ways around this. In fact, I'd argue that there are several ways to re-factor this and make it a little more "pretty". But that, my friend, is a different post for a different day (probably a day in the very near future - I've been reading "Uncle Bob" Martin's Clean Code and have quite a bit to say...)

What I'm here to write about now is the spiffy new multi-catch in Java 7.

Multi-catch allows you to place more than one exception within one catch block, separating each with the "|" character!

So, I can take the above code and modify the try/catch to look like this:
try{
     openUserInputStream(DEFAULT_FILENAME);
     parseUserInput();
     closeUserInputStream(DEFAULT_FILENAME);
}catch(GnarlyParseException|GnarlySyntaxException e0){
     logGnarlyException(e0);
}
catch(IOGnarlyOpenException|IOGnarlyCloseException e1){
     logIOException(e1);
}
Just a little FYI - the Exceptions are "caught" from left to right in a block like this, just like they're caught top down. That is, lets suppose that IOGnarly* Exception both extend IOException.

Lets also spoz that we'd like to handle a general IOException as well. If we were handling each with it's own catch block it'd be a syntax no-no to put IOException in a block above the other two. You're compiler would yell, kick, and scream, tell you to fix your code and send an email to your boss and all of your co-workers.

It gets just as angry if you try to do something like this " catch(IOException|IOGnarlyOpenException e)"so don't do that ! Good stuff to remember if you plan on taking an OCJP 7 exam ;)

Java 7 and ARM - no need for close!

If you haven't seen them yet, there are some pretty nifty new language enhancements coming (er… here) in Java 7!

One such feature allows you to remove your close!!!

No, not clothes, .close()! Lets take a look...

Spozing' you have a nifty little method that’s in charge of writing every object in a list to an ObjectOutputStream. If one were in a hurry one might write something that went a little like this:

try{
     ObjectOutputStream objectOutput = getDefaultObjectOutputStream();
     List bars = getBars();
     for(Bar bar : bars){
          objectOutput.writeObject(bar);
     }
}catch(Exception e){
     logError(e);
}

Now, ignoring the fact that I'm catching any old error here, do you see anything else wrong with this picture?... Take a good look… Do ya see it?...

Aha! I've got no close() !

Having caught the issue one might decide to modify the code a little bit and do something like the following:
ObjectOutputStream objectOutput = null;
try{
     objectOutput = getDefaultObjectOutputStream();
     List bars = getBars();
     for(Bar bar : bars){
          objectOutput.writeObject(bar);
     }
}catch(Exception e){
     logError(e);
}finally{
     objectOutput.close();
}
But that’s ugly! I'll have to modify the method this is in to throw IOException (since I'm not handling it in the finally) and I might want to check that objectOutput isn't null before calling close (just in case something went awry in getDefaultObjectOutputStream(), which I didn't do!).

Thanks to some nifty new features in Java 7, I don't have to remember my close() anymore! Java remembers my close() for me!

Applying the new fanciness to the above, I can go ahead and do this:

try(ObjectOutputStream objectOutput = getDefaultObjectOutputStream();){
     List bars = getBars();
     for(Bar bar : bars){
          objectOutput.writeObject(bar);
     }
}catch(Exception e){
     logError(e);
}

Thanks Java 7!

If your curious about this, take a gander at ARM (automatic resource management)...

If you want to check some of the new stuff out yourself in the comforts of a reasonably friendly IDE, I'd check out the Netbeans beta! Eclipse hasn't added support for the new JDK 7 so unfortunately, I wasn't able to play around in my IDE of choice ;)

There'll be more posts from me on the way, but right now I want to play! Hooray Friday!

Hey .intern() ... get me a String!

A lot of us that work in Java take Strings for granted. Some of us toss them around like primitive types paying little regard to what they represent or how they should be used. Because of this, some classic problems like "==" vs. ".equals()" arise. Just in case you don't know what I'm talking about here, in Java using == to test for equality between two objects (let's call them A and B), results in a comparison  of the reference to which A and B refer, NOT the value to which they refer. Notice that I said OBJECTS. Thats the key word here. I'm not talking about primitive types like int, short, char, boolean, etc... I'm talking about OBJECTS. Sometimes, people forget about Strings being objects so you'll see something like if ( A == B ){ ... I recently ran into a bug in a piece of code that was caused by just that. It actually went a little something like if( "VALUE" ==  srt ) { ...

If you read the above and scratched your head in confusion, I suggest taking some time to learn a little bit more about Strings, comparison operators, and a little bit more about Java in general before continuing onward.

If you've read the above and I've bored you, GOOD! This NEXT section is a little more interesting...


AND NOW, HERE'S WHERE THE WHEELS FALL OF THE CART!

There are times, in Java land, if you REALLY, REALLY, REALLY, know what you're doing, when you CAN use == to evaluate 2 Strings. I'm going to warn you though - I don't think I'd ever even use what I'm about to talk about unless I ABSOLUTELY HAD TO for some reason or another and ONLY after thorough testing.

And so, I introduce...


String.intern()

Since String objects are immutable in Java land, there are tons of little things you can do to produce all sorts of new String objects during runtime. Take for example, the following code:

String x = "FOO";

....

public String bar(String z)

{

return z+z;

}

...

String y = bar(x);

So now, our variable y is assigned the value "FOOFOO". What if, however, somewhere out in our program we had another variable w. And, lets just pretend that our variable w was assigned the value "FOOFOO" during runtime. Since Strings are immutable, we could have just used y to point to our w reference since we could, for all intents and purposes, consider them in this case to be equal.

Enter String.intern().  So, in a nutshell, .intern() is basically your way of saying "Hey... if there's already a String out there in Java land, point my value to that guy instead. I know he's not changing. I'll just use him!"

Under the hood, your JVM keeps a little pool of unique Strings floating around and happy for just this occasion.  If you call .intern(), the JVM lifeguard takes a gander into that pool to see if you look like anyone in there. If you do, he points you to that guy. If you don't, he throws you into that pool.

All of your String literals and compile time constants are in here. Runtime strings aren't. Not unless you invoke .intern().

So, that being said, if you use this method consistently throughout your program, you COULD replace your .equals() evaluations with ==.  Why would one do such  a thing?

Take a look at the String.equals() source (right around line 854). There's actually a LOT going on here. Especially down in that for loop! Using == might be a bit faster for evaluating equality in this case!

Here's the catch - you incur some up front loss in performance for some gains later on down the road. Calling .intern() isn't free OR cheap. In fact, you might see some people out there writing about how using if ( s0.intern() == s1.intern() ){...  is faster than if (s0.equals(s1)){...

I've run a few performance tests. Nothing too in depth (I was just curious to see for myself) but in most simple cases, the second evaluation is your safer bet. I encourage you to try it out for yourself! If you're really curious, take a look at the byte code! In some not-so simple cases however, you MAY achieve some performance gains. I wouldn't recommend s0.intern() == s1.intern() for evaluation, but rather s0 == s1 IF AND ONLY IF you have guaranteed that these Strings have been intern() 'd !

 

More IE issues: GWT setInnerHTML() and HTML5 tags

I meant to post this on here a while ago so I wouldn't forget to check up on this issue (p.s. - I forgot).

A while back , I had a few issues using some of the newer HTML tags ( <article> to be exact) in Internet Explorer. I was manipulating a String of HTML, and passing this String into the constructor of an HTMLPanel. Things looked wonderful in Firefox... but not so wonderful in IE. As I dug down deeper, I noticed that HTMLPanel is using Elemenet.java 's setInnerHTML() method which calls the native "this.innerHTML".

Bad things happen in IE land with this little guy. I was under a bit of a time crunch, so, although not quite semantically correct, I replaced the <article> tag I was using with a plain old <div> in IE before instantiating my HTMLPanel.

Its not pretty - just a temporary fix until a later date. I did submit a bug to the GWT folks ... it's still in new status though. Maybe I'll have to take a crack at that one and just fix it myself :)

Why does GWT History in IE make my page refresh?...

It's always something simple -  Dang '#' delimiter...

I'm still pretty new to Google Web Toolkit- I've been "gwitting" it up for about 2 months now, so there are far more experienced GWT guys out there. If my answer doesn't help - check one of their blogs or the GWT Issues List...

So - here's what my issue was: I chose to use the history token as a string containing values which I would parse to determine page state. I chose the '##'  as my delimiting token thinking that this was a fairly safe choice.

Turns out that isn't the case. If you check out the issues list for GWT you'll find this little guy . As it turns out, Internet Explorer doesn't play nice with using '#' within your history token. Good to know!

The workaround did it for me - changed up the '##' token with '&&" and all was go.

Spring Cleaning... do I really need this file?

It's amazing how much digital crap can accumulate. I don't watch too much television, but I have seen the show "Hoarders" and I have navigated my way through a few directories that deserve an episode on the show.

Its an easy thing to do - fill your hard drive up with crap that is... I'm guilty of it at home sometimes. I'll surf around the internet for little tidbits of information. Maybe come across a good link or a .pdf. Sometimes I'll copy some pics from a camera into a temporary directory thinking I'll sort through them later...
Over time, crap just builds and eventually /home ends up looking more like /pile_of_crap.

I ran into this dirty directory problem a year or so ago on a particular server that was continually filling up at work. Cleaning house can start of pretty simple if you already know where to look, but if the house isn't your primary domicile and you're not quite sure if someone else is going to need that ginormous file over there in the corner, there's only so far you can go when tidying up.

~ AGEDU to the rescue! ~

While tidying that server up to free up some resources, I came across a nifty little tool that Simon Tatham created to help out with the aforementioned. The tool is called agedu.

It's pretty simple and easy to use, not overly fancy but not underly lame, and the source is open for the peeking ;)

So, since spring is here, I thought I'd share.

I've managed to use this on both *nix machines and Windows boxes (with a little help from Cygwin) and haven't as of yet had any problems building or running the tool.  Its definitely served me well and let me clear our some crap I just don't need. Good stuff!

int i = 0; i = i++; /* How to Make Your Friends and Co-workers Scratch Their Heads in Less than 2 lines of Code */

Looking for a great way to kill productivity (stop! and get back to work!!! ;) )? Want to stump that developer who thinks they've seen it all? Well then have I got the code snippet for you!
(sorry - I felt the need to sound like an info-mercial salesman there for no good reason)...

Don't ask how this problem came up... It was one of those things that started off as a joke, but then got people thinking and scratching their heads...

Consider the following code snippet:

int i = 0;
i = i++;
/* output 1 if Java use System.out.println(i); if C/C++ use printf(%d,i); */
i = ++i;
/* output 2 if Java use System.out.println(i); if C/C++ use printf(%d,i); */


Seems pretty simple doesn't it? I bet though, that if you ask a handful of developers what the output on 1 & 2 would be, that you'd get some pretty interesting answers. This tiny little code snippet turned into a long discussion on more than one occasion. When actually run, most assumptions were wrong and many were stumped.
I suggest trying it yourself in your language of choice if your curious! You might be surprised too!... The TRULY surprising part might be that your language of choice might provide you with one answer when compiled with one compiler version, and another result when the same code is compiled using a different version.

Since this all came about in a Java shop, I immediately went ahead and ran it -
0 , 1 (yeah - I spoiled the surprise... sorry)
Wishing to get some clarification on what was going on, I surfed the web and found some help here.

It seems like (under the hood), that this:
int i = 0;
i = i++;

basically translates to this:
int i = 0;
int temp = i;
i++;
i = temp;


that is, since we're post incrementing on the right hand side of the above, that the expression is evaluated and stored in "temp", i is incremented, then the assignment occurs to the initially stored value... (thats what the above link seemed to point out...)

This seemed logical and explained the resulting values.

So I tried it out in C. I went ahead and wrote up the snippet and compiled with GCC version 3.something or other.
output- same as Java. 0,1.

So, I took the above explanation as a decent one that seemed to be applicable to both Java and C/C++...
Then the wheels fell off of the wagon. A buddy of mine and I were chatting when I brought up the above mentioned problem. Being the curious chap he is, he went and tried the same.
In C, using GCC, but this time version 4.2.something or other.
output... TOTALLY DIFFERENT! 1,2.

So I let out a big sigh. Back to finding answers...

The jury's still out on this one for me. Now on my TODO list is trying to determine where and how this is defined (or if it is!).
I recently came across a site that might point to this being undefined in C/C++ (found here)
But since you can't trust everything you read on the internet (except the stuff I write :) ) I'd like to find a "more offical" source if I can.

I know its a trivial thing, but its one of those trivial things thats gotten under my skin and that I now want to know the answer to.
I know the code looks trivial too... but there is some pretty gnarly looking code out there in the wild and who know's if anyone is doing something like this (or similar):
i = (someCrazyFunction() + 1) / i++; /* threw in the 1 for good measure! */

I guess the best thing I've gotten out of this is that... just because you think you know what the compiler is going to do, doesn't mean that the compiler is going to do that. So often we take whats going on under the hood for granted. Abstraction is a great thing and helps us crank out code faster and build bigger and better (okay... thats arguable) things. If we're going to operate within an abstraction though, we should have an understanding of not only what that abstraction provides us but also its limitations...

Ubuntu 9.10 + apt-get + proxy = yet another proxy work-around

Ah, the joys of life behind a proxy... So there I am setting up a little "under the radar" Ubuntu sanbox. After a quick and speedy install of 9.10 on a once lifeless and abandoned box, I went ahead and pulled down SSH so I could set things up @ my leisure remotely.

Using Ubuntu's GUI, I setup my proxy credentials through the Settings->Preference->Network menu. Things seemed to work like a champ and I was able to pull down SSH using the synaptic package manager GUI.

So, thinking I'm in the clear, I logoff and head on home. I decide to take some free time and setup a few things in my new little sandbox. I SSH in no prob, and attempt a little 'sudo apt-get install ..."
no buneo. Instead I get a whole lotta nothing.

So let me cut to the chase... here's what did work:

sudo su -
(go ahead and enter your password when prompted)
now that you're root
cd /etc
vi bash.bashrc


at the very bottom lines of this file add the following
export http_proxy=http://username:password@your.proxy.com:portnum/
export ftp_proxy=http://username:password@your.proxy.com:portnum/

(yeah, yeah... I know... passwords in plain-text... not good practice.)
After a good ol' :wq , logout and log back in again...
if the settings don't take, pull out the trusty ol'  sudo init 6
Once it's back up, things should be good to go! Good Luck!

HTTP/1.0 407 Proxy Authentication Required

Java IO exceptions got you down? Ran a little bit of code lately that returned a runtime exception that went a little something like this:

java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.0 407 Proxy Authentication Required"

Yeah... me too. So here's what I encountered:
The code:


//more code preceding...
final URL url = new URL(myURL);
final URLConnection urlConn;
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl, portNumber));
urlConn = url.openConnection(proxy);
urlConn.setDoOutput(true);
//more code proceding...


All looks fine and dandy but if you're like me and your proxy requires authentication, the above won't fly.
Luckily, there's a pretty simple fix... as always, this is just one way I found to get the job done. If you've come across another, post it!

Begin by making yourself a simple proxy authenticator class like this one:


import java.net.PasswordAuthentication;

public class SimpleProxyAuthenticator extends java.net.Authenticator{

private String username;
private String password;

public SimpleProxyAuthenticator(String username, String password){
this.username = username;
this.password = password;
}

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(this.username, this.password.toCharArray());
}
}
In the original code, import java.net.Authenticator and modify the code needing authentication:


//more code preceding...
Authenticator.setDefault(new SimpleProxyAuthenticator(proxyUsername , proxyPassword)); //added this line!
final URL url = new URL(myURL);
final URLConnection urlConn;
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl, portNumber));
urlConn = url.openConnection(proxy);
urlConn.setDoOutput(true);
//more code proceding...


Good luck!