Saturday, September 19, 2015

Changing Itunes backup location on windows

Assuming the username you are logged into is `bas`:

mklink /j "C:\\Users\\bas\\AppData\\Roaming\\Apple Computer\\MobileSync" "D:\\ITUNES"

And there you have it. Backup will now be in D:\ITUNES.

Wednesday, March 4, 2015

Create a .gitignore file on windows

As you know if you create a .gitignore file using windows explorer (or .htaccess or any other .something file) it will complain loudly.

The trick is to create a new file and call it :
.gitignore.

Notice the "." at the end. It is significant. Once you do that windows explorer will silently remove the trailing "." and you get exactly what you wanted ".gitignore"

Saturday, December 13, 2014

Github tip: Subscribe for updates to a single Issue / Pull request

When you are active in the open source world working on a bunch of active projects notifications quickly become too large to manage. Here is an example:

Fortunately a way to mange this is to only look at the notifications for issues / pull requests you are participating in.

However many times you don't have a meaningful way to participate and you end up doing this:
Comment just to participate
Fortunately you don't need to do this. If you are watching a repository (because you are active in it) you will see the message "because you're subscribed to this repository" as shown:


You can upgrade a particular issue / pull request to "participating" by clicking unsubscribe then subscribe again. Now you will see the message "because you're subscribed to this thread" as shown:

That's it. Now it will show up in "participating" for your notifications and no one needs to know (or get notified about you subscribing).

Admittedly its intuitive and I only learnt it from experience. I haven't searched for this so perhaps it is a documented way.

Friday, June 20, 2014

Getting Atom / apm to work on windows

This might be a short lived post, once Windows is officially supported you won't need this. For now, I got the built Atom from windows from here http://atom.someguy123.com

After extracting added (prepend with your extraction path) "Atom\resources\app\apm\node_modules\atom-package-manager\bin" to the windows system PATH, and then its all good

publish away : https://atom.io/docs/latest/publishing-a-package `apm publish minor`

Friday, April 4, 2014

Microsoft Sculpt Ergonomic Desktop Review

Here's what I just got:

Reason was that I've been doing a "lot" of writing and coding when at home and my old clunky keyboard / standard MS mouse was starting to give me wrist pain. I already have a MS 4000 Keyboard + Logitech Trackball in the office (which I took from home) and I can write code comfortably all day long. So clearly there was something that needed to be done for my home rig. I thought I'd give something new a shot. Out of the box:


 Has a raise bar for the keyboard as well (which I very much like):

I don't care for the numeric keyboard, so I like that it was separated. I left it in the box. My desk looks pretty clean:  

I have to admit : the best thing about this setup : the mouse. Its heavy, tall and nearly vertical. It feels like I am resting my hand on a ball. Very nicely done Microsoft!

Saturday, March 29, 2014

Setting up command prompt for screenshots

Here's my workflow. Create a new batch file foo.bat with the following contents:

title Node.js
prompt C:$G
cls

And put this in your windows path. Start it any folder using `foo.bat`. You get a nice clean looking prompt great for screenshots:


That answers "how do I hide the path on the command prompt". 

Saturday, July 6, 2013

Debugging AngularJS Source with WebStorm

The great thing about AngularJS is that it comes with a very full featured test suite. This means that you can use tests if you:

  • want to play around and try to add new features in AngularJS 
  • or try to understand AngularJS internals
This is my quick guide on the steps I had to carry out to debug the code I downloaded. I'll be using windows and webstorm. Some of these are pretty standard steps if you know nodejs + karma but should be helpful nonetheless. All commands should be run the from main AngularJS folder. The git root folder (whatever you want to call it). Not the src folder. In particular the folder where you have package.json , Gruntfile.js, karma-config-* files.

Get AngularJS source

Download (git clone) from https://github.com/angular/angular.js

Make sure you have NodeJS installed 


Install the pre requisite global NodeJS packages

You need grunt and karma. Pretty painless after you have node: 
npm install -g grunt
npm install -g karma 

Download AngularJS prerequisite NodeJS packages

Run:
npm install

from the main AngularJS folder. This will basically read package.json and download any prerequisites. 

Setup your CHROME_BIN

I have this environment variable pointing to my chrome.exe (not chrome canary).

Build Angular

Build AngularJS (required if you want to run the tests):
grunt build

Run the karma server

Simple command: 
karma start karma-modules.conf.js --no-single-run --auto-watch --reporters dots
This should start chrome + run the tests (module tests in this case as I ran karma-modules.conf.js) 

Leave this command (i.e. karma) running in the background.

Now setup debug environment in WebStorm

