Stop Wasting Time Logging Into GitHub on Command Line Every Time You Push: Just Set Up SSH Keys

1. Does GitHub always ask you for your password? There is a fix, read on :)

If you recently started using Git & Github in your workflow it is likely you are sick and tired of constantly having to type in your username and password every single time you want to push some chnages! Well that ends today as in this blog post I will show you how to tell Github to trust your laptop and just let you get on with coding without any fuss of logging in all the time.

In order for this to work we will use something called SSH keys.

2. What are SSH keys?

SSH keys are a means of identifyng yourself to a server without having to type in your username and password every time. It can be though of as a passwordless login. Instead of a user name and password the a pair of keys is used that is exchanged between your laptop and the server. They keys live on your laptop and on the other side, this way every time you talk to that server it will realise that you are already knowkn to it and who you are.

3. Do you already have SSH keys?

Before we make a new key, lets check if you have lying around already.

Windows

In command promt type in:

1
cd %userprofile%/.ssh

Now lets see if there is a key in there:

1
dir id_*

If you see and error something like “No such file or directory” then you don’t have a key and need to make one. Next section describes hwo to do this.

Mac & Linux

Open your preffered terminal and run the command below:

1
ls -al ~/.ssh

This will list all the files currently present in the ~/.ssh directory, which is a special directory where all keys are stored by default. The filenames to look out for are:

  1. id_rsa.pub
  2. id_rsa
  3. id_dsa.pub
  4. id_ecdsa.pub
  5. id_ed25519.pub

Check the content of the file that looks similar to the example above by using the cat command:

1
cat ~/.ssh/id_rsa.pub

There will be a whole lot ot stuff in that file including your email.

If you did not find anything in there, not to worry we will make a new SHH key!

4. Generate a new SSH key.

So if you found no keys form steps before then we should make one. Lets go back to the terminal and run the command that will generate us a new key:

1
ssh-keygen -t rsa -C "[email protected]"
  1. Just press Enter when prompted for a filename
  2. Create and enter a passphrase as requested.
  3. Tada you now have a shiny new key ready to be used.

Note that the ssh-keygen command is only available if you have already installed Git (for Windows that would be Git with Git Bash).

5. Adding a new SSH key to your GitHub account.

We now need to share the new key with Github in order to enjoy passwordless login when pushing code:

  1. Log in to your GitHub account
  2. Click on your profile photo (in the top right corner) → “Settings”
  3. In the sidebar click on “SSH and GPG keys” → “New SSH Key”
  4. Give it a title/name (perhaps this is the key for you work laptop)
  5. You now need to copy and paste the entirety of the key into here. So all the text your saw with your email that was generated during the previous step all of that is a key. If you had a key already, simply open the file and copy paste the entire contents into here.
  6. Save!

5. Try it out!

You can now go back to your project and try pushing some code, you should no longer be prompted for the password and username every time.

🔥 If you enjoyed this post and are keen to learn more about Git or use it in a practical project check out the courses I am working on to help a new developers get to grips with common workflows and best practices. Take a peek at the Introduction to Git & Github online course.

Frontend Automation With Grunt

1. What is Grunt?

Grunt is a JavaScript task runner. Grunt lets you automate tasks like HTML minification, copying files, compiling CSS, deploying to AWS etc.

2. Download Node.js

Grunt and Grunt plugins are installed and managed via npm the Node.js package manager. First of all if you will need to download Node.js (npm will be installed with it).

3. Basic Command Line Commands

If you have not used command line terminal before you here are some basic commands:

ls

Description: Lists the names of the files in the working directory. For more complete information use ls –alF

cd directoryname

Description: Changes the working directory to the one you named.

cd ..

Description: Brings you up one directory level.

cd

Description: Returns you to your home directory.

pwd

Description: Displays the pathname of the current directory.

mkdir newdirectoryname

Description: Makes a new directory

4. Install Grunt

  1. Open your preferred terminal or install iTerm.
  2. Install Grunt globally: instructions below will install grunt client globally on your machine, if you already have Grunt installed skip this step. For a more detailed explanation see the official documentation.
  3. Install Grunt locally: Now we will install Grunt locally specifically for this project. Go to your project folder. Replace the path after cd with the path to your folder:
1
cd Documents/workshop/

In the terminal type out the below command to get to the project folder (if you have saved the workshop folder elsewhere adjust the path):

1
npm install grunt –save-dev

5. Configure

To configure the project, within your project folder type npm init in the terminal and follow the instructions:

6. Grunt AWS Plugin

