Author Archives: budhramgurung

Run AngularJS, Bootstrap and Angular UI bootstrap documentation locally

It is always better to run the documentation of library locally as you won’t be dependent on internet for any documentation help. Also, navigation is fast due to local hosting.

Recently, I got chance to work with AngularJS in one of my project.
I chose my favorite front-end framework Twitter Bootstrap.
Also, came to know about Angular UI Boostrap – set of bootstrap components in AngularJS.

I googled a lot on “How to run documentation of above libraries locally?”.
I found few but mostly outdated.
Hence, this blog to summarize all in one page.

Run AngularJS documentation locally:

1. Go to https://code.angularjs.org/ and select your version and download the zip version.
Eg: For version 1.3.14, go to https://code.angularjs.org/1.3.14/ and download angular-1.3.14.zip(~9MB)

2. Extract the zip file. Above will be extracted into angular-1.3.14.

3. Through terminal, go to above folder

    cd angular-1.3.14

4. Start the server as:

    python -m SimpleHTTPServer

5. Visit url http://localhost:8000/docs


NOTE: For Bootstrap and Angular UI Boostrap, you need jekyll(http://jekyllrb.com/docs/installation/)
To install:(need to have Ruby, RubyGems installed)

    gem install jekyll

Run Bootstrap documentation locally:

1. Clone the gh-pages branch repo:

    git clone --branch gh-pages git://github.com/twitter/bootstrap.git

2. Go to bootstrap directory

    cd bootstrap

3. Serve using jekyll

    jekyll serve -P 8001

4. Visit url http://localhost:8001/


Run AngularUI Bootstrap documentation locally:

1. Clone the gh-pages branch repo:

    git clone --branch gh-pages git://github.com/angular-ui/bootstrap.git angular-ui-bootstrap

2. Go to angular-ui-bootstrap directory

    cd angular-ui-bootstrap

3. Serve using jekyll

    jekyll serve -P 8002

4. Visit url http://localhost:8002/

And Enjoy!!!!
docs

Advertisements

How much time did it take for you take to write a technical blog?

What is your opinion on this?

How much time did it take for you take to write a technical blog?

Use of bootbox.js for creating multiple prompts one after another

Bootbox.js is a small and handy JavaScript library which allows one to create dialog boxes using Twitter’s Bootstrap modals programmaticallly.

Basic Example:

  bootbox.prompt("What is your name?", function(result) {                
    if (result === null) {                                             
      // notify some error message
    } else {
      // do some stuff with result
    }
  });

Recently there is a requirement in my project which requires prompting user with few questions and based on user’s response process further stuff.

My first choice was to use bootbox.js’s prompt function and I went with it.

But then after some time I started to feel like “Oops! I selected wrong library here.”. I don’t know how to call another botbox.js prompt in the callback of first one without any redundancy.
Moreover, I need to store the result of each prompt’s response for later processing purpose.

Then, my team lead suggested me to use Underscore’s partial function and gave me pseudo code.

Underscore’s partial function basically defines a function named _.partial which accepts as a parameter a function and arbitrarily no. of arguments. The return value of _.partial is a new function that when called will pass both its own parameters and the initially provided arguments to the original function.

Basic Example of _.partial:

  var add = function(a, b) {
    return a + b;
  };

  var increment = _.partial(add, 1);

We can then call the increment function like this:

  var six = increment(5); // 6

For the add function in the above example, the parameter a is fixed to
the value 1. The first argument that’s passed to increment will be passed to add
as the b parameter.

The same technique I used in the implementation of invoking multiple bootbox.js prompts on
successive prompt’s callback.

Here is how I implemented it:

    var survey_pair, survey_pairs, survey_answers = {};

    // Survey type : Question
    survey_pairs = {
        name: 'What is your name?',
        age: 'How old are you (in number only)?',
        color: 'What is your favourite color?',
        movie: 'What is your favourite movie?'
    };

    function displaySurveyResults(responses) {
        var survey_results_div = $('#survey_results');
        survey_results_div.html('');
        _.each(responses, function(value, key) {
            survey_results_div.append('<li><strong>' + key + '</strong>: ' + value + '</li>');
        });
    }

    function getFirstSurvey() {
        var first_key, first_prompt = {};
        first_key = _.first(_.keys(survey_pairs));
        if (first_key) {
            first_prompt[first_key] = survey_pairs[first_key];
            delete survey_pairs[first_key];
        }
        return first_prompt;
    }

    // main functions
    function showSurvey(survey, callback) {
        // Making survey's type as fixed argument to partial
        var new_callback = _.partial(callback, _.keys(survey)[0]);

        // Calling bootbox.prompt with survey's question and
        // partial callback which has survey's type already
        // and user response will be given through the new_callback
        bootbox.prompt(_.values(survey)[0], new_callback);
    }

    function surveyCallback(survey_type, survey_response) {
        survey_answers[survey_type] = survey_response;
        survey_pair = getFirstSurvey();
        if (survey_pair && !_.isEmpty(survey_pair)) {
            showSurvey(survey_pair, surveyCallback);
        } else {
            displaySurveyResults(survey_answers);
        }
    }

    // Get first question and initiate survey
    survey_pair = getFirstSurvey();
    if (survey_pair && !_.isEmpty(survey_pair)) {
        showSurvey(survey_pair, surveyCallback);
    } else {
        displaySurveyResults(survey_answers);
    }

Here in showSurvey, I am fixing first argument of callback which refer to surveyCallback passed from showSurvey (line no. 53).
The second argument i.e. survey_response of surveyCallback(or callback in showSurvey)
will refer to bootbox.js prompt’s result(or user’s response).

Rest logic is simple. In surveyCallback I am setting survey’s response in some variable
survey_answers here and then fetching next first survey and repeating same iteration.

Click here for working demo.

Shrinking issue in jQuery Splitter on screen resize

After using jQuery splitter, everything was working as according to my requirement.
But as you never get your destination smoothly I also got stuck by one issue.

The issue was when I minimize the screen the three vertical panes doesn’t resize as proportion to their width ratio as shown below:

Right Pane shrinked

Right Pane shrinked

It looks like limitation of the jQuery Splitter plugin. Same issue found in Demo Site.

To solve this issue, I need to do following workaround.
This really helped me to meet my requirement properly.

   <script type="text/javascript">
      function resizeClassView(){
        var main_div_width, left_pane_width, right_pane_width,
            first_left_pane_width, second_left_pane_width, left_splitter, right_splitter;

        main_div_width = $(window).width() - 72;
        left_pane_width = (0.67 * main_div_width);
        right_pane_width = main_div_width - left_pane_width;
        first_left_pane_width = (0.5 * left_pane_width);
        second_left_pane_width = (left_pane_width - first_left_pane_width);
        left_splitter = $($('.vsplitter')[0]);
        right_splitter = $($('.vsplitter')[1]);
        $('#main_div').width(main_div_width + 'px');
        $('#left_pane').width(left_pane_width - 2 + 'px');
        $('#first_left_pane').width(first_left_pane_width - 5 + 'px');
        $('#second_left_pane').width(second_left_pane_width + 'px');
        $('#right_pane').width(right_pane_width + 'px');
        left_splitter.css('left', first_left_pane_width - 7 + 'px');
        right_splitter.css('left', left_pane_width - 5 + 'px');
      }

      $(document).ready(function(){
        var main_div_width = '100%';
        $('#main_div').width(main_div_width).height(500).split({
          orientation: 'vertical',
          limit: 3,
          position: '67%'
        });
        $('#left_pane').width($('#left_pane').width()).height(500).split({
          orientation: 'vertical',
          limit: 3,
          position: '50%'
        });

        // handling widow resize event
        $(window).resize(function() {
          resizeClassView();
        });
      });

   </script>

I handled window resize event and calculated and applied each div’s width and slider left attribute.

Split ‘div’ into three equal parts vertically

There has been a requirement in my project where I have to split a particular div into three equal parts vertically.
It must possess following properties:

  1. Each part should have a slider to resize its width
  2. One should be able to display two parts at a time or complete one part at a time
  3. The content within resizing part should also resize as according to slider movement

I googled for the possible available plugins.
Out of many I found jQuery splitter plugin interesting and decided to go with it.

The Demo Site demonstrates partially what I need but I know I need to do some tweak by myself to make this plugin work exactly what I want.

So following are the steps to how to use this plugin especially in my scenario:

  1. First include this plugin in your html file as :
      <script type='text/javascript' src='../lib/js/jquery-1.9.0.min.js'></script>
      <script type='text/javascript' src='../lib/js/jquery.splitter-0.14.0.js'></script>
      <link rel='stylesheet' type='text/css' href='../lib/css/jquery.splitter.css'>
      ....
    

    NOTE: jQuery should be loaded first as jQuery splitter depends on jQuery.

    You can get jquery.splitter-0.14.0.js(or latest version) and jquery.splitter.css in its Git Repo under js and css folders respectively.

  2. In html body, create div’s structure as bellow:
      <div id="main_div">
        <div id="left_pane">
          <div id="first_left_pane">
            <!-- your left content goes here --></div>
          <div>
          <div id='second_left_pane'>
            <!-- your middle content goes here --->
          </div> 
        </div>
        <div id='right_pane'>
          <!-- your right content goes here --->
        </div>
      </div>
    
  3. In script tag, call splitter method as:

      $('#main_div').width(800).height(500).split({
        orientation: 'vertical',
        limit: 3,
        position: '67%'
      });
      $('#left_pane').width($('#left_pane').width()).height(500).split({
        orientation: 'vertical',
        limit: 3,
        position: '50%'
      });
    

    Here, I am calling splitter method ‘split’ 2nd time to split the ‘left_pane’ div into two equal parts.

    That’s it. Three simple steps and you get the div splitted into approximately three equal parts.

  4. Optionally, if you want to apply extra CSS to slider bar you can do as:

      .splitter_panel .vsplitter {
        position: absolute;
        right: 0;
        top: 0;
        bottom: 0;
        width: 6px !important;
        background-color: gray;
        cursor: ew-resize;
        line-height: 15px;
        font-size: 14px;
        overflow: hidden;
      }
    
      .splitter_panel .vsplitter:before {
        content: ' * * * ';
        color: white;
        position: absolute;
        top: 50%;
      }
    

Following is the screenshot of what it appears after following above steps successfully:

Three Panes Vertically

Three Panes Vertically

Re-initialization of datasets in typeahead.js

typeahead.js is one of autocomplete search plugin inspired by twitter.com.

I have been using it quite from a while in my projects and had wonderful experience so far until I encountered with one requirement.

Requirement: Remove the selected data from dataset and don’t show it in next autosearch suggestions.

I used $(‘.typeahead’).typeahead(‘destroy’); as suggested but it didn’t work as expected.

It reverts the input element back to its original state but again adding typeahead feature to this same input with new dataSets doesn’t remove the autocomplete suggestions with new dataSets.

While googling for few hours for the ideal solution I found one good solution out of the discussion made in this github issue thread.

So following is solution I used and it works like charm!!! 🙂

Steps I followed for the solution:

  • Define a function to enable typeahead functionality as:
      function enable_auto_complete(name, dataSets){
        $('#typeahead_input_element').typeahead({
          name: name,
          local: dataSets
        });
      }  
    
  • Initialize the input with typeahead for first time with some name.
  • Remove the selected name from global ‘dataSets’.
  • Destroy typeahead feature as :
      $('#typeahead_input_element').typeahead('destroy')
    
  • Initialize the input again with typeahead but with different name and updated dataSets.

Working JSFiddle Link.

Intro to Splat (*) operator in Ruby.

I usually use following to create a bunch of array elements in Ruby.

arr = (10..50).to_a     #converting a range to an array.

Today I noticed following which performs same operation:

arr = [*10..50]       # splat operator

My reaction was :
“Awesome!!!!”

So, then, one day I took some time to investigate more on this (*) operator.
Following are few which I could come to know.

1) Generally used in “Method definition with variable no. of parameter” (I have used it but don’t know it was implementation of splat operator (^o^) )

