Archive for November, 2011

Centerim, Irssi, Alpine on Screen

November 27, 2011

I’ve recently acquired access to my own shell from anapnea.net

This allows me to carry out development, testing, and any on-line activity anonymously.
All via SSH.

One of the tasks I needed to do,
was to set up my date/time to my local time zone.
Rather than set the system wide time,
because there are many users on this machine,
I needed to set the time zone on a per user basis.

The behaviour of your interactive shell is defined by your ~/.bashrc and ~/.bash_profile files.
Edit one of these files and append or alter the TZ as follows:

 vim /home/myuser/.bashrc

where myuser is just that, my user name.

Append the following:

export TZ="/usr/share/zoneinfo/yourcountry"

Where yourcountry is one of the country files in /usr/share/zoneinfo/

Screen

Screen is a Linux shell session manager.
It’s great, because you can leave multiple sessions running and switch between them,
all in a single console.
Then you can just detatch from screen, leaving your programmes running on it.
Terminate your SSH session, and re-connect from another machine,
re-attach to screen, and carry on working where you left off,
with your programmes all still running.

This is a quick run down on what it is and how to use it.

Create a new screen session:

screen

List screens:

screen -ls

Detaching:

Ctrl-a, d

To re-attach to a screen:

screen -r

Or

screen -raAd

Reattach (-r), do some sizing stuff (a,A), and detach (d) before reattaching if necessary.
If your screen session is attached elsewhere, using -raAd will detach that session, and reattach it here.

Cycle through each screen:

Ctrl-a n
Ctrl-a p

You can kill a screen by typing exit.

Terminate a screen:

screen -X -S ID kill

Where ID is the id of the screen you want to terminate.

Useful links
http://quadpoint.org/articles/irssi
Full list of commands and their usage http://www.math.utah.edu/docs/info/screen_5.html

CenterIM

CenterIM is a Linux command line instant messenger client.
Getting started
with CenterIM

Setting up GTalk in CenterIM:
Assuming you have centerim installed.
cd into your .centerim directory and edit the config file.

vim config

Add the following to the file:

jab_nick MyUser@gmail.com
jab_pass
jab_server talk.google.com:5223
jab_osinfo 1
jab_prio 4
jab_ssl 1

Enter the command mode by pressing the Esc key.

:wq

This will write and quit.
run centerim:

centerim

or better, run it in screen…

screen centerim

Press F4 for the general menu.
Select Accounts..

Under the Jab protocol, you will now see the connection details reflected.

Irssi

Irssi is a Linux command line IRC client.
When I use Irssi,
these are the links I use most commonly.
http://pthree.org/2010/02/02/irssis-channel-network-server-and-connect-what-it-means/
http://quadpoint.org/articles/irssi
http://linuxreviews.org/software/irc/irssi/#toc6
IRC command reference http://www.ircle.com/reference/commands.shtml
and full help for commands http://static.quadpoint.org/irssi-docs/help-full.html
For the beginner
The Full manual
Splitting Windows

I’ll probably end up adding more to this.

Alpine

Alpine is a Linux command line mail client.
Here
is an accurate guide on how to setup your GMail accounts using IMAP in alpine.
I used this for my first account setup.

When you need to setup multiple accounts,
you have to do a little bit more configuration.
I followed this.

Then create a Role.

I run all my external shell apps on screen.
So I run the following command…

screen alpine

You should be presented with the Main Menu.

Press S (Setup), L (collectionLists)

Press A (Add Cltn)
Add a Nickname that makes sense to you to reference your account by,
and the Server, as you did in the initial account setup,
save as you did in the initial setup.
Your Setup Collection List should look similar to the following.

From the Main Menu, press S (Setup), C (Config).
Scroll down until you find “Enable Incoming Folders Collection” and turn the radio button on.

Press E (Exit), and Y (Yes) to the Commit changes prompt.
You should be back on the Main Menu now.
Now you need to add a role for each account you’ve just setup.
Press S (Setup), R (Rules).

Then choose R (Roles).
Press A (Add).
Setup each role like the following.

Press E (Exit Setup), and Y to the save prompt.

Again in the S (Setup), C (Config).
Some of the settings that need to be turned on are:

  • alternate-compose-menu is optional
  • confirm-role-even-for-default

I set the following fields, so they show up in new messages you are composing.

Create a new message

There are a few ways you can compose a new email message.
This depends on where you start the process from.
If you’re in one of your mail folders,
you can press C (Compose).
You’ll be asked which role you would like to use to compose the message.
These are the role’s you set up before,
each one applies to one of your email accounts.
Once you choose one,
you’ll see a template with the fields you set up before.
Fill out the fields.
When your done composing your message,
press Ctrl-X to send.