We will now install Grunt AWS Plugin. Grunt uses different plugins to perform certain tasks, in order to deploy to Amazon S3 we will use the grunt-aws-s3 plugin.

In your project folder we can install this using the command below:

1
npm install grunt-aws-s3 –save-dev

We now have the plugin installed and we can configure grunt to use this task to deploy our project without having to manually upload the files every time.

In order for us to use this plugin and deploy to S3 in the command line we need to create a file called s3settings.json, here we will keep all the login details and bucket information. This file MUST be kept secret, do not commit it to github or any other version control system. It should be excluded in .gitignorefile if you are using git. It is important to take care as if these details are made public your account may be accessed and used by someone else, leaving you with a bill to pay:

The key and secret are available in the user credentials file you downloaded when creating an IAM user. Bucket must be exactly what you called the bucket on Amazon S3 and the same for region.

The second file we need to create is Gruntfile.js this is a default file Grunt will look for locally within the project folder. Here is where we configure the tasks.

Using your text editor or command line, create a new file within the workshop folder called Gruntfile.js, the content of it should be the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-aws-s3');

grunt.initConfig({
  pkg: grunt.file.readJSON('package.json'),
  s3settings: grunt.file.readJSON('s3settings.json'),
      aws_s3: {
          options: {
              accessKeyId: '<%= s3settings.key %>',
              secretAccessKey: '<%= s3settings.secret %>',
              region: '<%= s3settings.region %>',
              uploadConcurrency: 5,
              downloadConcurrency: 5
      },
      live: {
          options: {
              bucket: '<%= s3settings.bucket %>',
              differential: true //Only uploads the files that have changed
          },
          files: [
              {expand: true, cwd: 'deploy/', src: ['**'], dest: ''},
              ]
          },
      });
  grunt.registerTask('deploy', ['aws_s3:live']);
};

Full code to copy is here.

Here we have configured the plugin to upload to Amazon S3 all files in the folder deploy, so we would now have to create this folder within the project and copy any files we want uploaded.

We have also created a task called deploy which can be run in command line within the project folder to upload all files within deploy folder to Amazon S3, to the bucket specified in the s3settings.json file.

7. Use Grunt to deploy to S3

Go to the project folder in the terminal. You can now run the deploy command by typing:

1
grunt deploy

And we are done!

Part 4: Create New IAM Users and Permissions in AWS

This is Part 4 of a tutorial post Create a Simple Website in CSS/HTML and deploy to Amazon S3.

Note: Here you can look over Part 1: HTML, Part 2: CSS and Part 3: Deploy to AWS of this tutorial.

1. Create a new User

  1. Sign in to the AWS Amazon console
  2. Click on Identity & Access Management
  3. Click on User on the left hand-side menu
  4. Click Create New User
  5. Enter username testuser
  6. Click Create
  7. Download the credentials. These will include User Name, Access Key Id, Secret Access Key. Keep these secret as they are tied to your account and can be used for malicious purposes if not kept safely. Remember that your account is tied to your credit card.

2. Set user permissions

  1. You should now see your user created in the user dashboard.
  2. Click your newly created user testuser
  3. Click on Permissions → Attach Policy

  1. Select AmazonS3FullAccess → Attach Policy:
  2. Done!

Part 3: Create a Bucket and Deploy a Website to Amazon S3

This is Part 3 of a tutorial post Create a Simple Website in CSS/HTML and deploy to Amazon S3, it is aimed at a completele beginner.

Note: Here you can look over Part 1: HTML and Part 2: CSS of this tutorial.

In this tutorial we will cover:

  1. Create a free account on Amazon S3
  2. Creating a bucket on Amazon S3
  3. Uploading your website to Amazon S3

1. Create a free account on Amazon S3

Amazon has a free tier which will be enough for most small websites.

1. Go to Amazon S3

2. Click on “Try Amazon S3 for Free”:

3. Enter your email address or phone number. Then select “I am New User” and click “Sign in using our secure server”:

4. Fill out required info:

5. Fill out credit card info

6. Confirm your identity via a call:

2. Creating a bucket on Amazon S3

1. Sign in to the Amazon console

2. Click on S3

3. Click “Create a new bucket”

4. Click “Create a new bucket”

3. Fill out the bucket name (example yourname.com)

3. Uploading your website to Amazon S3

1. Click into the bucket name you have just created

2. Select “Actions” → “Upload”

3. Click “Set Details” → “Set permissions”

4. Tick “Make everything public”

5. Click “Start Upload”

6. Select the file index.html and click “Properties”

7. Click on the link

8. Thats it! Your website is now live and accessible online via this link at any time.

