RSS Feed

Category Archives: programming

A brief comparison of GTK+ and Qt


I used to like C language, because it is a basic of programming, and it is portable, and it is low-level. When writing program with C language, it is just like showing off your advanced programming skill, how you manage the memory, how you manage the pointers and creating the linked list. However, in terms of efficiency, C++ is much more powerful, because of object-oriented and the syntax.

Because I like C language, so I chose GTK+ over Qt for long time ago. Not only that, I am also fond of GTK+ desktop environments like GNOME, Xfce4, LXDE, Cinnamon, but not Mate. I feel that KDE is heavy weight.

One of my personal projects, Med, which was written with GTK+, had some issues with multi-threading. I believe that my engine part does not have any problem. As a result, the suspicious part is the GTK+. The program crash without symptoms, and difficult to reproduce. Therefore, I decided to re-write the UI with Qt. If, Qt also produces the same problem, meaning my algorithm is problematic.

In my opinion, GTK+ is straight forward, because of procedural paradigm. Therefore, it is easy to learn and implement. The UI can be design with Glade. But I feel that it is still lack of something, such as button click callback function. Besides that, though there is gtkmm (C++ interface of GTK+), the library like WebKitGTK+ does not have the documentation for gtkmm (I believe still can work). In summary, GTK+ is slower as writing the code in C language.

On the other hand, Qt is more complicated. To use it, better to use qmake project file to generate the Makefile, or use the CMake, so that we can include the necessary headers and link with necessary libraries. And we also need to use some macro. This makes me feel that the coding is very Qt-oriented, not just a C++ language. However, in terms of design, I feel that Qt Designer is much easier. But GTK+ and Qt layout uses different concept.

Though GTK+ and Qt are both object oriented, GTK+ is in the library level yet Qt is in the language level. It is easier to write inherited classes in Qt, and easily make changes at the language level.

As a conclusion, Qt is better than GTK+ for development as C++ is better than C.

Heading, anchor, and bookmarking


