Tuesday, 26 July 2016

C++ overload operators

Three cases are enlisted below as templates -- . More could be added later...

(1) Box1 + Box2

// Overload + operator to add two Box objects.
Box operator+(const Box& b) 
{ 
    Box box;      // this is the new box to return
    box.length = this->length + b.length; 
    box.breadth = this->breadth + b.breadth; 
    box.height = this->height + b.height; 
    return box; 
}

(2) Box1 <  Box2 // Overload < operator to add two Box objects.
        bool operator<(Box &b)
        {
            if(this->l < b.l)
                {return true;}
            else if(this->b < b.b && this->l == b.l)
                {return true;}
            else if(this->h < b.h && this->b == b.b && this->l == b.l)
                {return true;}
            else
                {return false;}
        }



(3) Overloading the I/O operators

i) the output <<
//Overload operator << as specified
        friend ostream& operator<< (ostream &out, const Box &b)
        {
            cout<<b.l<<" "<<b.b<<" "<<b.h;
            return out;
        }


The above examples should be included as the public functions in the Class Box.

ref:

Monday, 25 July 2016

C++ Extract multiple int from one string using stringstream

Sometimes you might get the input such as "23,4,56" and you would like to extract them as integers. There needed some kind of iteration through the string. However, we do not know the length of how many numbers are there in the string.

I write the following case for this function.

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

int main()
{
    vector<int> vec;
    string input = "23,4,56";
    stringstream ss;
    ss << input;
    string temp;
    int iTemp;

    while(std::getline(ss, temp,',')) {
        if(std::stringstream(temp)>>iTemp)
        {
            vec.push_back(iTemp);
        }
    }
    
    for(int i=0;i<vec.size();i++)
    {
        cout<<vec[i]<<endl;
    }
    
    return 0;
}

ref:
http://stackoverflow.com/questions/21594533/c-extract-int-from-string-using-stringstream

c++ Static variable for object count


It is very often that you might need to count the current number of instance of this class. 


class Widget {
public:
    Widget() { ++count; }
    Widget(const Widget&) { ++count; }
    ~Widget() { --count; }
    static size_t howMany()
    { return count; }
private:
    static size_t count;
};

size_t Widget::count = 0;


Intuitively, you need a static variable in the class. However, it is very important to remember that 
static size_t count; is only a declaration and there is no memory allocated and referred to this variable. That is, we need the last line, size_t Widget::count = 0;, so that the linker knows what memory location you're referring to when you use the name.


ref:
http://www.drdobbs.com/cpp/counting-objects-in-c/184403484
http://stackoverflow.com/questions/7781188/static-variable-for-object-count-in-c-classes

C++ String Integer Conversion


There are several methods but I prefer this way.

1
2
3
4
5
6
7
template <typename T>
  string NumberToString ( T Number )
  {
     ostringstream ss;
     ss << Number;
     return ss.str();
  }
Usage: NumberToString ( Number ); 

1
2
3
4
5
6
7
template <typename T>
  T StringToNumber ( const string &Text )
  {
     istringstream ss(Text);
     T result;
     return ss >> result ? result : 0;
  }
Usage: StringToNumber<Type> ( String ); 

But #include <sstream> must be added at the top.


ref:
http://www.cplusplus.com/articles/D9j2Nwbp/

Thursday, 14 January 2016

Download Files in Windows with the Extension Name You Want

I am trying to download a ".sty" file for LateX editing. But Windows failed to recognize it as a LateX file (only .tex file can be automatically downloaded as .tex). So Windows game me only .txt type and I end up downloading the file: xxxxxx.sty.txt, which cannot be recognize by LateX! Sooooo annoying!!!

I searched and many suggested very complicated ways to remove it such as a third-party software or change something in the Windows Register. This is why I HATE Win. I find a easy way to do it inspired from the following blog:

http://lifehacker.com/5883860/change-the-file-extension-of-any-file-through-windows-save-as-menu

However, it is not perfect. For example. the file you are trying to Save As is abcde.sty and you input "abcde.sty" in the file name, then the type you will get is .sty". So only one quote at the beginning of the file name is enough, like this:

"abced.sty

Thursday, 17 December 2015

Appending Items to List in R

A very common programming problem is that a function must return a list of objects (itmes like trees...).
In R, we can do something like the following:

func_????? <- function ( ... )
{
    ret_TreeList = list()

    for(i in 1: ?????)
    {
        if(...)
        {
             ret_TreeList[[i]] = something
        }
        else(...)
        {
             ret_TreeList[[i]] = something else
        } 
        
    }

    return(ret_TreeList)
}

Then we cna use it like this:

>TreeList = func_?????(...)
>TreeList[3]

Hope it helps ;-}

Wednesday, 16 December 2015

Install R packages Removed from CRAN (from the source)

I need to use some really useful R packages but unfortunately they are removed from CRAN which means I cannot just install.packages(...) from the cloud and I must install it from the source.

There are two ways of doing this:

(1)
library(devtools)
install_url('http://cran.r-project.org/src/contrib/Archive/dynamo/dynamo_0.1.3.tar.gz')
install_url('http://cran.r-project.org/src/contrib/Archive/gafit/gafit_0.4.tar.gz')

(2) Which I prefer!!
Download the package source first and then:
install.packages('/path/dynamo_0.1.3.tar.gz', type = 'source')

ref:
http://stackoverflow.com/questions/18655976/how-to-install-the-package-that-has-been-removed-from-the-cran-repository-in-r-e

Sunday, 13 December 2015

Where is to find the bodyfat dataset?

When trying some old (even not so old) examples using R package mboost, the dataset "bodyfat" cannot be loaded.

> data("bodyfat", package = "mboost")
Warning message:

In data("bodyfat", package = "mboost") : data set ‘bodyfat’ not found

Many famous examples are still like this, like
Yanchang Zhao's book: “R and Data Mining: Examples and Case Studies”

==============================================================

The data is provided in package TH.data, but no longer in package mboost.

To use the data, run code below.

data("bodyfat", package="TH.data")

Saturday, 14 November 2015

Find the k Smallest Elements in a List using R

This program is definitely not the most efficient way to find the k smallest elements in a List. But I simply need this now. Improvements might be done later and you are mostly welcome to share any ideas of improvements.

l = c(7,3,6,1,0,2,10,9)

KSmallestElem <- function(DataList, k)
{
  n = length(DataList)
  kmin = {}
  
  initMinIndex = which.min(DataList)
  initMinVal = min(DataList)
  kmin = rbind(kmin,c(initMinIndex,initMinVal))
  
  # 1st level loop:
  #     k times to find the smallest k elemenst
  for(i in 1:k)
  {
    minIndex = 1
    minValue = DataList[1]
    # 2nd level loop:
    #     over the original DataList
    for(j in 1:n)
    {
      if(DataList[j] > kmin[i,2] &&
         DataList[j] < minValue)
      {
        minIndex = j
        minValue = DataList[j]
      }
      
    }
    
    kmin = rbind(kmin,c(minIndex,minValue))
  }
  
  return(kmin)
}


KSmallestElem(l,3)

#################################
Results:
> KSmallestElem(l,3)
     [,1] [,2]
[1,]    5    0
[2,]    4    1
[3,]    6    2
[4,]    2    3
> 









Saturday, 7 November 2015

Reverse scaling data/ Unscaling data in R

In machine learning, data should usually be scaled before feeding to the training model since variables might be in different kinds of ranges. If not scaled, it shall make the prediction far from accuracy when calculating the distances among  data.

However, we still need a prediction result in the original range, which is the reverse of scaling.

In r, we could do this:

attributes(d$s.x)

d$s.x * attr(d$s.x, 'scaled:scale') + attr(d$s.x, 'scaled:center')
for example:
> x <- 1:10
> s.x <- scale(x)
> s.x
            [,1]
 [1,] -1.4863011
 [2,] -1.1560120
 [3,] -0.8257228
 [4,] -0.4954337
 [5,] -0.1651446
 [6,]  0.1651446
 [7,]  0.4954337
 [8,]  0.8257228
 [9,]  1.1560120
[10,]  1.4863011
attr(,"scaled:center")
[1] 5.5
attr(,"scaled:scale")
[1] 3.02765
> s.x * attr(s.x, 'scaled:scale') + attr(s.x, 'scaled:center')
      [,1]
 [1,]    1
 [2,]    2
 [3,]    3
 [4,]    4
 [5,]    5
 [6,]    6
 [7,]    7
 [8,]    8
 [9,]    9
[10,]   10
attr(,"scaled:center")
[1] 5.5
attr(,"scaled:scale")
[1] 3.02765



ref:
http://stackoverflow.com/questions/10287545/backtransform-scale-for-plotting

If it helps, you could also try the R library:
http://www.inside-r.org/packages/cran/DMwR/docs/unscale



Thursday, 29 October 2015

Error in readRDS(file) : error reading from the connection

I met this error when I was installing the package "stringr". It is one of the dependencies if you want to install "ggplot2" package. I have this problem probably because my computer was interrupted when I was installing "ggplot2" package. But that's just a guess.

Right after the error, it prompts : "TRY removing /usr/local/lib/R/site-library/00LOCK-stringi/". So I just sudo went to that directory and rm -rf 00LOCK-stringi.

I solved the problem this way. But there are a popular ref online:
        http://stackoverflow.com/questions/6473831/readrdsfile-in-r

Try it if my solution doesn't work for you,

Wednesday, 28 October 2015

Deal with Missing Data NA in R

Firstly, Yes, there is no " " on NA.

I wrote something like
                   if(mat[i,j] == "NA"){...}

Please don't laugh at me R users...

I got my answer from the following post:
 http://stackoverflow.com/questions/27018471/r-missing-value-where-true-false-needed