If you would like to learn how to automate this deploy and make it easier for continuous development watch out for the next blog post where I will talk about using Grunt.

Part 2: Create a Simple Website in CSS/HTML and Deploy to Amazon S3

This is Part 2 of a tutorial post Create a Simple Website in CSS/HTML and deploy to Amazon S3, it is aimed at a completele beginner.

In this tutorial we will briefly cover:

  1. What is CSS?
  2. CSS Basics
  3. Create a Stylesheet
  4. Link HTML and CSS
  5. Basic CSS Properties
  6. CSS Exercises

1. What is CSS?

Cascading Style Sheets (CSS) is a style sheet language used for describing what the html elements should “look like”. It is used to describe whether an html element should be of certain height, width, if the text should be bold, text colour etc. We will try this shortly.

2. CSS Basics

This is a rule:

1
2
3
h1 {
  color: red;
}
  • This rule starts with h1, which is a selector.
  • The part inside the curly braces is the declaration.
  • color is a property.
  • red is a value.
  • color: red; is a property-value pair.
  • The ; after the property-value pair separates it from other property-value pairs in the same rule, for example:
1
2
3
4
h1 {
  color: red;
  text-align: center;
}

We will refer to those definitions throughout this class.

3. CSS Basics

When the browser reads the CSS file, it finds each selector and works out if it applies to any elements in the HTML. If it does, it uses the properties within the matching rule.

A style sheet consists of a list of rules. Each rule or rule-set consists of one or more selectors. Selectors allow you to SELECT all elements that match:

  • a certain tag name e.g. <h1>
  • a certain element inside another element e.g. all <li> within a <ul>

4. Create a Stylesheet

  1. Install Sublime or use your preferred text editor
  2. Create a new file in the same folder as the index.html and name it style.css
  3. Type out the code below and save in in your style.css file:
1
2
3
4
h1 {
  color: red;
  text-align: center;
}

Here you created a rule that says: All h1 elements have the following properties: text alignment is center & the text colour is red.

Exercise: Now use the example above to do the same for <p>. Clue: create a new rule and replace h1 with p.

5. Link HTML and CSS

Now that we have our first stylesheet, we can tell the html document index.html to use the stylesheet style.css so that the browser knows what the page should look like.

  1. Add the following line in your index.html file underneath the <title> tag:
    1
    
    <link rel="stylesheet" href="style.css">
    
  2. Reload the file in the browser or open it again: Open your web browser, then press Ctrl + O (Windows) or Cmd + O (Mac) to open the file we have just updated. You should see “Hello World” and the text you added in the paragraph with the added style.

6. Basic CSS Properties

color

  • Description: this is the text colour, this is used to style elements that have text e.g. h1, p, h2.
  • Example: color: white;
  • More Info: MDN: color

background-color

  • Description: this is used to define the background color of a particular element.
  • Example: background-color: blue;
  • More Info: MDN: background-color

font-size

  • Description: this is used to set the size of a font in px or other units.
  • Example: font-size: 16px;
  • More Info: CSS font size units

