Replace Conditional with Polymorphism

  • 0
Trying to convince my team to give up on if/then/else & case...

Let's play with some code!

First the the non Object Oriented / procedural version:

/*
 * non_oop.cpp
 *
 *  Created on: Sep 4, 2015
 *      Author: ferrazlealrm@ornl.gov
 *
 *  Non OOP example of URL:
 *  scheme:[//domain[:port]][/]path
 */

#include <iostream>
#include <string>

std::string domain = "ornl.gov";
std::string http_port = "80";
std::string https_port = "443";
std::string ftp_port = "20";

std::string build_url(const std::string &scheme,
  const std::string &domain,
  const std::string &port) {
 return scheme + "://" + domain + ":" + port;
}

int main(int argc, char* argv[]) {
 if (argc != 2) {
  std::cerr << "Use " + std::string(argv[0]) + " [http, https, ftp]"<<std::endl;
  exit(-1);
 }
 std::string scheme = argv[1];

 if (scheme == "http"){
  std::cout << build_url(scheme,domain,http_port) <<std::endl;
 }
 else if (scheme == "https"){
  std::cout << build_url(scheme,domain,https_port) <<std::endl;
 }
 else if (scheme == "ftp"){
  std::cout << build_url(scheme,domain,ftp_port) <<std::endl;
 }
 else {
  std::cerr << "Scheme not valid. Use of these: http, https, ftp"<<std::endl;
 }
 return 0;
}

And the finally the Object Oriented version:

/*
 * oop.cpp
 *
 *  Created on: Sep 4, 2015
 *      Author: ferrazlealrm@ornl.gov
 *
 *  OOP example of URL:
 *  scheme:[//domain[:port]][/]path
 */

#include <iostream>
#include <string>
#include <map>

// Abstract class: cannot be instantiated
class URL {
protected:
 std::string domain = "ornl.gov";
 std::string port;
 std::string scheme;
 std::string build_url(const std::string &scheme,
   const std::string &port) const {
  return scheme + "://" + domain + ":" + port;
 }
public:
 // Pure virtual function: i.e. must be overridden by a derived class
 virtual std::string build_url() const = 0;
 ~URL() {};
};

class Http: public URL {
public:
 Http() {port = "80"; scheme = "http";}
 std::string build_url() const {
  return URL::build_url(scheme, port);
 }
};

class Https: public URL {
public:
 Https() {port = "443"; scheme = "https";}
 std::string build_url() const {
  return URL::build_url(scheme, port);
 }
};

class Ftp: public URL {
public:
 Ftp() {port = "20"; scheme = "ftp";}
 std::string build_url() const {
  return URL::build_url(scheme, port);
 }
};

/**
 * Main function
 */
std::string build_url(const URL &url) {
 return url.build_url();
}

int main(int argc, char* argv[]) {
 if (argc != 2) {
  std::cerr << "Use " + std::string(argv[0]) + " [http, https, ftp]"
    << std::endl;
  exit(-1);
 }
 std::string scheme = argv[1];

 // UGLY!!!
 // In real world I would have here some sort of Dependency Injection (e.g. factory)
 // This just shows that we can get an object given a string
 Http http;
 Https https;
 Ftp ftp;
 std::map<std::string, URL*> choices;
 choices.insert(std::make_pair("http", &http));
 choices.insert(std::make_pair("https", &https));
 choices.insert(std::make_pair("ftp", &ftp));

 if (scheme == "http" or scheme == "https" or scheme == "ftp") {
  std::cout <<  build_url(*choices[scheme]) << std::endl;
 } else {
  std::cerr << "Scheme not valid. Use of these: http, https, ftp"
    << std::endl;
 }
 return 0;
}

I know it looks complicated, but imagine you want to add a new functionality. Let for example add a path to the HTTP url:

/**
 * Let's imagine that I want to add a path to the URL: http://ornl.gov:80/
 * I don't need to modify the code! Open/closed principle.
 * Just extend it, i.e., add new code.
 */

class HttpWithPath: public Http {
protected:
 std::string path;
public:
 HttpWithPath(std::string path) : Http(), path(path) {}
 std::string build_url() const {
  std::string default_url = URL::build_url(scheme, port);
  return default_url + "/" + path;
 }
};


It does not violate the open/closed principle, which states:
"software entities should be open for extension, but closed for modification".


Just for fun

  • 0