def demo(*numbers)
  numbers.each { |num| puts "#{num}" }
end
demo(1,2,3,4)

#output
1
2
3
4

2) Converting an array into list of arguments in method calling.
In this case, the splat converts the array into method arguments.

def demo(arg1, arg2, arg3)
  puts "arg1 is #{arg1}, arg2 is #{arg2} and arg3 is #{arg3}"
end
arr = [10, 20.45, "hello"]
demo *arr

#output
arg1 is 10, arg2 is 20.45 and arg3 is hello

3) Datatype coercion
Splat operator can be used to convert interesting datatype coercion.

3.1) String into Array : Splat can also be used to coerce string values into array.

arr = *"Hello"  #=> ["Hello"]
"Hello".to_a  #=> NoMethodError: undefined method `to_a' for "Hello":String

Note : This will only create array of size 1.

3.2) Range into Array :

arr = *(10..20)     # [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

Above is similar behavior as ‘arr = (10..20).to_a’

3.3) Hash into an Array:

arr = *{ :a => "111", :b => "222" }    # [[:a, "111"], [:b, "222"]]

Note : Use ‘Hash[*arr.flatten]’ to reverse it.

4) Use in ‘case’ statement :

male = ["ram", "rahul", "karan"]
female = ["kareena", "aish", "juhi", "katerina"]
person = "aish"