background-image

  • Description: this is used to set an image as a background of an element.
  • Example: background-image: url(http://examplelink.com);
  • More Info: CSS-tricks: background-image

text-align

padding

  • Description: sets the padding of the element. See the Box Model picture below for an explanation of what padding is and how it will affect the look of the element.
  • Example: padding: 10px 10px 10px 10px; or padding: 10px;
  • More Info: MDN: padding

margin

  • Description: this is used to set the margin of the element. See the Box Model picture below for an explanation of what padding is and how it will affect the look of the element.
  • Example: margin: 10px;
  • More Info: MDN: margin
6.1 CSS Box Model

In a document, each element is represented as a rectangular box. This model describes the content of the space taken by an element. Each box has four edges:

  1. margin edge
  2. border edge
  3. padding edge
  4. content edge (in blue)

You can read more about CSS Box Model here.

5. CSS Exercises

We can add more to the style.css at this stage or later, here is a list of CSS properties available.

  1. Try out all the properties from the Basic CSS Properties section and see what they all do.
  2. You can also style the <body> element, try setting a background image on the element and see what that does.
  3. Make an image to also be a link, ie make the image clickable that will take you to a different website. Tip: you can add some elements inside of other elements,try and add an img within the a.
  4. Align left or center all the text on the page.

Part 1: Create a Simple Website in CSS/HTML and Deploy to Amazon S3

This is Part 1 of a tutorial post Create a Simple Website in CSS/HTML and deploy to Amazon S3, it is aimed at a completele beginner.

In this tutorial I will briefly cover:

  1. What is HTML?
  2. HTML Basics
  3. Create a Simple HTML Page
  4. What is HTML5 and how is it different?
  5. HTML Exercisesb

1. What is HTML?

HTML - HyperText Markup Language is the standard language used to create web pages. Web browsers can read HTML files and render them into visible web pages. HTML documents are described by HTML tags, these are enclosed in angular brackets <>. HTML tags can be considered to be “keywords” that the browser can understand and render/draw in the browser appropriately when viewing the page. Each browser has default ways of interpreting each element, these can later be “styled” to look how you prefer with the help of CSS, which will be explained a little further on.

2. HTML Basics

We will create a very basic HTML page that will load and simply display “Hello World”. It will look like this:

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html>
    <head>
        <title>Page title goes here</title>
    </head>
    <body>
      <h1>Hello World</h1>
      <p>This is my first website!</p>
    </body>
</html>
  • The DOCTYPE is a declaration and tells the browser which ‘language’ we are talking in so it knows how to render it.
  • The text between <html> and </html> describes an HTML document
  • The text between <head> and </head> provides information about the document
  • The text between <title> and </title> provides a title for the document
  • The text between <body> and </body> describes the visible page content
  • The text between <h1> and </h1> describes a heading
  • The text between <p> and </p> describes a paragraph

3. Create a Simple HTML Page

  1. Install Sublime or use your preferred text editor
  2. Create a new folder in your Documents folder for this workshop, let’s call it website.
  3. Now open the text editor and save an empty file called index.html, you can press Cmd + S (Mac) or Ctrl + S (WIndows)
    • index.html is a special name and this is a file that the server will look for by default when a certain url is requested (link e.g. http://website.com).
    • Each simple website is basically a “directory” of files, the index.html is the first file the web browser will access and from here you can specify how to reach other files via writing hyperlinks.
    • The default file can be configured to be called something else if required, but for the purpose of this workshop we will only concentrate on simple defaults.
  4. Type out the code below:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    <!DOCTYPE html>
    <html>
        <head>
            <title>Page title goes here</title>
        </head>
        <body>
          <h1>Hello World</h1>
          <p>This is my first website!</p>
        </body>
    </html>
    
  5. Open your web browser, then press Ctrl + O (Windows) or Cmd + O (Mac) to open the file we have just created. You should see “Hello World” and the text you added as the paragraph, something like this:

4. What is HTML5 and how is it different?

HTML5 is simply a newer version that is supported by most modern browsers. HTML5 introduced some more awesome elements/tags we can use: such as <canvas>, <video>, <audio>, <footer> and many more to bring the HTML language more in-line with modern times.

5. HTML Exercises

We can add more to the page at this stage or later, here is a list of html and new html5 tags you can use.

  1. Add an image <img>:
    • Type out the following and modify the src to point to an image you like:
      1
      
       <img src="https://www.example.com/image.png " alt="Image description">
      
    • width="100" and height="90" are optional, play around with the numbers.
    • Read more about image <img> tag and it’s use.
  2. Add a link <a> to your favourite website:
    • Type out the following and modify it to link to point your favourite website:
      1
      
       <a href="https://www.example.com ">Link Text</a>
      
    • Read more about link <a> tag and it’s use.
  3. Add a footer <footer>. These usually sit at the bottom of the page, but sometimes have to be styled to stay at the bottom if there is not enough content to fill the page:
  4. Add a comment, which says “This is my first website!”:
    • Have a look at the example below and modify it as needed:
      1
      
       <!– Comment text, this will not be visible on the page –>
      
      * Read more about comments
  5. Add an unordered list of 3 things you love (use previous examples to get the format right):
    • Unordered list is started using the tag <ul> and closed using </ul>
    • Within the list declaration mentioned above you can add in list items, these are defined by: <li> </li>
    • You can have as many list items in the unordered list as you want
    • Within each item you can add other elements, such as: paragraph, link, images, another list.
    • Play around with this one, it is very useful especially for menus
    • Read more about unordered list ul tag and it’s use

Further reading and things to try:

Technical Code Interview Prep Notes

Data Structures and Algorithms

Question 1: How do you reverse a linked list using recursion (Java)?

I found the answer on this stackoverflow post “Reversing a linked list in Java, recursively”. This can be solved answering the following questions:

  1. What is the reverse of null (the empty list)? null.
  2. What is the reverse of a one element list? the element.
  3. What is the reverse of an n element list? the reverse of the second element on followed by the first element.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 public ListNode Reverse(ListNode list) {
    // What is the reverse of null (the empty list)? null.
    if (list == null) return null;

    // What is the reverse of a one element list? the element.
    if (list.next == null) return list;

    // What is the reverse of an n element list? the reverse of the second element on followed by the first element.
    // so we grab the second element (which will be the last after we reverse it)
    ListNode secondElem = list.next;

    // bug fix - need to unlink list from the rest or you will get a cycle
    list.next = null;

    // then we reverse everything from the second element on
    ListNode reverseRest = Reverse(secondElem);

    // then we join the two lists
    secondElem.Next = list;

    return reverseRest;
}

Question 2: How do you find a length of a linked list?

Traverse through all the elements until you find the last node which points to null.

Question 3: How do you find the middle of a linked list using only one pass?

  1. Maintain two pointers as you traverse through the linked list.
  2. Increment Pointer 1 on every node and only increment Pointer 2 on every 2nd node.
  3. When you reach the end of the list, Pointer 2 will be pointing to the middle of the list.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class LinkedListTest {
    public static void main(String args[]) {
    // Creating LinkedList with 4 elements including head
    LinkedList linkedList = new LinkedList();
    LinkedList.Node head = linkedList.head();
    linkedList.add( new LinkedList.Node("1"));
    linkedList.add( new LinkedList.Node("2"));
    linkedList.add( new LinkedList.Node("3"));

    // Finding middle element of LinkedList in single pass
    LinkedList.Node current = head;
    int length = 0;
    LinkedList.Node middle = head;

    while(current.next() != null){
      length++;
      if(length % 2 == 0){
          middle = middle.next();
      }
      current = current.next();
    }

    if(length % 2 == 1){
      middle = middle.next();
    }

    System.out.println("Length of LinkedList: " + length);
    System.out.println("Middle element of LinkedList : " + middle);

    }
}

Read more here.

Question 4: Does a given linked list have a loop?

This is solved similarly to the question above “Question 3: How do you find the middle of a linked list using only one pass?”:

  1. Maintain 2 pointers as you traverse through the list.
  2. Increment Pointer 1 on every node and only increment Pointer 2 on every 2nd node.
  3. If Pointer 1 and Pointer 2 point to the same node, the list has a loop.

Question 5: An integer array has numbers from 1 to 100, there is a duplicate in the array. Find the duplicate.

  1. Add all the numbers stored in the array.
  2. Find the expected sum of all the numbers if there were no duplicates. The sum is represented by a formula n(n+1)/2.
  3. Subtract the actual sum from the expected sum. The answer is the dulicate number.
  4. This works if there is 1 duplicate in the array, for multiple duplicates use a Hash Map, where the number is the key and the the occurence is the value. Any values larger than 1 will reveal the duplicates.

Question 6: What is the difference between a Stack vs a Queue?

A Stack is LIFO (Last In First Out) structure and a Queue is a FIFO (First In First Out) structure.

Question 7: What is a Binary Search Tree?

They are also sometimes called ordered or sorted binary trees, are a class of data structures used to implement lookup tables and dynamic sets. They store data items, known as keys, and allow fast insertion and deletion of such keys, as well as checking whether a key is present in a tree. In a binary search tree:

  1. Every left node is smaller than the root element.
  2. Every right node is larger than the root element.
  3. There are no duplicates in the binary search tree.

Question 8: How would you sort and array using a Bubble sort?

Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. Worst Case performance is O(n^2), best case is O(n).

  1. Start comparing first and second element array[0] and array[1].
  2. If array[0] > array[1] then swap numbers e.g. array[0] = array[1] and array[1] = array[0].
  3. Repeat with the next two element, array[1] and array[2] and so on until you reach the end of the list
  4. This is referred as one pass and at the end of first pass largest number is at last.
  5. Repeat this comparison again starting from array[0] but this time going till second last pair only array[n - 1].

In a Bubble sort we need n - 1 iteration to sort n elements at end of first iteration largest number is sorted and subsequently numbers smaller than that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var array =[13,1,24,56,23,4,3,2,7,9,10,11];

console.log("Sorted Array: " + bubbleSort(array));

function bubbleSort(a){
  var swapped = true;
  for(var i = 0; i < a.length-1; i ++){
    swapped = false;
    for(var j = 0; j < a.length-1; j ++){
      console.log(i +" " + j);
      if (a[j] > a[j+1]){
        var temp = a[j];
        a[j] = a[j+1];
        a[j+1] = temp;
        swapped = true;
      }
    }
    if(swapped === false) return a; // if no swaps have been made, the array is sorted. No need to keep looping.
    }
  return a;
}

Question 9: How would you check if a number is a palindrome?

Using a modulo we can determine if a number is a palindrome:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
var number = 2332; // example number
var orig_num = number; // keep a copy of the original number
var new_num = number; // this number will change as we try to reverse the number without using strings
var check_num = 0;
var check_is_palindrome =[]; // storing all the individual numbers here  as we get them in reverse order.
// console.log("Number to check: " + number);

function isPalindrome(number) {

    if (number === 0) return true;

    var num_of_passes = 0;

    while (new_num > 0){
        num_of_passes ++;
        remainder = number % 10;
        //console.log("Remainder: " + remainder);
        new_num = (number - remainder)/10;
        //console.log("New number: "+ new_num);
        number = new_num;
        check_is_palindrome.push(remainder);
        //console.log(check_is_palindrome);
        //console.log("Num of passes: " + num_of_passes)
    }

    var final_check_num = 0; // this is to save our result after reversing the number

    for (var i = 0; i < check_is_palindrome.length; i++){
        final_check_num += check_is_palindrome[i] * Math.pow(10,num_of_passes - 1);
        num_of_passes --;
        //console.log("Final_check_num: " + final_check_num);
      }

    return orig_num === final_check_num;
}

console.log("Is number " + number " a palindrome? " + isPalindrome(number));

Question 10: Describe a Selection Sort?

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n^2) time complexity, making it inefficient on large lists. It performs worse than the similar insertion sort.

  1. Divide the list into two parts: the sublist of items already sorted and the sublist of items left to be sorted. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list.
  2. Find the smallest or largest element in the unsorted sublist.
  3. Exchange places with the leftmost unsorted item.
  4. Repeat 2 & 3 until no unsorted items left.

Question 11: Describe a Shell Sort?

The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared. Starting with far apart elements can move some out-of-place elements into position faster than a simple nearest neighbor exchange. It is similar to the Insertion sort that allows the exchange of items that are far apart. Worst case performance is O(n^2), best case is O(n log2 n). Picking the correct gaps is difficult, they should be reducing until the gap is 1.

Question 12: Describe an Insertion Sort?

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.

  1. For each item, remove form unsorted and place in the correct place in teh sorted list or sub-list
  2. Move up all larger elements if required to place the item in the correct place.

Question 13: Describe a Quick Sort?

This is an efficient sorting algorithm. The steps are:

  1. Pick an element, called a pivot, from the array.
  2. Reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way).
  3. After this partitioning, the pivot is in its final position. This is called the partition operation.
  4. Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.
  5. The last element is ussually chosen as the pivot, but this will yeild a wort case complexity on an already sorted array or on an array of identical elements.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var array = [13,1,24,56,23,4,3,2,7,9,10,11];

