每一个错误的经验积累,就是通向成功的阶梯。
Each mistake I made shall become one of the stairs towards success.
Thursday, 20 October 2016
Friday, 14 October 2016
[Important] static variable and static global variable
There might be a time, that you DID assigned some value to an static variable, but in a function somewhere else, the change cannot be detected. For example, I met this problem when using Software Timers (Particle) whose callback functions don't take any input parameters and return values. Therefore, global/static variables are the only way of communication to the callback functions.
Here is the reason:
(1) Global variables are stored in static region.(2*) Non-static global variable and static global variable are different where non-static global variable (just defined without keyword static) can be seen in all project source files while static global variable can only be seen in the source file where it is defined.
So if I want some variables to be static and global, I should not put "static" in front of the definition otherwise functions in other source files cannot see it.
///////////////////////////////////////////////////////////////////////////////////////////////////////////
More, if coping with c++ objects...here are some tips.
(1) Dealing with Class/Object pointers:
First, variables declared as
external must be defined. So you need to haveLogger *log;
in
Logger.cpp. You can also initialize it there like this:Logger *log = new Logger();
Second, you don't need any more declarations, that is you just need to include
(2) Dealing with objectsLogger.h, no need to declare another Logger variable in Foo.h, just use log from Logger.h.In .h file:
extern Timer _timerXXX;
extern Timer _timerYYY;
extern Timer _timerZZZ;
In .cpp file:
// give inputs to the constructors
Timer _timerXXX(x1, x2);
Timer _timerYYY(y2, y2);
Timer _timerZZZ(z1, z2);
ref:
http://www.cnblogs.com/sideandside/archive/2007/03/29/692559.html
http://blog.csdn.net/ymangu666/article/details/22277673
ref more:
http://stackoverflow.com/questions/8362679/extern-pointer-initialization
Sunday, 2 October 2016
Great Vim Configuration File
Found many online, but this one is perfect for me:
My Vim Configuration:
Mono-spaced small font suitable for a small laptop screen at 1280×800
“Desert theme” with dark background, 256-color palette
Some useful keyboard mappings
Use spaces as tabs (2 spaces = 1 tab), Smart indentation
Display line-numbers, Show matching braces when hover
Display all special characters (that is generally not supported in code files)
Auto-completion
Status-line modifications
Syntax-checking upon saving for almost all languages (plugins, see below)
File skeletons upon creation (plugins, see below)
Ignore CVS-, temporary and images (etc) files and directories
Disabled annoying sounds and bells (blinking)
Configuration:
" For Pathogen plugin manager call pathogen#runtime_append_all_bundles() call pathogen#helptags() """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " Editing setings """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " Enable filetype plugin filetype plugin on filetype indent on " Filetypes and encoding set fileformats=unix,dos,mac set encoding=utf-8 set wildignore=.svn,CVS,*.o,*.a,*.class,*.mo,*.la,*.so,*.obj,*.swp,*.jpg,*.png,*.xpm,*.gif " General behaviour set autochdir " CWD is always same as current file set ai " Autoident "set si " Smartident set nowrap " Do not wrap lines set nocompatible " ViM settings instead of Vi set smartcase " Smart casing when searching set ignorecase " ... or ignore casing set hlsearch " Highlight matches set incsearch " Modern (wrapping) search set history=500 " Long undo history set tw=1000 " make backspace a more flexible set backspace=indent,eol,start " Disable sounds set vb t_vb=" set noerrorbells set visualbell
" Tabbing, Default to 2 spaces as tabs set cino=:0g0(0,W2 set expandtab set tabstop=2 set softtabstop=2 set shiftwidth=2 " Filetype sesific "au FileType python setlocal tabstop=4 softtabstop=4 shiftwidth=4 """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " User interface setings """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" syntax on colorscheme desert set showmatch " Show matching braces when over one set ruler " Always show current position set number " Always show line-numbers set numberwidth=5 " Line-number margin width set mousehide " Do not show mouse while typing set antialias " Pretty fonts set t_Co=256 " 256-color palletes set background=dark " Dark background variation of theme set guifont=Andale\ Mono\ 7.5 " Monospaced small font set guioptions-=T " TODO set guioptions+=c " TODO Console messages set linespace=0 " Don't insert any extra pixel lines set lazyredraw " Don't redraw while running macros set wildmenu " Wild menu set wildmode=longest,list,full " Wild menu options " Display special characters and helpers set list " Show < or > when characters are not displayed on the left or right. " Also show tabs and trailing spaces. set list listchars=nbsp:¬,tab:>-,trail:.,precedes:<,extends:>
" Autocompletion
set ofu=syntaxcomplete#Complete
set completeopt+=longest,menuone
highlight Pmenu guibg=brown gui=bold
let g:SuperTabDefaultCompletionType = "<C-x><C-o>"
" Statusline
set statusline=%F%m%r%h%w[%L][%{&ff}]%y[%p%%][%04l,%04v]
" | | | | | | | | | | |
" | | | | | | | | | | + current
" | | | | | | | | | | column
" | | | | | | | | | +-- current line
" | | | | | | | | +-- current % into file
" | | | | | | | +-- current syntax in
" | | | | | | | square brackets
" | | | | | | +-- current fileformat
" | | | | | +-- number of lines
" | | | | +-- preview flag in square brackets
" | | | +-- help flag in square brackets
" | | +-- readonly flag in square brackets
" | +-- rodified flag in square brackets
" +-- full path to file in the buffer
" Highlight trailing whitespaces (+ keybindings below)
highlight ExtraWhitespace ctermbg=red guibg=red
highlight ExtraWhitespace ctermbg=darkgreen guibg=darkgreen
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhitespace /\s\+$/
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Plugins
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" ViM highlighting
au BufNewFile,BufRead *.mxml set filetype=mxml
au BufNewFile,BufRead *.as set filetype=actionscript
" Highlight errors for VIM supported languages
" Supported languages are: ada, c, chill, csc, forth, groovy, icon, java, lpc, mel, nqc, nroff, ora, pascal, plm, plsql, python and ruby. The c settings also apply to cpp.
let c_space_errors = 1
let java_space_errors = 1
let python_space_errors = 1
let ruby_space_errors = 1
" NERDTree noremap <F12> :NERDTree<CR> " Tskel let tskelUserName='Anders Evenrud' let tskelUserEmail='andersevenrud@gmail.com' " Syntastic set statusline+=%#warningmsg# set statusline+=%{SyntasticStatuslineFlag()} set statusline+=%* "SyntasticEnable php "SyntasticEnable javascript "SyntasticEnable xhtml "SyntasticEnable python let g:syntastic_enable_signs=1 let g:syntastic_auto_loc_list=1 "let g:syntastic_quiet_warnings=1 " CloseTag autocmd FileType html,htmldjango,jinjahtml,eruby,mako let b:closetag_html_style=1 autocmd FileType html,xhtml,xml,htmldjango,jinjahtml,eruby,mako source ~/.vim/bundle/closetag/plugin/closetag.vim " SuperTab let g:SuperTabDefaultCompletionType = "context" """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " Key mappings """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" inoremap <expr> <Esc> pumvisible() ? "\<C-e>" : "\<Esc>" inoremap <expr> <CR> pumvisible() ? "\<C-y>" : "\<CR>" inoremap <expr> <Down> pumvisible() ? "\<C-n>" : "\<Down>" inoremap <expr> <Up> pumvisible() ? "\<C-p>" : "\<Up>" inoremap <expr> <PageDown> pumvisible() ? "\<PageDown>\<C-p>\<C-n>" : "\<PageDown>" inoremap <expr> <PageUp> pumvisible() ? "\<PageUp>\<C-p>\<C-n>" : "\<PageUp>" " RESIZE with numlock +-/* if bufwinnr(1) map + <C-W>+ map - <C-W>- endif
"<home> toggles between start of line and start of text
imap <khome> <home>
nmap <khome> <home>
inoremap <silent> <home> <C-O>:call HHome()<CR>
nnoremap <silent> <home> :call HHome()<CR>
function! HHome()
let curcol = wincol()
normal ^
let newcol = wincol()
if newcol == curcol
normal 0
endif
endfunction
"<end> goes to end of screen before end of line
imap <kend> <end>
nmap <kend> <end>
inoremap <silent> <end> <C-O>:call HEnd()<CR>
nnoremap <silent> <end> :call HEnd()<CR>
function! HEnd()
let curcol = wincol()
normal g$
let newcol = wincol()
if newcol == curcol
normal $
endif
"http://www.pixelbeat.org/patches/vim-7.0023-eol.diff
if virtcol(".") == virtcol("$") - 1
normal $
endif
endfunction
"Ctrl-{up,down} to scroll. (gvim)
if has("gui_running")
nmap <C-up> <C-y>
imap <C-up> <C-o><C-y>
nmap <C-down> <C-e>
imap <C-down> <C-o><C-e>
endif
if bufwinnr(1)
map <kPlus> <C-W>+
map <kMinus> <C-W>-
map <kDivide> <c-w><
map <kMultiply> <c-w>>
endif
" For highlighting trailing whitespaces nnoremap <Leader>wn :match ExtraWhitespace /^\s* \s*\<Bar>\s\+$/<CR> nnoremap <Leader>wf :match<CR> " space / shift-space scroll in normal mode noremap <S-space> <C-b> noremap <space> <C-f>
ref:
https://anderse.wordpress.com/2011/09/07/my-vim-gvim-configuration/
Saturday, 1 October 2016
permissions denied on serial port /dev/ttyACM0
Serial port is very commonly used when developing embedded systems such as Arduino or Particle core.
But we might encounter the following problem when trying to open the serial monitor:
Permission denied, cannot open /dev/ttyACM0
Many suggest to do:
sudo chmod 666 /dev/ttyACM0
I don't know them but it did NOT work for me. This DID:
sudo usermod -a -G dialout boris
in which boris is my username.
And call:
Maybe you gotta login again.
Ref:
http://askubuntu.com/questions/616517/dev-ttyacm0-permission-denied-error
http://askubuntu.com/questions/58119/changing-permissions-on-serial-port
But we might encounter the following problem when trying to open the serial monitor:
Permission denied, cannot open /dev/ttyACM0
Many suggest to do:
sudo chmod 666 /dev/ttyACM0
I don't know them but it did NOT work for me. This DID:
sudo usermod -a -G dialout boris
in which boris is my username.
And call:
groups boris
to check.Maybe you gotta login again.
Ref:
http://askubuntu.com/questions/616517/dev-ttyacm0-permission-denied-error
http://askubuntu.com/questions/58119/changing-permissions-on-serial-port
Open terminal by right click
Install
nautilus-open-terminal. In a terminal type:sudo apt-get install nautilus-open-terminal
Once it installs, type
nautilus -q && nautilus & to quit and reopen nautilus, and check the right click option.ref:
http://askubuntu.com/questions/293566/open-terminal-from-nautilus-by-right-click
Sunday, 25 September 2016
Make VIM into an IDE
(1) ctags
> $sudo apt-get install exuberant-ctags
> Now go to the directory with the source files, go into it, not one level out it. And use:
$ctags -R *
-R indicates recursively, which means the subdirectories are also searched. And we can see a new file naned "tags".
Here are some useful cmds for ctags:
Ctrl + ]
Ctrl + t
:tag function_name
Here are some useful cmds for ctags:
Ctrl + ]
Ctrl + t
:tag function_name
:ta function_name
ref:
http://blog.csdn.net/daniel_ustc/article/details/8299096
https://andrew.stwrt.ca/posts/vim-ctags/
ref:
http://blog.csdn.net/daniel_ustc/article/details/8299096
https://andrew.stwrt.ca/posts/vim-ctags/
Friday, 23 September 2016
Ubuntu Chinese Pingying Characters not Coming Out
When I just added Pingying Input and tried to type, there is no characters coming out for choosing. Here is the solution:
terminal$: ibus-daemon -drx
This basically re-start the ibus process.
Ubuntu Chinese Pingying Characters not Coming Out
When I just added Pingying Input and tried to type, there is no characters coming out for choosing. Here is the solution:
terminal$: ibus-daemon -drx
This basically re-start the ibus process.
Wednesday, 21 September 2016
How to use #if 0 ... #endif
#if 0
...
#endif
basically tells the compiler that there is no need to compile this part of codes.
Usage:
(1) There might be something needed LATER in the program but we don't yet know exactly how this part works. So just leave it there now without compiling it.
(2) When we want to comment a block of codes using /* ... */, but there are some other comments in this block using /* ... */, the only option we have is use #if 0 to avoid the compilation of it.
(3) Testing and debugging
#if 0
{original program...}
#else{new program...}
#endif
if we need to change back to the original program, just change the 0 back to 1.
ref:
http://www.programmer-club.com.tw/ShowSameTitleN/c/29150.html
Tuesday, 13 September 2016
Particle Photon Getting Started
Step 1:
To install Node.js, type the following command in your terminal:
1
|
sudo apt-get install nodejs
|
Then install the Node package manager, npm:
1
|
sudo apt-get install npm
|
Create a symbolic link for node, as many Node.js tools use this name to execute.
1
|
sudo ln -s /usr/bin/nodejs /usr/bin/node
|
Now we should have both the Node and npm commands working:
1
2
3
4
|
$ node -v
v0.10.25
$ npm -v
1.3.10
|
Step 2:
sudo npm install -g particle-cli
Ref:
http://www.hostingadvice.com/how-to/install-nodejs-ubuntu-14-04/#ubuntu-package-manager
https://docs.particle.io/guide/tools-and-features/cli/photon/
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Trouble shooting, after an particle-cli upgrade, I am getting two errors look like:
/usr/local/lib/node_modules/particle-cli/commands/Key Commands.js:213
and the other similar one.
This is because the node version is too old. So we have to (1) upgrade node (2) remove particle-cli (3) re-install particle-cli again.
(1) in order to install the latest node
1 Install npm:
sudo apt-get install npm- Install
n
sudo npm install n -g- Get latest version of node
sudo n latest(2) remove and re-install particle-cli
sudo npm remove -g particle-cli
sudo npm install -g particle-cli
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
I setup a brand new computer again.
Step 1:
sudo apt-get install nodejs-legacy
sudo apt-get install npm
You wont get the latest version but we are going to upgrade them in a minute.
Step 2:
Update them.
sudo npm cache clean -f
sudo npm install -g n
sudo n latest
Step 3:
bash <( curl -sL https://particle.io/install-cli )
Wait a while and that's IT!!!
ref:
https://github.com/spark/particle-cli/issues/176
http://stackoverflow.com/questions/34974535/install-latest-nodejs-version-in-ubuntu-14-04
http://www.hostingadvice.com/how-to/update-node-js-latest-version/
https://docs.particle.io/guide/tools-and-features/cli/photon/
Tuesday, 26 July 2016
C++ overload operators
Three cases are enlisted below as templates -- . More could be added later...
{
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.
(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
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.
|
|
NumberToString ( Number );
|
|
StringToNumber<Type> ( String ); But #include <sstream> must be added at the top.
ref:
http://www.cplusplus.com/articles/D9j2Nwbp/
Subscribe to:
Posts (Atom)