case person
when *male
  puts "Male"
when *female
  puts "Female"
end

#output
Female

5) Interesting Array data retrieval:

arr = ["one", "two", "three", "four"]

first, *others = arr         #first = "one", others = ["two", "three", "four"]
*others, last = arr          #others = ["one", "two", "three"] , last = "four"
first, *center, last = arr   #first = "one", center = ["two", "three"], last = "four"  

Getting started with Vim

Vim is a highly configurable text editor built to enable efficient text editing. It is an improved version of the vi editor distributed with most UNIX systems. Vim is distributed free as charityware.

Its navigation system include:

  1. Line navigation
  2. Screen navigation
  3. Word navigation
  4. Special navigation
  5. Paragraph navigation
  6. Search navigation
  7. Code navigation
  8. Navigation from command line

1. Vim Line Navigation

Following are the four navigation that can be done line by line.

  • k – navigate upwards
  • j – navigate downwards
  • l – navigate right side
  • h – navigate left side


By using the repeat factor in VIM we can do this operation for N times. For example, when you want to
go down by 10 lines, then type “10j”.

Within a line if you want to navigate to different position, you have 4 other options.

  • 0 – go to the starting of the current line.
  • ^ – go to the first non blank character of the line.
  • $ – go to the end of the current line.
  • g_ – go to the last non blank character of the line.