console.log("Sorted Array: " + quickSort(array));

function quickSort(a) {
  var answer = [];
  if(a.length === 1) answer=a;
  if (a.length > 1){
    console.log("quicksort " + a);
    var pivot = a[a.length-1];
    //console.log(a.length);
    var left_a = [];
    var right_a = [pivot];
    for(var i = 0; i < a.length; i++){
      //console.log("Comparing " + pivot " and a[i]= " + a[i]);
      if(pivot > a[i]){
        left_a.push(a[i]);
      }
      if(a[i] > pivot){
        right_a.push(a[i]);
      }
      console.log(left_a, right_a);
    }
    answer.push(quickSort(left_a));
    answer.push(quickSort(right_a));
  }
  return answer;

Question 14: Describe a Merge Sort?

A merge sort is an O(n log n) comparison-based sorting algorithm. Mergesort is a divide and conquer algorithm that was invented by John von Neumann in 1945. Conceptually, a merge sort works as follows:

  1. Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted).
  2. Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. This will be the sorted list.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function merge_sort(list m)
    // Base case. A list of zero or one elements is sorted, by definition.
    if length(m) <= 1
        return m

    // Recursive case. Divide the list into equal-sized sublists.
    var list left, right
    var integer middle = length(m) / 2
    for each x in m before middle
         add x to left
    for each x in m after or equal middle
         add x to right

    // Recursively sort both sublists
    left = merge_sort(left)
    right = merge_sort(right)
    // Then merge the now-sorted sublists.
    return merge(left, right)

