Decorating directives with isolate scope in Angular 1.3

A question from reddit excited my interest. Angular 1.3 apparently has broken the ability to decorate isolate scopes.

I tried version of Angular between the 1.2.26 known working version to the 1.3.0 broken version and found the issue was introduced in 1.3.0-rc.2.

The way to get around this is hacky:

app.config(function($provide) {
    $provide.decorator('mycustomDirective',['$delegate','$controller', function($delegate, $controller) {
        var directive = $delegate[0];
        directive.$$isolateBindings['othervar'] = {
          attrName: 'othervar',
          mode: '=',
          optional: true
        };
        
        return $delegate;  
    }]);
});   

Here’s a working example: http://plnkr.co/edit/CRxhX6?p=preview

flattr this!

Manually debugging Angular scope

While a utility like Angular Batarang is invaluable, you’ll sometimes want to quickly and effectively inspect what exists on a given scope. If you’ve used Angular Batarang, you know that can be a pain in the ass. Here’s a quick alternative that works in Google Chrome, Firefox, and Safari.

Right-click on some element you want to inspect in your AngularJS-backed page. Select Inspect Element. This will open an ‘Elements’ inspector tab. Leave the element selected in that tab and go to ‘Console’. Type out the following:

angular.element($0).scope();

This will dump the scope to the console. You can assign this to a variable or navigate the parent/child scopes from here. This works because most browsers’ developer consoles support some extras in their Command Line API. The $0 refers to the most recently selected DOM element (try $0 through $4!).

You can test this out on the AngularJS Phone Catalog Tutorial. Here’s what you should see:

Android element debugging.

flattr this!

Your interview questions probably suck

I have interviewed somewhere between 200 and 300 people in my professional career. I’ve learned a lot from the process. In fact, I am planning to write a short book containing some of this “knowledge” about interviewing.

One thing I’ve always had an odd distaste for is interview coding questions based on some ridiculous scenario. For example: “There’s no such thing as a queue, create a queue using two stacks.” or “There’s no such thing as arrays, create a queue with something else.”

Two things immediately happen when presented with this kind of question:

  1. I get pissed
  2. I feel sorry for the interviewer

Why?

These types of questions are an attempt to trip you up. “Quick, think outside the box!” These questions are actually really easy, but the intentional psychological disorientation is like a verbal punch to the face. These types of questions are actually no different from saying “I need you to write me a program, but there’s no such thing as keyboards.” It can be done, but the problem has already been solved. This is why I get pissed.

We live in the real world where engineers have access to a wealth of information when we’re presented with a problem. I’ve interviewed plenty of people virtually and told them that they could use the internet if they wanted to while solving a problem. I’m realistic.

Early in my career, I gave an interview candidate a question based on an unrealistic scenario. I admittedly found this question while researching online for questions used by big software companies. The dude aced the question and was hired. He sucked as a programmer. Unrealistic interviews often yield unexpected employees. This is why I feel bad for interviewers who haven’t yet understood this. In case the message isn’t clear: unrealistic coding questions are no gauge of actual ability.

Consider the state of mind of someone interviewing for a position. If your company isn’t hugely known, your candidates can be in any number of mindsets. Including:

  • Passively open to new opportunities – not 100% interested in your company or the position, possibly only interviewing to remain ‘in the game’
  • Passively looking for new opportunities – candidate is casting a line but not expecting any bites
  • Actively looking with no other prospects – your interview is the one this candidate wants (or needs)
  • Actively looking with plenty of prospects (and possibly pending offers) – the candidate may be looking for more money or just there to ‘see how it goes’
  • Not looking – maybe recruited by your company, which increases the feeling of expectations in the candidate

In all of these scenarios, there’s an element of uncertainty which causes the brain to do some funny things (see behavioral science field of neuroeconomics). You’re putting a candidate into an unfamiliar place by having that candidate interview with your company. If the candidate comes into your office, it can heighten the risk and uncertainty that can actually hinder the application of rational thought processes to begin with. As if this isn’t enough, interviewers asking these ridiculous questions are further taking away something familiar from the candidate (even worse if asked to whiteboard these questions or use an unfamiliar coding environment). This state of mind is nearly unavoidable. The loss aversion affecting candidates who are dying for the position only furthers the problem. These feelings are magnified if you work at a company like Expedia where many candidates would do almost anything to work with you. Many developers are anti-social, making the interaction even more unwelcoming. There’s a lot on a candidate’s plate and you’re probably making it worse.