2. Vim Screen Navigation

Following are the three navigation which can be done in relation to text shown in the screen.

  • H – Go to the first line of current screen.
  • M – Go to the middle line of current screen.
  • L – Go to the last line of current screen.
  • ctrl+f – Jump forward one full screen.
  • ctrl+b – Jump backwards one full screen
  • ctrl+d – Jump forward (down) a half screen
  • ctrl+u – Jump back (up) one half screen

3. Vim Special Navigation

You may want to do some special navigation inside a file, which are:

  • N% – Go to the Nth percentage line of the file.
  • NG – Go to the Nth line of the file.
  • G – Go to the end of the file.
  • `” – Go to the position where you were in NORMAL MODE while last closing the file.
  • `^ – Go to the position where you were in INSERT MODE while last closing the file.
  • g – Go to the beginning of the file.

4. Vim Word Navigation

You may want to do several navigation in relation to the words, such as:

  • e – go to the end of the current word.
  • E – go to the end of the current WORD.
  • b – go to the previous (before) word.
  • B – go to the previous (before) WORD.
  • w – go to the next word.
  • W – go to the next WORD.

WORD – WORD consists of a sequence of non-blank characters, separated with white space.
word – word consists of a sequence of letters, digits and underscores.

Example to show the difference between WORD and word

  • 192.168.1.1 – single WORD
  • 192.168.1.1 – seven words.

5. Vim Paragraph Navigation

  • { – Go to the beginning of the current paragraph. By pressing { again and again move to the previous paragraph beginnings.
  • } – Go to the end of the current paragraph. By pressing } again and again move to the next paragraph end, and again.

6. Vim Search Navigation

  • /i – Search for a pattern which will you take you to the next occurrence of it.
  • ?i – Search for a pattern which will you take you to the previous occurrence of it.
  • – Go to the next occurrence of the current word under the cursor.
  • – Go to the previous occurrence of the current word under the cursor.

7. Vim Code Navigation

% – Go to the matching braces, or parenthesis inside code.

8. Vim Navigation from Command Line

Vim +N filename: Go to the Nth line of the file after opening it.

vim +10 /etc/passwd


Vim +/pattern filename: Go to the particular pattern’s line inside the file, first occurrence from first. In the following example, it will open the README file and jump to the first occurrence of the word “install”.

vim +/install README


Vim +?patten filename: Go to the particular pattern’s line inside the file, first occurrence from last. In the following example, it will open the README file and jump to the last occurrence of the word “bug”.

vim +?bug README

Ruby Quirks (You would amaze at first point)

Right now i am at the stage of learning. (I guess this line applies to every people who are associated with ruby (^o^) since learning never ends )

While studying Ruby i am finding(**still continuing) that language looks quite simple but has its own complex and hidden secrets.

So, i am writing my experience of unexpected or peculiar behavior (Quirks) i have observed or will be going in future in this post.

1) Why following statement results into ‘nil’ ?

expand = defined?( expand ) ? expand : true

Assume that expand encountered here for the first time.

2) In the following Ruby code, x gets the value nil and pqr remains an undefined local variable. Why?

if false
  x = pqr
end
puts x
puts pqr

3) What is happening in following code and why, how?

x = 5
y = 10
x, y = y, x
puts x
puts y

4) Why expression 1 == 1.0 evaluates to true ?
Check following irb session:

> 1.class   #output Fixnum
> 1.0.class #output Float
> 1 == 1.0  #output true

5) In case of multiple values at right hand side(RHS) of assignment, the rules of parallel assignment come into play. First, all the RHS values evaluated, left to right, and collected into an array (unless they are already an array). This array will be the eventual value returned by the overall assignment. Next, the left hand side (lhs) is inspected. If it contains a single element, the array is assigned to that element otherwise values get corresponding assignment.

a = 1, 2, 3, 4             # => a == [1, 2, 3, 4]  
b = [1, 2, 3, 4] (Array)   # => b == [1, 2, 3, 4]  
c,d = 1,2,3,4              # => c = 1, d = 2

^o^

Happy to create my blog!!!

\^o^/