function merge(left, right)
    var list result
    while notempty(left) and notempty(right)
        if first(left) <= first(right)
            append first(left) to result
            left = rest(left)
        else
            append first(right) to result
            right = rest(right)
    // either left or right may have elements left
    while notempty(left)
        append first(left) to result
        left = rest(left)
    while notempty(right)
        append first(right) to result
        right = rest(right)
    return result

Question 15: Describe a Heap Sort?

Heap sort is a comparison-based sorting algorithm. Heapsort can be thought of as an improved selection sort.

HTML, CSS and JavaScript

Question 1: Explain what are selectors in CSS?

Selectors enable selecting an element to which a style is to be applied. There are different types of selectors, like class, id, descendant, type selectors.

Question 2: Explain a CSS box model?

Each element is represented as a rectangular box. Each of these boxes is described using the standard box model. Each box has four edges: the margin edge, border edge, padding edge, and content edge.

There are two types of box model, border-box and content-box.

Question 3: What are pseudo classes and what are they used for?

Pseudo classes are similar to classes, but they are not defined in the markup. Some examples are :link, :visited, :hover, :active, :first_line. They are used to call a specific action on an element, for example changng the link colour after it is visited, or changing a link colour when it is hovered.

Question 4: How do you optimize a website’s assets?

Some of the ways to optimize assets are:

  1. Make fewer HTTP requests
  2. Use a Content Delivery Network
  3. Add an Expires header
  4. Gzip components
  5. Put CSS at the top
  6. Move scripts to the bottom
  7. Make JavaScript and CSS external
  8. Minify JavaScript
  9. Remove duplicate scripts