Running out of processing power...
64 x AMD Opteron(tm) Processor 6376
$ lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                64
On-line CPU(s) list:   0-63
Thread(s) per core:    2
Core(s) per socket:    8
Socket(s):             4
NUMA node(s):          8
Vendor ID:             AuthenticAMD
CPU family:            21
Model:                 2
Stepping:              0
CPU MHz:               2300.114
BogoMIPS:              4599.35
Virtualization:        AMD-V
L1d cache:             16K
L1i cache:             64K
L2 cache:              2048K
L3 cache:              6144K
(...)

$ grep MemTotal /proc/meminfo
MemTotal:       529254920 kB

$ df -h
(...)
                      1.1P  552T  477T  54% /(...)
(...)


JQuery autocomplete with ranged fields

  • 0
Few weeks ago I was looking for a way to get a form field autocomplete from a remote JSON file with a single HTTP request. The solution is here.
Now I want to do the same but using ranged fields (i.e., sort of an array where commas separate items and hyphen define ranges). A valid field would be: 1-8,10,13,15-20.

Here the javascript / JQuery code:
    /* Function to populate the autocomplete from a remote json.
      For ranged fields, .e.g,: 4588-4590,465-658 */
    function split(val) {
        return val.split(/[,-]\s*/);
    }

    function extractLast(term) {
        return split(term).pop();
    }

    function set_autocomplete_ranged(selector, jsonurl) {
        $.ajax({
            url: jsonurl,
            type: 'get',
            dataType: 'json',
            async: true,
            success: function (data) {                
                $(selector).autocomplete({
                    minLength: 0,
                    source: function (request, response) {
                        response($.ui.autocomplete.filter(
                        data, extractLast(request.term) ));
                    },
                    focus: function () {
                        return false;
                    },
                    select: function (event, ui) {
                        var this_value = ui.item.value
                        var all_values = this.value
                        this.value = all_values + this_value
                        return false;
                    }
                }).bind('focus', function () {
                    if (!$(this).val().trim()) $(this).keydown();
                });
            }
        });
    }
An then just add the URL for the JSON and the id for the field you want to use the ranged autocomplete:
    /*
    Function called only once! It populates the autocomplete from a remote json.
    The filtering is made locally as the source is a local variable :)
    */
    $(function() {
        var jsonurl = "http://mysite.com/myjson.json";
        var selector = '#id_ranged_field';
        if  ($(selector).is('*')) {
            set_autocomplete_ranged(selector,jsonurl);
        }
    });

Writing Blogger posts in Markdown

  • 0
Just write your markdown post here:

http://jbt.github.io/markdown-editor/

And copy paste from the right pane :) That's all!!


I have tried a few, including the stackedit.io, and this looks the best as Blogger doesn't mess up the format...

Flavoured (i.e., github) Markdown syntax is available here:

https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet


Git: Going back in time

  • 0
  1. Testing stuff on a old commit
# This will detach the HEAD, i. e., it leaves no branch checked out:
git checkout 

# Or:

# This will create a new branch from an old commit. Ideal to play and make new commits.
git checkout -b old-state 
  1. Getting rid of everything done since a specific commit
# If no published commits exist, i. e., it all the commited changes are were not pushed yet!
git reset --hard 
  1. Undo published commits with new commits.
# Delete a commit somewhere in time (the following commits are kept!):
git revert HEAD~2

# Delete the last commit:
git revert HEAD

# Delete the last two commits:
git revert HEAD~2..HEAD

Git: Delete Branch Remote and Locally

  • 0
  1. See all branches:
git branch -a
  1. Delete the branch locally:
git branch -D 
  1. Delete the branch remotely:
git push origin --delete 
DONE!

Git Roll Back

Rolling back to a previous commit:

Only, and only, if you are working by your self!

(This is dangerous in a collaborative environment: we are rewriting history!)
git reset --hard 
git push -f origin
Note, if by any reason you want to have access to the lost commits, use:
git reflog

Getting your pocket content delivered to your Kindle touch

  • 0
I wanted to have the articles I save in my Pocket emailed to my old kindle touch... I hate reading in LCDs so I used for a while the en2kindle until the point it became paid. It's not expensive but after checking the python wrapper for the pocket api, I figured out that implementing something similar shouldn't be too hard...
So I came across the kindler on github and decided to give it a go.
First think was to have a look at the Pocket Authentication API Documentation and get a consumer key for the Kindler script.
I forked the repo changed a few things in the code because GMail wasn't working.
I now leave it running in my mac or Linux Box 24h a day and get stuff delivered almost instantaneously.
If you want to give it a go, here a few notes:
I had to install before:
pip install pyyaml
pip install setproctitle
pip install requests
pip install pyquery
pip install humanize
pip install gevent
Get it to work having an http server running:
python -m SimpleHTTPServer
My cfg.yml:
api:
  consumer: ########
  redirect: http://localhost:8000/