Sometimes I read online articles, and these articles are usually long pages and have outlines at the beginning. These outlines are the hyperlinks to the subtopics headings. Technically, you click the outline hyperlink, your browser will browse to the “anchor”, the URL will append with hash (#). Therefore, it is useful for bookmarking, so that you can share the URL target on the topic to someone else, or re-visit your bookmark.

Thus, I wrote a script as bookmarklet to solve this issue, so that I can click the headings when I am reading the article. You can create the bookmark with the following URL:

javascript:var elems=document.querySelectorAll("h1[id],h2[id],h3[id],h4[id],h5[id],h6[id],h1>*[id],h2>*[id],h3>*[id],h4>*[id],h5>*[id],h6>*[id],a[name]:not([href])");var array=Array.from(elems);array.forEach(function(elem){elem.style.cursor="pointer";elem.setAttribute("title","anchor:"+(elem.id?elem.id:elem.name));elem.innerHTML+=" *";elem.addEventListener("click",function(el){location.hash=el.target.id?el.target.id:el.target.name})});

(Yes, it starts with javascript: instead of http://. Sadly WordPress.com doesn’t allow to create bookmarklet in the post. Moreover, I was actually using ⚓ instead of asterisk *, but WordPress.com auto convert it to emoji, consequently cannot use it in the script above.)

You can try any Wikipedia page to test it. It also works on Stackoverflow, so that you can share the URL to a certain answer to others.

Lecturer, researcher, hobbyist, and software developer


I am cognitive science student. That is why I learnt AI, computational linguistic, machine learning, expert system, etc. 

Since I was a researcher on Augmented Reality, then I applied my computing skills. After this, I became a non-computer related lecturer, and spent my time doing programming as a hobbyist. Then later I became computer science lecturer, yet still had to do programming as a hobbyist. Now as a software developer, I know what are the differences of these roles: lecturer, researcher, hobbyist, and a true software developer. 

A lecturer, as long as they know how to bluff, they are considered good in programming skill.

A researcher, whether they are good in programming skill is totally not important. Because the focus is the research. As a researcher, you do not need to write programs  or scripts. Though these may help, they are not required. As long as your research methodology is correct, that is the core element of the research.

As a hobbyist, you can learn any programming language and write any program. You can write the code that you yourself think it is elegant. You can write any powerful function and use a simple but accurate solution to solve your own problem. You can share your code and publish your project. You can have very strong knowledge to write wondrous algorithm and solve the problem effectively and efficiently. BUT, you are still lacked of industrial experience. 

An actual software developer who works in industrial, what you need is to produce stable products. Yes. Stable. In order to produce stable products, you need to have your products fully tested. Hire a tester can only perform black box testing. They test only as an end user perspective. But the problem is, the bugs are found after you have written the dependent codes on the bugs. So, it would be best to test before these, during the development level. As a developer, writing test cases becomes exhaustive. That is why, Test Driven Development comes in. A stable product is the actual thing that the customers want. They paid the money to get the product, or specifically, the customers hire you to develop a product to them. That is why your products must be stable. Unlike the commercial products, the government projects usually have no clear objective. As long as you deliver a prototype, you can get the money. That is why, the products standards are very different, the developers quality is also very different.

As a lecturer, you talk.

As a researcher, you do experiments.

As a hobbyist, you learn and write.

As an actual software developer, you write and test.

C++ revisit


I liked C programming, as it is low level and the compiler is widely available. Using C language can demonstrate the understanding of pointer and memory. You can implement a linked list or a hash table by using C. So that you can understand better how the linked list and hash table work.

But as long as you want to build some end user applications, C language is never a good choice. Choosing a language for our product is important. We do not develop a web application using low level programming language. It is totally impractical.

C and C++

Do not think that C language is an old language. It can survive until today because it has some powerful features (yet I cannot name them out, because I am not a C developer). There are new features on C99 and C11. But practically to solve higher level problem like game development, C++ is much more better than C. (But there is a better choice like Lua.)

Syntax

Why is C++ better than C? From the syntax level, it is easier to read and easier to write. For example,

strtolower(trim(myString));

where myString is a C string, then trim() is a function that returns trimmed string, strtolower() is another function that returns the string with lower case. (The function names I used here is based on PHP.) So, we can see, when we read or write, we need to read from right to left: trim then strtolower. And the parentheses needs to be matched properly.

On the other hand for C++,

myString->trim()->strtolower();

Let’s say myString is a customized object, namely MyString, that manipulates the string. So, the syntax is much more intuitive. myString calls the trim() method and returns the MyString object, so that we can continue with strtolower() that returns MyString object. This is called method chaining.

Object oriented

Object oriented is a wondrous invention! It is so powerful that most programming languages today support object oriented. Inheritance, polymorphoism, and interface, these features reduce a lot of tremendous works. You can implement object oriented in C (using library such as GObject), but C language is not designed for object oriented.

Because of syntax and the object oriented, I prefer C++ than C.

String

Another advantage of C++ is the string. C string is an array of character, with the fixed size. It is not dynamic as C++ string. For example, you want to perform strcat(), you need to have a larger buffer to store the strcat() result. And if you want to do it with dynamic memory allocation, then you have to free the memory manually. This is exhaustive.

Object method

Related to method chaining, in C++ we can write the methods. In C, because it is using struct, to implement something like method is troublesome. For example,

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int a;
    int (*b)(int a);
} MyType;

int myTypeMethod(int a) {
    return a+20;
}

MyType* myTypeNew() {
    MyType* myType = (MyType*)malloc(sizeof(MyType));
    myType->a = 20;
    myType->b = myTypeMethod; //There is no method in struct, so we assign the callback function
    return myType;
}

void myTypeDelete(MyType** myType) {
    free(*myType);
    *myType = NULL;
}

int main(int argc, char** argv) {
    MyType* myType = myTypeNew();
    printf("%d\n", myType->a);
    printf("%d\n", myType->b(20));
    myTypeDelete(&myType);
    return 0;
}

Because C doesn’t have namespace, but we can do something like namespace by using prefix.

C++11, C++14, C++1z

If you are not C++ lover, you may think that C++ is an archaic programming language. Just like HTML and JavaScript, there are ongoing proposals for the new features for C++. That is why, C++ is not dying yet. There are some notable features I need to state here.

New syntax

“auto” data type

#include <iostream>
#include <typeinfo>
using namespace std;

int main(int argc, char** argv) {
  int a = 10;
  auto b = a;
  cout << b << endl;
  cout << typeid(b).name() << endl; //"i" as integer
  float c = 20.0f;
  b = c;
  cout << b << endl;
  cout << typeid(b).name() << endl; //Still "i"
  return 0;
}

“auto” is just like “var” in C#.

foreach

Most modern programming languages allows foreach keyword, like JavaScript, PHP, and even Python. Though Python uses “for” keyword, it works actually like foreach in PHP.

#include <iostream>
using namespace std;
int main(int argc, char** argv) {
  int a[] = { 4, 5, 3, 2, 1 };
  for(auto item : a) {
    cout << item << endl;
  }
  return 0;
}

Another foreach,

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main(int argc, char** argv) {
  vector<int> a{ 4, 5, 3, 2, 1 };
  for_each(a.begin(), a.end(), [](auto &item) {
      cout << item << endl;
    });
  return 0;
}

The above code can only be compiled with c++14 standard. If using c++11 standard, we must use “int” instead of “auto”.

Lambda expression

Lambda expression, a.k.a anonymous function. If you are working with JavaScript, such as

var a = [ 4, 5, 3, 2, 1 ];
var found = a.find(function(item) {
    if(item == 2)
        return item;
});

So, the above example shows that the parameter of the find() is a function, without a function name. This is a common syntax in functional programming. Functional programming is a trend of most modern programming language. The anonymous function is also supported by PHP. The advantage of functional programming is the elimination of side effects and avoiding changing state of the data. Therefore, it is a good paradigm for parallel programming.

Therefore, looking at the example above, there is some syntax like,

  ([](int b) {
    cout << b << endl;
  })(12);

Which is similar to JavaScript,

(function(b) {
    console.log(b);
})(12);

In C++, the squared bracket is used to capture the variable of the scope. (I think it is similar to PHP “using” keyword.)

Previously, we can use the callback function like,

#include <iostream>
using namespace std;

int foo(int (*cb)(int, void*), int size, void* data) {
  return cb(size, data);
}

int callback(int size, void* data) {
  int sum = 0;
  int* intData = (int*)data; //typecast
  for(int i=0;i<size;i++) {
    sum += intData[i];
    cout << intData[i] << endl;
  }
  return sum;
}

int main(int argc, char** argv) {
  int a[] = { 4, 5, 3, 2, 1 };
  int sum = foo(callback, 5, a);
  cout << sum << endl;
  return 0;
}

Since we can use anonymous function, we need not to create a callback function like above. This can be written as,

#include <iostream>
using namespace std;

int foo(int (*cb)(int, void*), int size, void* data) {
  return cb(size, data);
}

int main(int argc, char** argv) {
  int a[] = { 4, 5, 3, 2, 1 };
  int result = foo([](int size, void* data) {
      int sum = 0;
      int* intData = (int*)data;
      for(int i=0;i<size;i++) {
        sum+= intData[i];
        cout << intData[i] << endl;
      }
      return sum;
    }, 5, a);
  cout << result << endl;
  return 0;
}

Multi-threading, asynchronous programming, promise

We can implement multi-threading using other libraries like pthread. But with C++11, you can create thread without third party libraries, perform sleep, sleep by milliseconds or even nanoseconds. There is also library for mutex (mutually exclusive).

C++11 also supports asynchronous programming like C# and promise like JavaScript. With the lambda expression, the syntax shares some similarities with C# and JavaScript. With async, we can do something at the background (using thread), and use the result later. With promise, you can promise to return some value, else throw an exception.

Regular expression

Regular expression is so important for text processing. C++11 supports regular expression. There are different regular expression syntax: BRE (basic regular expression) is the default syntax used by “grep” command, ERE (extended regular expression, and Perl regular expression. Perl regular expression is very powerful. If you use Python, JavaScript, Ruby, and C#, you will find that they have different syntax.

However, interestingly C++ uses ECMAScript regular expression syntax by default (though we can choose BRE, ERE, or awk). That means, if you know JavaScript RegExp, then you will have no problem with C++ regex.

(I see the converging features of the different programming languages, which means these features are useful, intuitive, and influential.)

 

Garbage collection

So far, there is no good garbage collection for C++.

 

Another thing I have to state. Because of the networking and big data, parallel programming is a demand and the trend. To make sure the data is immutable, functional programming becomes handy.

Vim


Because of the new working environment, I cannot use my favourite customised Emacs to work. So, I have to adapt with the new text editor. Luckily, vim is available in the remote server. That means I can use SSH to run the vim. And, even Emacs is available, I feel difficult to customise and install the packages I need, because I don’t have experience installing Emacs’ packages using text-based UI. (But if it is available, I may make a try.)

On the other hand, vim is a little different. vim is more tend to text-based UI, though there is a GUI version called GVim. In order to familiarise with vim, I also did some customisation on it, especially the key binding (hotkey) which is, totally not user-friendly by default. So, I share my ~/.vimrc with this post.

:set tabstop=4 ai ic wrap lbr showcmd
:set shiftwidth=4
:set expandtab
:set autoread
:set list
:set listchars=eol:↵,tab:→·,space:⋅
:set whichwrap+=<,>,h,l,[,]
":set nu
:set display+=lastline
:colorscheme ron

:filetype plugin on
:syntax on

"Navigate
vmap <Down> gj
vmap <Up> gk

"This will be overridden by YouCompleteMe, so need to have alternave solution
imap <Down> <C-o>gj
imap <Up> <C-o>gk
imap <C-Down> <C-o>gj
imap <C-Up> <C-o>gk
nmap <Down> gj
nmap <Up> gk

"Select
nmap <S-Up> v<Up>
nmap <S-Down> v<Down>
nmap <S-Left> v<Left>
nmap <S-Right> v<Right>
nmap <S-Home> v<Home>
nmap <S-End> v<End>
imap <S-Up> <C-o>v<Up>
imap <S-Down> <C-o>v<Down>
imap <S-Left> <C-o>v<Left>
imap <S-Right> <C-o>v<Right>
imap <S-Home> <C-o>v<Home>
imap <S-End> <C-o>v<End>
vmap <S-Up> <Up>
vmap <S-Down> <Down>
vmap <S-Left> <Left>
vmap <S-Right> <Right>
vmap <S-Home> <Home>
vmap <S-End> <End>

"Remap the delete key, so that will not override the register for pasting
vmap <Delete> "_x
vmap <Backspace> "_x

"For the characters like newline (if shown with list)
highlight NonText guifg=#333333 guibg=#000000 ctermfg=darkgrey
"For special key like whitespace and tab
highlight SpecialKey guifg=#333333 guibg=#000000 ctermfg=darkgrey

 

GVim and Emacs

Best ever text editors: (g)vim and emacs

Multilingual programming


Recently I involve in various projects. And they are using different technologies. I am fervent in programming because it conforms to my theological and philosophical perspective.

The languages and technology I am currently using: AngularJS and NodeJS, .NET MVC with C# Mono, and Ruby on Rails. Other related technologies: Nginx, AWS, migrations, Bootstrap CSS, etc. Besides that, my background is strong fundamental C, C++, and PHP skills; have good experience on Python; some experiences on Java, Android, Perl, and VB Script.

Since the advancement of cloud computing, everything is about server and client. HTML, JavaScript, and CSS are the basic of the basics. Furthermore, I am a Linux user, working on sysadmin tasks becomes much easier.

Naming convention and syntax

Involving in various languages and different development frameworks, there is something very important, that is, naming convention. Unlike syntax, where syntax is the language level rules, naming convention is the framework level rules. That means, when using a certain framework, you should follow the naming convention, especially MVC framework. Because by following naming convention (and file structure as well), the framework will use the corresponding database, view page, and controller as well. That is why, you follow it, your development will work faster, need not to care about the internal algorithms.

And some of the naming conventions, is just the style, not really related to the framework. They are “recommended”, instead of “required”. You must know how to differentiate these two.

Let me explain why the naming convention matters. Web technology is a very interesting area. If you open an HTML file, you will see three kinds of syntaxes: HTML, JavaScript, and CSS. Yes, these kinds of syntaxes exist in one file. JavaScript usually use the camel case, so do HTML DOM methods. CSS selector has no requirement, you can use camel case as well, but it is usually hyphenated identifiers, eg foo-bar instead of fooBar. HTML has no restriction. But the attributes are usually hyphenated, yet the value can be camel case or hyphenated. If it is JavaScript related, then camelCase; if CSS, hyphenated. This is how HTML works.

The above is purely client side HTML. For the server side, we usually use a template engine or template system. MVC uses Razor: Rails uses ERB; ExpressJS uses Jade; etc. So, when using these engines, new syntax comes in. Some template engines allow logical statements written in the view, such as Razor and ERB. As a result, you will see pascal case in Razor, snake case in ERB. So, by looking at these naming conventions and syntaxes, you will know what languages being used and what you should do. On the other hand, AngularJS has a very neat template design. No logical statements allowed in the template. Consequently, the template is very neat!

Pascal case and camel case

I don’t like Microsoft, but I admit that Microsoft has its own strength in some technologies. (Else you will not see Mono in Linux.)

Microsoft uses Hungarian notations in C/C++ documentation, for instance, “szName” means identifier “Name” with zero-terminated string data type. It is less human readable. Currently there are a lot of high level languages, thus human readable is required so EVERYONE can code. That is why the methods/functions are verbs like getSomething, setSomething, countSomething, addSomething, removeSomething, clearSomething, etc.

Microsoft uses PascalCase; JavaScript uses camelCase. Because I am used to work on JavaScript and HTML DOM more, that is why I prefer camelCase. Microsoft doesn’t disallow camelCase, but the PascalCase is a suggested naming convention. The reason I prefer camelCase rather than PascalCase is because, uppercase of the first later like

MyType

means data type. And

myData

means variable.

So, using the uppercase of the first letter allows me to differentiate my source code easily. However, Microsoft .NET C# uses PascalCase.

So, the question is, should I follow PascalCase or camelCase when using C#? After working with so many projects, I decided to follow the naming convention as recommended. Just use PascalCase as it is recommended. So that, I can feel the conformity instead of alienation. So, how to differentiate the data type and the variable? That is an easy solution. Just recognise them semantically! Because the programming languages, at the end, are still human readable language.

Editor

Lastly, I have to talk about the text editor. Instead of IDE, I prefer my favourite text editor, which can split the view into multiple unlimited windows, or clone multiple unlimited windows. Not only that, the text editor has syntax highlighting in multiple languages in one file like HTML. At the same time, open different file types like Ruby, C#, JavaScript, CoffeeScript, CSS, SASS, SCSS, it can still differentiate them. None of the editor can beat it! Yah! That is Emacs. Emacs is the best programmer editor!

I like Vim too. There is always Emacs and Vim war. I like Vim, as it is a general text editor. Edit any text with keyboard only. Edit configuration files through SSH, Vim is the best. Yet, Emacs is the programmer editor. It takes care the programming language indentation smartly. This is what I need! Highlight all and TAB, everything is formatted!

Unit testing and TDD


  1. I was thinking, WT* is the unit test?
  2. Why should I need unit test?
  3. Why should I spend my time to prepare the test cases?
  4. Why should I spend my time to become a tester instead of a developer?

For the first question, if searching online, what you get are just bunch of almost useless information. They can let you get high score in exam.

For the second question, instead of answering why, I will say, it depends. It depends on the language you are using and the framework that you are using. Let’s say you are working on C programming, there is less support of unit testing library. If you are working on Linux kernel development, unit test is difficult to implement. But, if you are developing web application, then unit testing and other testings are highly recommended. Why? Let me go to the next two answers beforehand.

For the 3rd and 4th questions, if you are not a tester, you no need spend your time specifically to prepare the test case. But, since you are a developer, surely you need to test your function during the development. Then, that is the time you prepare your test cases.

Why do you need “testing”?

Because of the advance of the web applications, the faster web development is needed. That is why there are so many MVC frameworks. But, faster development does not guarantee stable and valid products. In order to make it stable and valid (do what I want), you need to test it.

Since I was developing command-line tools, C/C++ libraries, scripting, desktop application using GUI widgets like GTK+/GTKMM, they are less likely to be tested as MVC. For example, if you are writing a linear function, y=mx+c, are you going to write a test case on it? Surely no. You can write a test case, but it is insignificant to see the advantage of unit testing. Because it is too simple. Nevertheless, if you insist to write the test cases, then you can include the test cases with non numerical input parameters, numerical input parameters, etc. However, since you are not a tester, but a developer, surely you can ignore this kind of testings.

In the case of web development, it is different. The reason is, because your web application involves so many things, MVC: model, view, and controller. It involves I/O, database, HTTP protocols, session, cookie, cache, email, HTML, JavaScript, CSS, etc. So, the question is, how are you going to test your product? Are you going to test everything? Yes, you should test everything. But test from login and click every links, enter various types of inputs, until logout, is just impracticable. So, that is why test-driven development (TDD) comes in. And it involves unit test and integration test. Unit test is the smallest unit testing. It is smallest, to make sure each unit works as expected individually. Only if the unit testing is passed, then we do the integration testing, which tests the units together.

Now, interesting part is writing the test cases. Once we write the test cases, then we can test these cases in automation. This is the part I like most. When you do the testing, it will go through all the test cases you have written. This means that, we can get the bugs when we do the development and testing. Since the web application involves so many components, we will break the functionality easily when we add some features. By adding new functions, we modify the old function, and accidentally break the old functions. Without using automated testing, we will prone to test the new functions only, because we “knew” that, old functions work.

So, using unit test and integration test, we can make sure that our product passes all the test cases. And we are confident that our product is not just being tested with the latest function, but the existing functions are still working.