Question 5: What are the 3 different ways to apply CSS?

  1. Inline
  2. External
  3. Embedded/Internal

Question 6: How is the float property implemented in CSS?

Floats allow an element to be positioned horizontally, allowing elements below the floated element to flow around it. Several floating elements can be placed together to make a gallery type layout. To prevent subsequent elements from flowing around the floated element, pass in the clear property, followed by the side you wish to disable (i.e., ‘left’, ‘right’, ‘both’).

Question 7: What is the purpose of the z-index and how is it used?

The z-index helps specify the stack order of positioned elements that may overlap one another.

Question 8: What’s the difference between standards mode and quirks mode?

One prominent difference between quirks and standards modes is the handling of the CSS Internet Explorer box model bug. Another notable difference is the vertical alignment of certain types of inline content.

If the browser decides that the document is modern, it’ll render it in standards mode. This means that, as a rule, CSS is applied in accordance with the CSS2 specification. If the browser decides that the document is old-school, it’ll render it in quirks mode.

Question 9: Graceful degradation vx progressive enhancement?

Graceful degredation - making sure that everythign still works to some level in an older browser, providing with basic functionality of the site.

Progressive enhancement - starting off with the oldest browsers in mind and adding in better functionality for browsers that can handle it.

Degrading gracefully means looking back whereas enhancing progressively means looking forward whilst keeping your feet on firm ground.

Useful Resources:

  1. Mozilla Developer Network.
  2. Wikipedia.
  3. StackOverflow.
  4. Tuts+.
  5. Java Revisited Blog.
  6. Quirks Mode.
  7. Google Developers.
  8. Skilled Up
  9. Quirks vs Standard
  10. Excellent resource of front end interview questions.
  11. HTTP2

Cancun to Belize City by Bus

After 3 weeks in Cuba, Cancun was a refreshing change. The weather changed for the worse in Havana and our entire stay was overcast and grey so feeling warmth and sun on your skin again was excellent! We were a few hours in into our 24 hr trip from Havana (Cuba) to Columbia San Pedro (Belize) where we will be spending 3 educational weeks on an organic permaculture farm in the Belizian rainforest. After long wait at security in Cancun Airport we set off to find the ADO bus counter to book our tickets for that night to get to Belize City. Of course, as luck would have it, the bus was full for that night. This has shifted all of our plans by one day and left us homeless for the night. We booked our tickets for the next day in person at the ADO bus counter at the Cancun airport and spent the next few hours searching for somewhere to stay.

I wanted to share the information I have learned about getting from Cancun to Belize City.

1. Buy or book ADO bus tickets

The buses form Cancun to Belize are operated by ADO (pronounced “aa-de-oo”). They conveniently have an ADO ticket counter as you are exiting the airport. Here you can pre-book your trip to Belize in person as no online booking is available for the bus to Belize (you can also pre-book the ticket in the ADO bus station in Downtown Cancun).

There is only 1 bus a day at 10pm (it arrives in Belize City at 8.30am) from the ADO bus station in downtown Cancun. If you are traveling form the Cancun airport you would have to take another bus (it costs 64 Peso and takes 1hr) or taxi to the downtown ADO bus station. I have snapped a recent picture of the bus times from the airport to downtown Cancun:

Image of bus times from Cancun airport to downtown