users:
- pocket:
    user: ########
    pass: ########
  kindle:
    email: ########@kindle.com

smtp:
  host: smtp.gmail.com
  port: 587
  user: ########@gmail.com
  pass: <Application password! Not your GMAIL!!>

JQuery Autocomplete with an AJAX call to a remote JSON

I'm posting this because it took me ages to figure it out...
I wanted an input field with autcomplete values provided by a remote JSON. My requisites were the following:
  • No dynamic JSON request:
  • Every time the user types a letter no JSON remote call!
  • autocomplete accepts a source : data field, where data can be an URL to a remote location. The problem is that when the user is typing it keeps sending requests to the URL appending ?term=. The idea is that the filtering is done on the server side.... Not what I want... I want the filter to be done on the client side as in case when data is a local variable.
  • Also, because every JSON generation takes more than 1 second, I wanted just one, and a single one request, to the remote location.
So here the code that sorted it out:
/* Function to populate the autocomplete from a remote json. 
   Note the Ajax call which success populates the autocomplete selector
*/
function set_autocomplete(selector, jsonurl) {
    $.ajax({
        url: jsonurl,
        type: 'get',
        dataType: 'json',
        async: true,
        success: function(data) {
            //console.log(data);
            $(selector).autocomplete({
                source: data,
                minLength: 0,
            });
        }
    });
}

/* This is only called once when the page is loaded :) 
   Here the URL to the json and the selector are defined.
*/
$(function() {
    var jsonurl = "URL TO CALL";
    var selector = 'YOUR SELECTOR, e.g.: input';
    if ($(selector).is('*')) {
        set_autocomplete(selector, jsonurl);
    }
});
My JSON looks like this (note that what the user types matches the label but the input field will keep what I have in the value) :
[  
   {  
      "value":"46477",
      "label":"46477 - erererer"
   },
   {  
      "value":"46478",
      "label":"46478 - erererere"
   },
   {  
      "value":"46479",
      "label":"46479 - ererererer"
   },
   {  
      "value":"46480",
      "label":"46480 - trhteyretytryteyety"
   }
]
And the CSS (just to keep the drop down box with a fixed width and scroll bar):
.ui-autocomplete { height: 200px; overflow-y: scroll; overflow-x: hidden;}

Python is now the most popular introductory teaching language at top U.S. universities

  • 1



Python is currently the most popular language for teaching introductory computer science courses at top-ranked U.S. departments. Specifically, 8 of the top 10 CS departments (80%), and 27 of the top 39 (69%), teach Python in introductory CS0 or CS1 courses.



Source : Python is now the most popular introductory teaching language at top U.S. universities | blog@CACM | Communications of the ACM

Mantid for the ILL

  • 0