Move a message from folder to another folder

  1. Select the message you want to move.
  2. Press the S (Save) key.
  3. If you have multiple email accounts, press Ctrl+N (Next Collection) or Ctrl+P (Prev Collection) to cycle through your accounts.
  4. Press Ctrl+T (To Folders).
    You will be presented with the collection of your email folders for your account.
  5. Select Which folder you want to put your message into.
  6. Press enter, unless you have to move the message down another level.
  7. If this is the case, press ‘/’ (the slash key).
  8. Then either the Tab key twice, or Ctrl+X (List matches).
    This will show you the next layer of folders to choose from.
    Either select the folder you want to move your message to and press Enter,
    or to go to another level, repeat steps 5 to 8.
  9. Once you’ve located the target folder (and selected it) to save (move) your message to,
    you’ll be provided with the path that you are about to save to.
  10. Press Enter. The message [Saving DONE] will be displayed.
    You message is now moved.
    When you return to the source folder,
    you will be asked if you want the message that is there deleted,
    so that you have moved, not copied the message.
    You have the option to either copy or move.

Multi selecting (Selecting multiple emails)

  1. Select the email and press the ‘;’ (semicolon) key.
  2. You will be prompted chose a selection criteria.
    I selected C (just select current message).
    When you do this, zoom will come into effect.
    So you will only see the currently selected messages.
  3. To un-zoom, so you can see all messages from the folder you were in, just press Z
    You will now see an ‘X’ next to the messages you have multi selected.
  4. Press the Z key again to zoom to the selected messages.
  5. Press A (Apply), then select the command you want to apply and that’s it.
  1. Select the link.
  2. Press Enter.
  3. Right click the link and select “Open link”.

Enable Spell Check in Alpine

First check that it’s not enabled

When composing a message, press  Ctrl+T
If you don’t get spell check, you’ll need to do the following.

Make sure you have aspell installed

On a debian based system, you can run

dpkg-query -l '*aspell*'

This will show you the aspell components installed

Or more precisely, just search for aspell

dpkg -l aspell

Once you find it, you can run

dpkg-query -W -f='${Status} ${Version}\n' aspell

This will tell you whether or not it’s installed.
If it’s not, you’ll need to install it:

sudo apt-get install aspell

From the Main menu in Alpine, S (Setup), C (Config).
Look for “spell”.
You can press ‘W’ to search and type in “spell” without the quotes.
Press Enter.
The first option you will find should be “Spell Check Before Sending”.
You can turn this on if you like.
Press ‘W’ again, accept the default, press Enter.
You should now see the option “Speller”.
Press Enter, and type in

aspell -c

Press Enter to accept.
Press ‘E’ to exit config.
Press ‘Y’ to the Commit changes prompt.

If you run the following at the command prompt

aspell

You should get a little information about what the -c switch does.

Scoping & Hoisting in JavaScript

November 14, 2011

Scoping

JavaScript scoping is different to classical languages, and can take some getting used to for programmers used to languages such as C, C++, C#, Java.
Classical languages like the before mentioned have block scope.
JavaScript has function scope.

In the following example “5” will be alerted.

var foo = 1;
function bar() {
   if (!foo) {
      var foo = 5;
   }
   alert(foo);
}
bar();


In the following example “1” will be alerted.

var a = 1;
function b() {
   a = 10;
   return;
   function a() {}
}
b();
alert(a);


In the following example Firebug will show 1, 2, 2.

var x = 1;
console.log(x); // 1
if (true) {
   var x = 2;
   console.log(x); // 2
}
console.log(x); // 2


In JavaScript, blocks such as if statements, do not create new scope. Only functions create new scope.

There is a workaround though 😉
JavaScript has Closure.
If you need to create a temporary scope within a function, do the following.

function foo() {
   var x = 1;
   if (x) {
      (function () {
         var x = 2;
         // some other code
      }());
   }
// x is still 1.
}

Line 3: begins a closure
Line 6: the closure invokes itself with ()

I discuss closure in depth in a later post.

Hoisting

Terminoligy

As far as I know…
function declaration or function statement
are the same thing.
function expression or variable declaration with function assignment
are the same thing.


A function statement looks like the following:

function foo( ) {}


A function expression looks like the following:

var foo = function foo( ) {};


A function expression must not start with the word “function”.

//anonymous function expression
var a = function () {
   return 3;
};

//named function expression
var a = function bar() {
   return 3;
};