The only way I’ve found as an interviewer and as an interviewee to overcome some of this dampening mindset is to understand that an interview is a two-way street. Your company is interviewing a candidate because you need someone good on your team, but a lucid candidate is also interviewing you to see understand if your company is where they want to be for a while. From this perspective, you’re doing both sides a disservice by asking asinine questions. I’ve been told in the past that questions like these are designed to show how well someone can ‘think on their feet.’ That’s just bullshit. You can think on your feet no matter what data structures are available to you. A candidate is less likely to be able to think on their feet when their ‘fight or flight’ instincts are engaged or they’re afraid of failing an interview miserably. One could argue that the industry is constantly in flux and developers must always adapt; the fact is that the industry is constantly improving, while ridiculous scenarios are based on unrealistic regressions.

It’d be foolish to not acknowledge why these types of questions are asked. They’re often asked to demonstrate knowledge of data structures and algorithms. They’re often asked to evaluate how well a candidate can talk through a problem and come to a solution. If you’re asking such a question, allow your candidate to speak. I’ve been in multiple interviews where I just wanted to walk out because the interviewer literally wouldn’t shut up and let me finish one sentence. There’s a difference between being helpful and being rude. If you’re being rude, not only will it make a possibly good interview go poorly but it will make a smart candidate decide against your company. You may both be at a loss.

Then, there’s the level of unrealism of your question. For instance, if there’s no such thing as arrays… how is the computer operating? If there are no stacks, queues, lists, or arrays, can the candidate assume there is no such thing as contiguous memory? If there are no arrays, can I access a .Keys property of some other data structure? Are there functionally no enumerable structures?! I know I’m being ridiculous, but so is your question.

So what can you do as an interviewer?

First, put yourself in your candidate’s shoes. Don’t just put yourself in your candidate’s shoes as someone who has worked at your company for 8 years and can attack any problem with a fully clear head. Put yourself in your candidate’s shoes, feeling completely naked in an unfamiliar interrogation room with something the candidate either wants or needs dangling in front of yourself by the thinnest of threads. Your interview question probably sucks.

Second, be more realistic. Whether you’re doing a whiteboard exercise, phone screen, or virtual coding exercise, tell the candidate that they’re more than welcome to search the internet for assistance. This will immediately put your candidate at ease. I’ve told many candidates this and I’ve only had one or two people actually use the internet. Something this simple actually works wonders to unveil the true nature of a candidate. If you end up with a candidate who searches for a solution and solves your problem immediately, this means that you either have a problem that’s no problem at all (easily accessible on the internet) or that you’ve found a candidate that can get things done quickly. This will naturally lead you as an interviewer to come up with an original and realistic coding question for the next candidate.

The challenge here is to not ask puzzlers like “all numbers occur an even number of times except one, find it.” Instead, ask a question like “model an ATM” or “create a utility that dynamically loads types from every assembly in a directory.” You could ask a more advanced question like “Write a producer-consumer using a BlockingQueue” or “Write a SIP header parser”. Don’t ask questions like “Solve this obscure IIS problem that took me 5 days of research to figure out” (paraphrasing, but I’ve seen this happen). If you’re going to ask algorithm and data structures questions and you want to evaluate an area the candidate may not be familiar with, consider a reverse polish notation evaluator and the Shunting Yard algorithm.

I was prompted to write this after reading an article on Programmers StackExchange. The question and answers are a pretty good read to get both sides of the interviewing wall.

Just to be clear: I am all for asking complex interview questions. In fact, I think most actual coding questions should be questions that can’t be written in the allotted time (a realistic, yet unfortunate, software management approach). I think it’s fine to make candidates sweat a little because of complexity, but it’s a little unfair to make a candidate sweat because of unfamiliarity.