June 18th
10:00 Mantid presentation (College 1 seminar)
Quick introduction to Mantid for the ILL. Scope, current status (E. Farhi, 15').
Introduction to the MantidPlot user interface (A. Markvardsen, 25').
Specific work done in Mantid to support ILL instruments (R. Leal, 35').



Full presentation:
Mantid @ILL

Thoughts on scientific code...

  • 0
Two interesting articles I've just read on the way to work:

The Low Quality of Scientific Code

Why bad scientific code beats code following "best practices"

On (roughly) the same subject" this is also quite interesting:

Scientific computing’s future: Can any coding language top a 1950s behemoth? - Scientific computing’s future: Can Haskell, Clojure, or Julia top Fortran?




Most Popular Programming Languages of 2014

  • 0

Python retains it's #1 dominance :)




Screen Shot 2014-01-17 at 2.46.35 PM.png

Source: CodeEval.

GitHub language trends 2014

  • 0
JavaScript ahead??
Probably thanks to the thousands of automatically generated lines of code...




Source : Redmonk.

C++ : Constructors involved when returning values from functions

  • 0

Trying to figure out how to return huge objects when they are created inside a function or changed inside a function (i.e. avoiding copy constructors).

Code and output should be easy to understand.

Code:

#include <iostream>

using namespace std;

class Dummy {
 int x;
public:
 Dummy() :
   x(0) {
  cout << "\t -> Default Constructor" << endl;
 }
 virtual ~Dummy() {
   cout << "\t -> desctructor" << endl;
  }
 Dummy(int i) :
   x(i) {
  cout << "\t -> Parameter Constructor" << endl;
 }
 Dummy(const Dummy& other) :
   x(other.x) {
  cout << "\t -> Copy Constructor" << endl;
 }
 // Two existing objects!
 Dummy& operator=(const Dummy& other) {
  x = other.x;
  cout << "\t -> Copy Assignment Operator" << endl;
  return *this;
 }
 //C++11
 Dummy(Dummy&& other) {
  x = std::move(other.x);
  cout << "\t -> C++11 Move Constructor" << endl;
 }
 //C++11
 Dummy& operator=(Dummy&& other) {
  x = std::move(other.x);
  cout << "\t -> C++11 Move Operator" << endl;
  return *this;
 }

 void setX(int x) {
  this->x = x;
 }

 friend ostream& operator<<(ostream &out, const Dummy &m);
};

ostream& operator<<(ostream &out, const Dummy &m) {
 out << "\t   -> Dummy.x=" << m.x << endl;
 return out;
}


Dummy fRetClassValue() {
 return Dummy();
}

Dummy fRetClassValue(int x) {
 Dummy d = Dummy(x);
 return d;
}

// Cant't return references to local variables
//Dummy& fRetClassRef() {
// return Dummy();
//}
//
//Dummy& fRetClassRef(int x) {
// Dummy d = Dummy(x);
// return d;
//}

/**
 * This will return a reference for the class passed by param
 * No copy constructors involved
 */
Dummy& fRetClassRef(Dummy &d) {
 return d;
}

Dummy& fRetClassRef(Dummy &d, int x) {
 d.setX(x);
 return d;
}

/**
 * This will return a copy for the class passed by param
 * Copy constructors involved!
 */
Dummy fRetClassValue(Dummy &d) {
 return d;
}

Dummy fRetClassValue(Dummy &d, int x) {
 d.setX(x);
 return d;
}

Dummy& f3(Dummy &m) {
    m.setX(21);
    return m;
}


int main(void) {
 cout << "1........................." <<endl;
 Dummy d1 = fRetClassValue();
 cout << d1;
 Dummy d2 = fRetClassValue(2);
 cout << d2;

 cout << "1_2......................... (Need const to work!)" <<endl;
 const Dummy &d1_2 = fRetClassValue();
 cout << d1_2;
 const Dummy &d2_2 = fRetClassValue(22);
 cout << d2_2;

 cout << "2........................." <<endl;
 Dummy d3 = fRetClassRef(d1);
 cout << d3;
 Dummy d4 = fRetClassRef(d1,4);
 cout << d4;

 cout << "2_2........................." <<endl;
 Dummy &d3_2 = fRetClassRef(d1);
 cout << d3_2;
 Dummy &d4_2 = fRetClassRef(d1,42);
 cout << d4_2;

 cout << "3........................." <<endl;
 Dummy &d5 = fRetClassRef(d1);
 cout << d5;
 Dummy &d6 = fRetClassRef(d1,6);
 cout << "d1" << d1;
 cout << "d6" << d6;
 d6.setX(123);
 cout << "d1" << d1;
 cout << "d6" << d6;

 cout << "4........................." <<endl;
 const Dummy &d7 = fRetClassValue(d1);
 cout << d7;
 const Dummy &d8 = fRetClassValue(d1,7);
 cout << "d1" << d1;
 cout << "d8" << d8;
 d6.setX(1234);
 cout << "d1" << d1;
 cout << "d8" << d8;

 cout << "END ........................." <<endl;

 return 0;
}

Output:

1.........................
  -> Default Constructor
    -> Dummy.x=0
  -> Parameter Constructor
    -> Dummy.x=2
1_2......................... (Need const to work!)
  -> Default Constructor
    -> Dummy.x=0
  -> Parameter Constructor
    -> Dummy.x=22
2.........................
  -> Copy Constructor
    -> Dummy.x=0
  -> Copy Constructor
    -> Dummy.x=4
2_2.........................
    -> Dummy.x=4
    -> Dummy.x=42
3.........................
    -> Dummy.x=42
d1    -> Dummy.x=6
d6    -> Dummy.x=6
d1    -> Dummy.x=123
d6    -> Dummy.x=123
4.........................
  -> Copy Constructor
    -> Dummy.x=123
  -> Copy Constructor
d1    -> Dummy.x=7
d8    -> Dummy.x=7
d1    -> Dummy.x=1234
d8    -> Dummy.x=7
END .........................
  -> desctructor
  -> desctructor
  -> desctructor
  -> desctructor
  -> desctructor
  -> desctructor
  -> desctructor
  -> desctructor