Create a new WebStorm project from your AngularJS folder. Edit your run configurations: 
(Don't mind that I already have debug karma setup, you will not). 

Add a remote debug config: 

Add set it up as follows. Call it whatever you want but url to open and remote url are important: 
http://localhost:9876/debug.html
http://localhost:9876/base


Great. Now set a breakpoint, Start debugging and watch the magic happen. 

Friday, July 5, 2013

Origin null is not allowed by Access-Control-Allow-Origin Chrome fix

When working on simple html prototypes that don't really need a backend server (Single page app prototypes). You often need to load html / js files from disk. This is disallowed for your protection by default and you will get errors like:

Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin. file:///D:/asdf.html
XMLHttpRequest cannot load file:///D:/asdf.html. Origin null is not allowed by Access-Control-Allow-Origin. 

Simple solution for chrome: Start with --allow-file-access-from-files option :

chrome --allow-file-access-from-files

Saturday, June 29, 2013

ASP.NET MVC Single checkbox generates two values

So a single checkbox:

Will generate two input fields in MVC CheckboxFor:

It is because the browser does not post a checkbox when the value is false. MVC takes this into account and creates a dummy field for the case when the checkbox is unchecked. So when the checkbox is checked you get ‘true,false’ instead of ‘true’

TryUpdateModel will take this all into account and work out the correct value for you.

The most awesome option in SourceTree

Rebase by default:


Thursday, June 27, 2013

AngularJS minification

Just downloaded angular source. Its no secret that AngularJS uses google closure tools. In case you are wondering how here is the grunt config:


This uses the custom grunt task as follows:

And the contents of the grunt task are just calling google closure compiler with proper arguments:


Sunday, June 9, 2013

Typescript: Indexer enforces property compliance

Here is a new thing I found about typescript 0.9Alpha. Once you specify a string indexer all other properties must be of the same type (which makes sense):

interface IBar{
    bar: string;
}

interface IFoo{
    a?: {
        [key: string]: IBar; // Once you have a string indexer all other properties
        options?: IBar;        // e.g Options, must have the same type
    }
}

var x: IFoo = {
    a: {        
        'someKey': {
            bar:'asdf' // put any thing other than a string here and you get an error
        }        
    }
}

Trying the Latest Version of TypeScript for Visual Studio

There is a blog post on the topic by the TypeScript team over at : http://blogs.msdn.com/b/typescript/archive/2013/01/29/trying-the-latest-typescript-build.aspx

However that was for TypeScript 0.8 and the path is different for TypeScript 0.9.

For Visual Studio Extension

To try out the latest built version of TypeScript, just copy the typescriptServices.js file from  the bin folder of the file you checkout from release-0.9.0 branch at  https://git01.codeplex.com/typescript over to:

C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\CommonExtensions\Microsoft\TypeScript

Overwriting what was already there.


For the Compiler

Additionally you might want to replace the tsc.js and typescript.js files in the following location:

C:\Program Files (x86)\Microsoft SDKs\TypeScript

Again using the files in the bin folder of the repository. 

Friday, June 7, 2013

Why use semicolons in JavaScript

I always use semicolons even though they are optional in JavaScript. A key reason for me is convention and javascript minification (although closure compiler will rewrite your js with semicolons inserted). But if you want to know what else could go wrong even if you do not do minification there is actually only one case. When a line starts with `(` it should have a semicolon before it.

An Example

When you have an immediately executed function to create a new scope:

// define a function with assignment
var fn = function () {
   //...
} // semicolon missing at this line

// then execute some code inside a new scope
(function () {
    //...
})();

Will get interpreted as :

var fn = function () {
    //...
}(function () {
    //...
})();

The second function will fail with a "... is not a function" error at runtime.

Another example 

// careful: will break
a = b + c
(d + e).print()
// Will get interpreted as:
a = b + c(d + e).print();

Alternate Solution

 A potential solution if you want to be a cowboy and not use semicolons everywhere is to use a semicolon before ‘(‘:

; (d + e).print()

Its also potentially a good idea when your file starts with '(' since if someone (who does not use semicolons) does concatenation of your file it might become a problem. 

An example was from this answer: http://stackoverflow.com/a/1169596/390330

Thursday, June 6, 2013

Inspect all the event handlers on a DOM Element


Here’s how chrome Developer Tools make it super simple. Just inspect an element and look inside the Event Listeners section as shown:


Expand any event and you can see what element level the event is handled on e.g. here blur is handled on document as well as the div:

You can even jump to the function body (this is a minified file so it’s all on line 1) by clicking on the filename

As an aside: there is no way to do this in your own code http://stackoverflow.com/a/2623352/390330

Saturday, June 1, 2013

YouTube video url transformations

There are some really innovative ways that you can transform the youtube url quite easily. Here are a few

Just the video frame

Use /v/ 

Download YouTube Video

Provided by a third party (save from). Add ss after www.

Tuesday, May 28, 2013

Trick question : Closures in Javascript

Closures are one of the most powerful features of the Javascript language. If there is one thing that makes JS so versatile, it has to be closures. But they can be tricky if you do not understand:
  1. Closures capture the variable not just its value.
  2. Scope only changes using functions in Javascript.
So the question, What does the following code print:

var funcs = [];
// Setup
for (var i = 0 ; i < 10 ; i++) {
    funcs.push(function () { console.log(i) });
}
// Call
for (var j = 0 ; j < funcs.length ; j++) {
    funcs[j]();
}

The intuitive answer is 0,1,2,3…9 . However that is not the case. This is because each function in setup captured the variable i and not its value. When the for loop finished the variable i has a value 10 and therefore all functions print out 10. You now understand what (1) means. 

Now let’s make these functions print 0,1,2,3…9. The solution would be to create a new variable within the scope of the for loop so that each function gets a new variable. Now the only way to create a new scope is using a function (2). Lets say you don't know this and try the following which will not work. It will print 9 instead of 10 however since that is the last value that gets assigned to foo:

// Clear
funcs = [];
// Setup
for (var i = 0 ; i < 10 ; i++) {
    var foo = i;
    funcs.push(function () {
        console.log(foo)
    });
}
// Call
for (var j = 0 ; j < funcs.length ; j++) {
    funcs[j]();
}

To fix this we use the concept of immediately executing functions i.e. we declare a function (to create a new scope) and immediately execute it (to fall into that scope). The following will work. :

// Clear
funcs = [];
// Setup
for (var i = 0 ; i < 10 ; i++) {
    (function () {
        var foo = i;
        funcs.push(function () {
            console.log(foo)
        });
    })();
}
// Call
for (var j = 0 ; j < funcs.length ; j++) {
    funcs[j]();
}

You now understand (2). You can find the code here : http://jsfiddle.net/basarat/U9brW/

As a aside you might think the following is a good idea (will not work as expected):

// Setup
for (var i = 0 ; i < 10 ; i++) {       
    funcs.push(function () {
        var foo = i;
        console.log(foo)
    });   
}

But it’s actually no different than (will not work as expected):

// Setup
for (var i = 0 ; i < 10 ; i++) {
    funcs.push(function () { console.log(i) });
}

Because the only variable that is captured by the function is still i from the outer scope.

Monday, May 27, 2013

Using Actions to clean up your code

I am a firm believer of DRY “If you are doing the same thing thrice, you are doing it wrong” . Within reasonable effort ofcourse.

So when I see code like this:

List<string> permissions = new List<string>();
// The ones we care about:
if (Session.HasPermissions(Permission.AdministrationSetPoints))
{
    permissions.Add(Permission.AdministrationSetPoints.ToString());
}
if (Session.HasPermissions(Permission.Administration))
{
    permissions.Add(Permission.Administration.ToString());
}

There is no wonder that I want there to be a function to abstract out the if conditions. But creating a new function at class level looks a bit dirty. Not only do you have a new function that is only called from one place but you need to pass in a ref argument (permissions list). Later on its unclear at first sight (without reading xml comments perhaps) why this new function was created. Additional constraints like making sure your private functions are at the end may increase the distance between your original function and this new function. 

Lucky for us C# 3.0 gave us an excellent solution with inline lambdas:

List<string> permissions = new List<string>();

Action<Permission> addPermission = (Permission p) =>
    {
        if(Session.HasPermissions(p))
            permissions.Add(p.ToString());                   
    };
           
// The ones we care about:
addPermission(Permission.AdministrationSetPoints);
addPermission(Permission.Administration);

Notice that:
  • the action (addPermission) does not need to be passed in the permissions object since the outer scope variable is available.
  • The function is declared closer to where it is used and you can tell at first look why it was created.


To be honest. For this I was inspired by JavaScript closures.

Thursday, May 23, 2013

Add Existing Item as Link in Visual Studio


It is a feature that is used very commonly for code sharing between project. But I could not find good screenshots to show someone so here they are.

Right lick project folder and select Add - Existing Item:


Now select your file and choose “Add As Link”


An additional useful option is Copy if newer:

Wednesday, May 22, 2013

Setup maxlength for strings in ASP.NET MVC

String length is an attribute available in the System.ComponentModel.DataAnnotations; namespace for your viewmodels. It sets up validation for max length e.g:

[StringLength(100, ErrorMessage = "Length must be less than or equal to 100")]

In html this will warn the user if the length exceeds 100. But if you want the html input to disallow the user to even type more than 100 characters then that functionality is not provided out of the box. You can use the attribute added to the html tag because of StringLength ie. data-val-length-max to add the maxlength attribute using one line of jquery:

$('[data-val-length-max]').each(function () { $(this).attr("maxlength", $(this).attr('data-val-length-max')); });

The maxlength attribute prevents the user from entering more characters than are allowed. This one line does it for all inputs that have this attribute setup in a view.