//self invoking named function expression.
(function sayHello() {
   alert('hello!');
})();

//self invoking anonymous function expression.
(function ( ) {
   var hidden_variable;
   // This function can have some impact on
   // the environment, but introduces no new
   // global variables.
}() );


In JavaScript, a name enters a scope in one of four basic ways:

  1. Language-defined: All scopes are, by default, given the names this and arguments.
  2. Formal parameters: Functions can have named formal parameters, which are scoped to the body of that function.
  3. Function declarations: These are of the form function foo() {}.
  4. Variable declarations: These take the form var foo;.

Function declarations and variable declarations are always hoisted
invisibly to the top of their containing scope by the JavaScript interpreter.
Function parameters and language-defined names are, obviously, already there. This means that code like this:

function foo() {
   bar();
   var x = 1;
}

Is actually interpreted like this:

function foo() {
   var x;
   bar();
   x = 1;
}


It turns out that it doesn’t matter whether the line that contains the declaration would ever be executed.
The following two functions are equivalent:

function foo() {
   if (false) {
      var x = 1;
   }
   return;
   var y = 1;
}
function foo() {
   var x, y;
   if (false) {
      x = 1;
   }
   return;
   y = 1;
}

The assignment portion of the declaration is not hoisted.
Only the identifier is hoisted.
This is not the case with function declarations, where the entire function body will be hoisted as well,
but remember that there are two normal ways to declare functions. Consider the following JavaScript:

function test() {
   foo(); // TypeError 'foo is not a function'
   bar(); // 'this will run!'
   var foo = function () { // function expression assigned to local variable 'foo'
      alert('this won't run!');
   }
   function bar() { // function declaration, given the name 'bar'
      alert('this will run!');
   }
}
test();

In this case, only the function declaration has its body hoisted to the top. The name ‘foo’ is hoisted, but the body is left behind, to be assigned during execution.

Including named function expressions added to the local object

//'use strict';

var container;

function Container() {

   var that = this;
   var descender = 3;
   var targetMin = 0;
   var ascender = 0;
   var targetMax = 3;    

   this.inc = function () {

      if (ascender < targetMax) {
         ascender += 1;
         console.log('ascender incremented: now equals ' + ascender);
         return that;
      } else {
         that.inc = function () {
            console.log('inc now modified to return ' + targetMax);
         };
         that.inc();
         return that;
      }
   };

   alert(dec); // Uncaught ReferenceError: dec is not defined. we're actually looking for the global objects dec property which doesn't exist.
   alert(this.dec); // Prints 'undefined' because this.dec is hoisted and declared, but of course not yet defined.
   // If this.dec was not hoisted, we would get the same 'Uncaught ReferenceError: this.dec is not defined'.

   this.dec = function () {

      if (descender > targetMin) {
         descender -= 1;
         console.log('descender decremented: now equals ' + descender);
         return that;
      } else {
         that.dec = function () {
            console.log('dec now modified to return ' + targetMin);
         };
         that.inc();
         return that;
      }
   };
}

container = new Container();
container.inc().inc().inc().inc();
console.log(container.inc);
container.dec().dec().dec().dec();
console.log(container.dec);

Out of interest, the output looks like the following:

modify routine on the fly

Name Resolution Order

The most important special case to keep in mind is name resolution order. Remember that there are four ways for names to enter a given scope. The order I listed them above is the order they are resolved in. In general, if a name has already been defined, it is never overridden by another property of the same name. This means that a function declaration takes priority over a variable declaration. This does not mean that an assignment to that name will not work, just that the declaration portion will be ignored. There are a few exceptions:

  • The built-in name arguments behaves oddly. It seems to be declared following the formal parameters, but before function declarations. This means that a formal parameter with the name arguments will take precedence over the built-in, even if it is undefined. This is a bad feature. Don’t use the name arguments as a formal parameter.
  • Trying to use the name this as an identifier anywhere will cause a Syntax Error. This is a good feature.
  • If multiple formal parameters have the same name, the one occurring latest in the list will take precedence, even if it is undefined.

Now that you understand scoping and hoisting, what does that mean for coding in JavaScript?
The most important thing is to always declare your variables with var statements.
Declare your variables at the top of the scope (as already mentioned JavaScript only has function scope). See the Variable Declarations section.
If you force yourself to do this, you will never have hoisting-related confusion.
However, doing this can make it hard to keep track of which variables have actually been declared in the current scope.
I generally like to follow these coding standards with JavaScript.

function foo(a, b, c) {
   var x = 1;
   var bar;
   var baz = 'something';
   // other non hoistable code here
}