I’d be happy to hear your thoughts so I can improve as an interviewer.

flattr this!

Your First App: Node.js is complete!

I’m stoked to announce that I’ve finished writing my first self-published book, Your First App: node.js.

The book is a full-stack application development tutorial using what is commonly known as the ‘MEAN’ stack, but with a heavier focus on the backend technologies: node.js, express.js, and MongoDB. The book ends with a starter AngularJS project of an HTML5 instant messaging chat application.

While following along in the book, it may be useful to run test queries in a REST client. Postman is available for Google Chrome as a packaged application. Import `yfa-nodejs.postman_dump.json` (located in the root of the supplemental code’s repository) into Postman to evaluate the application’s API.

Check out the code on GitHub

flattr this!

Data at the root level is invalid. Line 1, position 1.

Recently, I encountered a really weird problem with an XML document. I was trying to load a document from a string:

var doc = XDocument.parse(someString);

I received this unhelpful exception message:

Data at the root level is invalid. Line 1, position 1.

I verified the XML document and retried two or three times with and without the XML declaration (both of which should work with XDocument). Nothing helped, so I googled for an answer. I found the following answer on StackOverflow by James Brankin:

I eventually figured out there was a byte mark exception and removed it using this code:

string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
    xml = xml.Remove(0, _byteOrderMarkUtf8.Length);
}

This solution worked. I was happy. I discussed it with a coworker and he had never heard of a BOM character before, so I thought “I should blog about this”.

Byte-Order Mark

The BOM is the character returned by Encoding.UTF8.GetPreamble(). Microsoft’s documentation explains:

The Unicode byte order mark (BOM) is serialized as follows (in hexadecimal):

  • UTF-8: EF BB BF
  • UTF-16 big endian byte order: FE FF
  • UTF-16 little endian byte order: FF FE
  • UTF-32 big endian byte order: 00 00 FE FF
  • UTF-32 little endian byte order: FF FE 00 00

Converting these bytes to a string (Encoding.UTF8.GetString) allows us to check if the xml string starts with the BOM or not. The code then removes that BOM from the xml string.

A BOM is a bunch of characters, so what? What does it do?

From Wikipedia:

The byte order mark (BOM) is a Unicode character used to signal the endianness (byte order) of a text file or stream. It is encoded at U+FEFF byte order mark (BOM). BOM use is optional, and, if used, should appear at the start of the text stream. Beyond its specific use as a byte-order indicator, the BOM character may also indicate which of the several Unicode representations the text is encoded in.

This explanation is better than the explanation from Microsoft. The BOM is (1) an indicator that a stream of bytes is Unicode and (2) a reference to the endianess of the encoding. UTF8 is agnostic of endianness (reference), so the fact that the BOM is there and causing problems in C# code is annoying. I didn’t research why the UTF8 BOM wasn’t stripped from the string (XML is coming directly from SQL Server).

What is ‘endianness’?

Text is a string of bytes, where one or more bytes represents a single character. When text is transferred from one medium to another (from a flash drive to a hard drive, across the internet, between web services, etc.), it is transferred as stream of bytes. Not all machines understand bytes in the same way, though. Some machines are ‘little-endian’ and some are ‘big-endian’.

Wikipedia explains the etymology of ‘endianness’:

In 1726, Jonathan Swift described in his satirical novel Gulliver’s Travels tensions in Lilliput and Blefuscu: whereas royal edict in Lilliput requires cracking open one’s soft-boiled egg at the small end, inhabitants of the rival kingdom of Blefuscu crack theirs at the big end (giving them the moniker Big-endians).

For text encoding, ‘endianness’ simply means ‘which end goes first into memory’. Think of this as a direction for a set of bytes. The word ‘Example’ can be represented by the following bytes (example taken from StackOverflow):

45 78 61 6d 70 6c 65

‘Big Endian’ means the first bytes go first into memory:

45 78 61 6d 70 6c 65
<-------------------

‘Little Endian’ means the text goes into memory with the small-end first:

45 78 61 6d 70 6c 65
------------------->

So, when ‘Example’ is transferred as ‘Big-Endian’, it looks exactly as the bytes in the above examples:

45 78 61 6d 70 6c 65

But, when it’s transferred in ‘Little Endian’, it looks like this:

65 6c 70 6d 61 78 45

Users of digital technologies don’t need to care about this, as long as they see ‘Example’ where they should see ‘Example’. Many engineers don’t need to worry about endianness because it is abstracted away by many frameworks to the point of only needing to know which type of encoding (UTF8 vs UTF16, for example). If you’re into network communications or dabbling in device programming, you’ll almost definitely need to be aware of endianness.

In fact, the endianness of text isn’t constrained by the system interacting with the text. You can work on a Big Endian operating system and install VoIP software that transmits Little Endian data. Understanding endianness also makes you cool.

Summary

I don’t have any code to accompany this post, but I hope the discussion of BOM and endianness made for a great read!

flattr this!

Your first app: Node.js (update)

I am currently writing a book called Your first app: Node.js. I am self-publishing this book through leanpub.com. You can check it out here.

One cool thing about self-publishing on leanpub is that people can purchase the book early and receive all future updates as I write. Feedback from this process may also help me to revisit areas I’ve unintentionally left a little light or not explained very well.

The book is currently about 66% completed. I recently completed the chapters through the node.js API. To complement that API, I will be writing a chapter on creating an AngularJS front-end. Then I’ll explain how to deploy your application to Digital Ocean (although the steps will be similar for many other hosts). Finally, I will provide some suggestions for further learning.

Below is the book description as shown on leanpub.

ABOUT THE BOOK

This book is intended for professionals or students who have a comfortable working knowledge of JavaScript, HTML, CSS, and the stateless nature of HTTP. If you’re not comfortable with JavaScript, I highly recommend reading both JavaScript: The Definitive Guide and JavaScript Garden. Although I’ll quickly go over some necessary fundamentals for beginners, it will be difficult to become a ‘node.js developer’ without a solid foundation in JavaScript. HTML, CSS, and client-side JavaScript will be necessary for the presentation of your application, while understanding the stateless nature of HTTP will make some of the techniques discussed in this book easier to learn.

Why this book?

Many books on a given technology focus on really digging into a certain framework or a few simple concepts. Node.js is an interesting technology for many reasons, including:

  • it popularized server-side JavaScript
  • encourages modularization
  • has a fairly large community
  • provides amazing throughput for data

I have read many technology books and yet I’ve always felt like there was a gap between books covering a given technology and how you’d actually undertake creating a full application on your own. When I realized that node.js is attracting a lot of front-end developers and hobbyists to the community, I understood what that missing “gap” was: the application life cycle. For developers without a degree in Computer Science or Information Systems, it may be difficult to figure out how to actually start creating a full application. I hope to address this in the text by providing some simple guidelines that help to lay out a clear path between the starting point and the finished product. The intended audience for this book is anyone familiar with HTML, CSS and JavaScript. You don’t need to be a professional engineer or even have years of experience. In early chapters, I discuss the aspects of JavaScript that I feel are crucial to understanding how to write an application in node.js.  Where I feel newer developers may benefit from further reading, I suggest online or print resources that I’ve found helpful.

What makes this book different?

When working with Junior developers, I try to avoid the sink or swim mentality that many Seniors seem to have.  Instead, I like to explain why I’ve chosen one thing over another. In this book, I include an entire chapter to discuss development considerations which are usually omitted from mainstream texts.  For instance, when was the last time you read a book that suggested a build automation tool? I can’t remember any book that clearly explained why a sample application was written to use MongoDB instead of Redis or MySQL. These are things I attempt to cover in this book before diving in to the meat of the text you’d find in similar books. I even have a short prototyping chapter for readers who are unfamiliar with the technologies used in the book to try some hands-on code before applying this knowledge to the sample application.

These are all things people with professional full-stack (e.g. client-server-database) experience do on a regular basis. With such a fresh, young community being attracted to node.js application development (many without server-side or database experience) I think this book’s early focus on process and maintainability are important aspects for any beginner to pick up.

Technologies