Luckily we found somewhere to stay within a 5 minute walk of the ADO downtown bus station and after a much needed rest we carried on our journey the next evening.

2. Take the bus from Downtown ADO bus terminal

You have to arrive at least 15 minutes before the bus departure time, so to be safe we were waiting at the ADO bus station from 9:30 pm onwards. Bonus tip there is free wifi at the station!

Listen for the announcements and the bus arrived to gate 1 on time, we took our bags with us and loaded them into the special compartment just before getting on.

Image of ADO bus

The bus itself is air conditioned and it is absolutely freezing, so bring a blanked (not a joke! it was way too cold to fall asleep and it is apparently a well known fact). If you don’t fancy using the bus toilet you can get off at any of the stops and use the bathroom, usually the driver stops for about 5 minutes or so to pick up more people in Playa Del Carmen, Tulum, Bacalar and then Belize City.

3. Crossing the border

We arrived at the Mexican border at about 4am where we all had to get off the bus and queue outside to go through border control, they checked passports and collected the immigration slip that you would have filled out on entering the country. This is also where we had to pay Mexican Border Exit Tax which was about 300 MXN.

After about an hour at the border we were ushered back onto the bus and a short ride later we arrived at the Belizian border. Here we had to get off the bus with all our luggage and cross the border into Belize and scan all our luggage. Another hour later we were free to go back to sleep but not for long as we would be arriving into Belize City at 8.30am with a few stops on the way (Corozal and Orange Walk).

4. Arriving in Belize City

The bus terminal is still commonly known as Novelo’s (this is the name of a former bus company). The ADO buses arrive and depart from here along with a few other buses.

Image of Novelo Bus Terminal

From Belize City out journey to reach an organic farm cituated in the Belizian rainforest carries on still onto a small town of Punta Gorda in Southern Belize, but that is a whole other blog post.

Food in Havana

On our arrival we quickly realised that we were luckily not staying in the tourist area and that meant all the food near us would be in local Peso and super cheap! We had a chance to try a whole lot of pizza from little hole-in-the-wall places and decided on our favourite spots to have pizza in Havana.

There are 2 that stand out the most: a little blue window on San Lazaro just past Aramburu street and a small place on the Boulevard (not the one in Old Havana, but the one behind the Capitolio) it is right next to some benches and a sandwich place which seems to share the same kitchen, this one is the only one we have seen to make full sized pizzas and to actually fully utilise all available ingredients in Cuba to make tasty pizzas rather than a 2 ingredient pizza available almost everywhere else. Unfortunately I don’t have a picture of either of the places as I was too busy enjoying the food. But this is what the small pizzas look like:

Pizza Jabon y Queso Image

Apart from pizza, there have been a few good meals. Mostly in small local places where the main dish is usually Chuleta or Lomo with rice (usually it is a smoked pork cutlet), sometimes there is also pasta, but ususally it is just that - pasta with not much else.

One evening we walked past what looked like a little pub/bar called El Pachanguero and luckily decided to try it out. The food was not bad compared to most other places and prices reasonable (they accepted CUC and Pesos). There are not many places with “good” food in Cuba to be honest.

El Pachanguero Image

El Pachanguero Image

El Pachanguero Image

Havana, Cuba

Havana is a beautiful city, well worth seeing. It is however very easy to leave with a wrong impression about Havana, on one side you have Old Havana which is extremely well kept and touristy and beautiful but you also have the side of Havana that the locals live in which is much bigger and well worth seeing.

On our journey to Trinidad we found out that there is a China Town in Havana, so on our second day we set out to find it. This is definitely the most disappointing China Town I have ever been to, but at least it had an arch:

China Town Havana Image

Some of the buildings had the original Chinese signs and design, but very few and we only found about 3 places that even do chinese food. Given all that we skipped getting chinese and headed off towards the Capitolio in search of beans and rice.

Capitolio Havana Image

Capitolio is a must see, it is grand and this is where you can find all the old cars parked and ready to give you a ride or a tour of the city. If you don’t fancy that you can simply enjoy the view in the nearby park, by the Jose Marti Monument:

Jose Marti Monument Havana Image

This is a nice place to relax in the evening before heading into Old Havana:

Old Havana Image

We spent a few evenings walking around Old Havana, it is full of beautiful old buildings but it is also full of tourists and people trying to sell you stuff.

Our daily walk back from all the sightseeing took us through the Malecon, this is a nice walk in the sunshine but beware of the waves soaking you on windy days. The view of the city is incredible and if you have time it stretches for hours and takes you through a couple of interesting monuments:

Malecon Havana Image

And some quirky newer buildings:

Colourful Building Image