comments = c("no","yes",NA)
for (l in 1:length(comments)) {
    if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"
So the function is.na is the way to do the judgement. And yes use NA directly, no need to quote.

Sunday, 25 October 2015

R problem of installing packages: package ‘xxxx’ is not available (for R version 3.2.2) and unable to access index for repository xxxx

I met this problem after re-installed the Ubuntu. I've got to set up the whole programming environment again...  :-{{

--- Please select a CRAN mirror for use in this session ---
Warning: unable to access index for repository http://cran.utstat.utoronto.ca/src/contrib
Warning message:
package ‘xxxx’ is not available (for R version 3.2.2) 

Checked something online. The following two helped...

http://stackoverflow.com/questions/25721884/how-should-i-deal-with-package-xxx-is-not-available-for-r-version-x-y-z-wa
http://stackoverflow.com/questions/25599943/unable-to-install-packages-in-latest-version-of-rstudio-and-r-version-3-1-1

Basically, just change to another mirror...I changed to one in US, didn't work either... Then Canada(BC), WORKed!!!!

Wired...but you can try the same cuz there might be many problems to the unavailability of a university server, which is usually the case for R mirrors...

Happy coding!

Friday, 23 October 2015

VIM color scheme

With "syntax on" command in configuration file "~/.vimrc", the color scheme is really unacceptable for a programmer...

There are many beautiful alternatives. Some commonly used color scheme conf files can be find in Ubuntu directary: "/usr/share/vim/vim7x/colors/" such as desert.vim and morning.vim.

We only need to, in ~/.vimrc, add:
                  colo desert 
                  syntax on

...much better now!

But if you would like to use other color conf downloaded from somewhere else, you have to put the "xxxx.vim" file under the above directary so that vi could locate it automatically.

Hope it helps!

Wednesday, 21 October 2015

Unbreakable Linux, Windows and Me: Ubuntu Builder - Installation on Ubuntu 12.04LTS

Unbreakable Linux, Windows and Me: Ubuntu Builder - Installation on Ubuntu 12.04LTS: Ubuntu Builder is a very handy and powerful tool in building a custom Ubuntu linux distro. The following steps are taken for me to succes...

Installing .deb Packages on Ubuntu and Remove it

Sometimes it is more direct to install softwares on Ubuntu using .deb packages like in Windows using setup.exe. Here are some how-to commands.

(1) Installing:
                    sudo dpkg -i xxxxxxxxxxxx.deb

(2) Find out the list of all installed packages:
                    dpkg --list
                    dpkg --list | grep -i keywords

(3) Uninstalling:
With the pack name found using the commands above, we can remove the install.
                   sudo dpkg --remove xxxxxxxx


Continuing and please comment to add more...

WiFi Certificate File Install

  Some WiFi connections require a special certificate in Ubuntu, for example: ca-bundle.crt. And here is the way to install this kind of certs in Ubuntu.

1. copy the cert file to directory: /etc/ssl/certs/
    This is the place in Ubuntu to put the cert file and in other Linux distributions it might be a little different.

2. check the permissions on the cert file.








 Sometimes the original file is with the permission as the following when it has just been downloaded:

-rw------- 1 root root 660107 Oct 21 06:43 ca-bundle.crt


However, the cert file cannot been seen for users when selecting the cert file in filling up the WiFi information. So we need to change it to:

                      -rw-r--r-- 1 root root 660107 Oct 21 06:43 ca-bundle.crt

by command:
                      chmod 644 cert-cert

It means that "I can change it and everyone else can read it".

Now back to the WiFi security table and try to find the cert file, it can be seen.

Hope it helps and happy ubunt'n!

Friday, 16 October 2015

vi getting multiple “Sorry, the command is not available in this version…”

Just re-installed Ubuntu, but I am getting the following error codes when launching vi...I am using the configuration from:
    http://jsdelfino.blogspot.ca/2010/11/my-vi-configuration-file.html

Error detected while processing /home/boris/.vimrc:
line   30:
E518: Unknown option: autochdir
line   39:
E319: Sorry, the command is not available in this version: syntax on
line   43:
E319: Sorry, the command is not available in this version: filetype indent on
line   64:
E319: Sorry, the command is not available in this version: function! RESTORE_CURSOR()
line   68:
E319: Sorry, the command is not available in this version: endfunction
line   69:
E319: Sorry, the command is not available in this version: autocmd BufReadPost * call RESTORE_CURSOR()
Press ENTER or type command to continue


Soved by using suggestions from this bbs:

Try from within vim ...
:version
and if your get ...
Small version without GUI.
You are missing package vim-gui-common. It is probably also advisable to install vim-runtime. Commands to install:
sudo apt-get install vim-gui-common
sudo apt-get install vim-runtime

Another cause might be that alternatives is pointing to the wrong one:
update-alternatives --display vim
to show what is used and ...
update-alternatives --config vim
to change to another vim. It could be that /usr/bin/vim.gnome is used and you need /usr/bin/vim

########################################################
It worked for me right after I installed vim-gui-common:
sudo apt-get install vim-gui-common


Hope this helps!