Writing an application requires a developer to pick up skills in multiple technologies for frameworks. I plan to at least cover the basics of all the tools necessary to create a full node.js application. Some of the technologies covered in this book are:

  • express.js (node.js)
  • grunt.js (node.js)
  • mocha (node.js)
  • Twitter’s Bootstrap (CSS)
  • angular.js (client JavaScript)
  • MongoDB (database)
  • git (source control)

The intention is not to fully teach a developer everything about every one of these technologies, but I will go over the basics for everything that is not considered node.js and go over the node.js technologies in greater detail.

Planned Chapters

Future chapters will focus on:

  • ✓ git workflow
  • ✓ project structure and setup
  • ✓ setting up a database
  • ✓ modeling a database “schema”
  • ✓ creating a minimal API
  • creating a front-end application
  • asynchronous communication between client and server
  • ✓ authentication strategies
  • … more

As this book is written, I welcome your feedback and comments at nodejs@ipreferjim.com

Status

This book is currently about 66% complete.

The final product is estimated to be between 200 and 250 pages in length (not including appendices).

Sample Code

Sample code for this book is located on github at jimschubert/yfa-nodejs-code.

flattr this!

Hard link in OS X

Under linux, I used mount --bind olddir newdir to link a source code directory from a git repository in my Dropbox folder to another public git repository. I did this to avoid using git submodules and, for whatever reason, git had trouble following hard links under Ubuntu.

I recently purchased a Macbook Pro, and I was trying to use the same bound mount point. The mount provided with OS X doesn’t offer --bind. A main suggestion I found online is to use bindfs. bindfs didn’t work for my needs, and I didn’t want to manually compile a link/unlink application as others suggested.

I found that the homebrew package coreutils provides the gnu version of ln. To install:

brew install coreutils

This package doesn’t overwrite OS X default packages unless you run the above command with the --default-names switch, otherwise all utilities are prefixed with a g. Using the gnu ln program, I was able to hard-link successfully:

gln -d src target

I don’t know what the difference is between Ubuntu and OS X (both running git 1.8.4), but I can now work properly under git with hard links as expected.

Installing more gnu utilities

You can go one step further and install more gnu utilities (found on StackExchange):

brew install coreutils findutils gnu-tar gnu-sed gawk gnutls gnu-indent gnu-getopt

Then, add the following to your .bashrc:

PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"
MANPATH="/usr/local/opt/coreutils/libexec/gnuman:$MANPATH"

Thanks to the Apple StackExchange user lri for the excellent post.

flattr this!

System76 notebooks… are they worth the money?

On June 19 2012, I purchased a 15″ Pangolin Performance with the following configuration:

  • Ubuntu 12.04 LTS 64 bit
  • 15.6″ 720p High Definition LED Backlit Display ( 1366 x 768 )
  • Intel HD Graphics 4000
  • 3rd Generation Intel Core i7-3610QM Processor ( 2.30GHz 6MB L3 Cache – 4 Cores plus Hyperthreading )
  • 16 GB Dual Channel DDR3 SDRAM at 1600MHz – 2 X 8 GB
  • 750 GB 7200 RPM SATA II
  • 8X DVD±R/RW/4X +DL Super-Multi Drive
  • Intel Centrino 1030 – 802.11 b/g/n Wireless LAN + Bluetooth Combo Module

Total price: $1,038.00

The price was higher than I wanted to spend, but I considered this purchase an investment. After all, I had previously owned a Sony Vaio for almost 5 years, and which I had purchased for $800. The reviews for System76 seemed a bit mixed. I’ve been using Linux or BSD as my main desktop environment since 1998, so I took a chance on the mixed reviews and made the investment.

Issue #1

After two months, I had to open a ticket because the Ubuntu version preinstalled on the machine displayed the graphics card as ‘Unknown’ and the screen itself exhibited a sort of wave of energy which was giving me headaches. I was told by the support engineer that the fix would be to install the mesa-utils package. Why is mesa-utils not installed by default if it’s a necessary package? I have no idea, but here’s the response I received from my support ticket:

It’s actually a known issue without having the mesa-utils installed. Apparently, the info is actually pulled from glxinfo.

Mesa-Utils isn’t part of the default install, and admittedly, we do not add it either. I know there’s talk of trying to add it as part of the install.

Sure.

The graphics issues were actually resolved by an early upgrade to Ubuntu 13.04.

Issue #2

In October 2012, I decide to dual boot a copy of Windows 8 from MSDN. There were numerous issues with drivers. After opening a support ticket, I was told that System76 doesn’t have access to drivers for their hardware from their vendors (bison or chicony hardware). That seems really shady, considering a machine for such a high price should have quality hardware. I ended up removing Windows 8 and installing Windows 7 within a VirtualBox VM. The hardware is beefy enough to host multiple concurrent VMs, so this is actually my preferred method for cross-platform development. However, a machine that can’t dual boot Windows basically renders the machine useless for developers who need to code at a low level like packet processing or driver development.

Issue #3

On June 15 2014, just shy of two years after purchasing this machine, I decided to open a ticket regarding battery issues I started having after installing Ubuntu 14.04. My battery began to hold no more than 75% or so charge. I inquired how to troubleshoot whether or not there were some other factors causing battery issues. For reference, here are screenshots of the battery statistics:

I was told by the support team that my battery was causing problems because:

The statistics indicated this is within your battery. The energy designed (48.8 W/hr) and full (40.0 W/hr) is where your discrepancy lies.

So, I opened a ticket saying that my machine had a max of 76% charge after hours of charging (both booted and off) and support replied saying my problem was that my battery could only hold a max charge of 83.3%. The resolution offered was to purchase a new battery at $105.

That’s not right. Every two years of ownership, I will need to purchase the same low quality battery at $105 out of pocket? In a sense, I have purchased a machine that also requires a $50/year battery fee. This seems really silly.

I admit that I had no battery issues for about two years. In fact, I was surprised by the battery life (2.5 to 3 hours) early on. Machines with a mechanical hard drive and 16GB of RAM are generally considered battery hogs. I don’t know of anyone who actually works on such a machine on battery.

Conclusion

Although my machine has worked well for two years, I don’t like the quality of the hardware or the poor response from the company about the issues I have had. I probably wouldn’t mind it if the quality of support offset the quality of the hardware. For example, if System76 actually stood behind their product and replied “Wow, our batteries should last more than 1.95 years. We’ll send you a replacement immediately,” I would recommend purchasing from the company. You do get a pretty beefy machine for relatively cheap. As a software engineer with multiple side projects and a 9 month old son, I don’t have time to continuously try to troubleshoot issues that I really shouldn’t be having with a quality piece of hardware.

My own resolution was to purchase a 13″ Macbook Pro. This machine has 8GB RAM and a 256GB SSD Hard Drive. I have been getting 8 or 9 hours of battery life, and that’s with the power-sucking Google Chrome open at all times. I became accustomed to the OS X environment while working at Expedia. Mac OS X is a UNIX certified OS, so I feel at home in the environment. The only issue I had with OS X when I first started working in the environment was the difference between COMMAND, OPTION, and CONTROL. This took a week or two to become habit. My wife also left her Sony VAIO for a Macbook Air last year and she loves it. You’d be hard-pressed to find a Linux distribution which allows for such a smooth computing experience for non-geeks.

I will be selling my System76 machine after backing up all important information. If you’re interested, let me know. You’d be getting a beefy machine and not taking along any of the annoyance of paying over $1000 for subpar customer support.

To answer the question “Are they worth it?”, I would have to say “It depends.” If you want a machine that would cost $2500-3000 elsewhere for around $1000, then yes it is definitely worth it. If you don’t mind replacing a battery after two years, then yes it’s worth it. If you’ve used Linux for a long time like I have and don’t mind spending an hour or two every time a ‘surprise’ surfaces, then yes it’s definitely worth it. If you’re like me and you have little free time, then you’ll want to open your machine and expect everything to work as expected with little or no interaction with customer support. In my case, it’s just not worth it to own a machine that requires so much maintenance. If this system was a car, I would sell it as a car that runs well and needs little or no work. That is, if you don’t work off battery you’d be all set.

flattr this!

Developer James Schubert shares his code and his thoughts.