Wednesday, May 5, 2010

Vim for developers


set nobackup       #no backup files
set nowritebackup  #only in case you don't want a backup file while editing
set noswapfile     #no swap files

good for ref:: http://www.danielmiessler.com/study/vim/


To turn off autoindent when you paste code, there's a special "paste" mode.
Type
:set paste
Then paste your code. Note that the text in the tooltip now says -- INSERT (paste) --.
After you pasted your code, turn off the paste-mode, so that auto-indenting when you type works correctly again.
:set nopaste
Put the following in your vimrc (change to whatever key you want):
set pastetoggle=


Using VIM which terminal type is dtterm
syntax enable
"colorscheme darkblue
"colorscheme morning
colorscheme desert                 <<<<< good

Make sure ~/.vim/colors has desert.vim



show full path: press 1 then Ctrl + g

OR

set title
set laststatus=2
"""""""set statusline+=%F
set statusline+=%f



http://www.cs.rit.edu/~cslab/vi.html
http://www.lagmonster.org/docs/vi2.html

General Startup
 To use vi: vi filename
 To exit vi and save changes: ZZ   or  :wq
 To exit vi without saving changes: :q!
 To enter vi command mode: [esc]


Counts
        A number preceding any vi command tells vi to repeat
 that command that many times.





Cursor Movement

 h       move left (backspace)

 j       move down

 k       move up

 l       move right (spacebar)

 [return]   move to the beginning of the next line

 $       last column on the current line

 0       move cursor to the first column on the 
  current line

 ^       move cursor to first nonblank column on the
  current line

 w       move to the beginning of the next word or 
  punctuation mark

 W       move past the next space

 b       move to the beginning of the previous word 
  or punctuation mark

 B       move to the beginning of the previous word,
  ignores punctuation

        e       end of next word or punctuation mark

        E       end of next word, ignoring punctuation

        H       move cursor to the top of the screen 

        M       move cursor to the middle of the screen

        L       move cursor to the bottom of the screen 





Screen Movement

       G        move to the last line in the file

       xG       move to line x

       z+       move current line to top of screen

       z        move current line to the middle of screen

       z-       move current line to the bottom of screen

       ^F       move forward one screen

       ^B       move backward one line

       ^D       move forward one half screen

       ^U       move backward one half screen

       ^R       redraw screen 
  ( does not work with VT100 type terminals )

       ^L       redraw screen 
  ( does not work with Televideo terminals )





Inserting

       r        replace character under cursor with next 
  character typed

       R        keep replacing character until [esc] is hit

       i        insert before cursor

       a        append after cursor

       A        append at end of line

       O        open line above cursor and enter append mode





Deleting

 x       delete character under cursor

 dd      delete line under cursor

        dw      delete word under cursor

        db      delete word before cursor





Copying Code

        yy      (yank)'copies' line which may then be put by
  the p(put) command. Precede with a count for
  multiple lines.





Put Command
        brings back previous deletion or yank of lines,
 words, or characters

        P       bring back before cursor

        p       bring back after cursor




 Find Commands

 ?       finds a word going backwards

 /       finds a word going forwards

        f       finds a character on the line under the
  cursor going forward

        F       finds a character on the line under the
  cursor going backwards

        t       find a character on the current line going
  forward and stop one character before it

 T       find a character on the current line going
  backward and stop one character before it

 ; repeat last f, F, t, T





Miscellaneous Commands

 . repeat last command

 u undoes last command issued

 U undoes all commands on one line

 xp deletes first character and inserts after
  second (swap)

 J join current line with the next line

 ^G display current line number

 % if at one parenthesis, will jump to its mate

 mx mark current line with character x

 'x find line marked with character x

 NOTE: Marks are internal and not written to the file.





Line Editor Mode
 Any commands form the line editor ex can be issued 
 upon entering line mode.

 To enter: type ':'

 To exit: press[return] or [esc]





ex Commands
 For a complete list consult the 
 UNIX Programmer's Manual





READING FILES
 copies (reads) filename after cursor in file 
 currently editing

 :r filename





WRITE FILE

 :w  saves the current file without quitting





MOVING

 :# move to line #

 :$ move to last line of file





SHELL ESCAPE
 executes 'cmd' as a shell command.

 :!'cmd'





Vim for Perl developers

Vim tutorial

      1 "set cursorline
      2
      3 nnoremap QQ :q!
      4 nnoremap :set invpaste paste?
      5 set pastetoggle=F3
      6 set showmode
      7
      8 " enable the plugin for Vim editor.
      9 filetype plugin on
      1 " Sets how many lines of history VIM has to remember
      2 set history=1700
      3
      4 " line number
      5 set number
      6
      7 " Set to auto read when a file is changed from the outside
      8 set autoread
      9
     10 "Always show current position
     11 set ruler
     12
     13 " Configure backspace so it acts as it should act
     14 set backspace=eol,start,indent
     15 set whichwrap+=<,>,h,l
     16
     17 " Highlight search results
     18 set hlsearch
     19
     20 " Makes search act like search in modern browsers
     21 set incsearch
     22
     23 " Show matching brackets when text indicator is over them
     24 set showmatch
     25 " How many tenths of a second to blink when matching brackets
     26 set mat=2
     27
     28 " Enable syntax highlighting
     29 syntax enable
     30
     31 " Turn backup off, since most stuff is in SVN, git et.c anyway...
     32 set nobackup
     33 set nowb
     34 set noswapfile
     35
     36 " Use spaces instead of tabs
     37 set expandtab
     38
     39 " Be smart when using tabs ;)
     40 set smarttab
     41
     42 " 1 tab == 3 spaces
     43 set shiftwidth=3
     44 set tabstop=3
     45
     46 " Always show the status line
     47 set laststatus=2
     46 " Always show the status line
     47 set laststatus=2
     48 
     49 " Format the status line
     50 " set statusline=\ %{HasPaste()}%F%m%r%h\ %w\ \ CWD:\ %r%{getcwd()}%h\ \ \ Line:\ %1
     51 
     52

     61 " Taglist variables
     62 " Display function name in status bar:
     63 let g:ctags_statusline=1
     64 " Automatically start script
     65 let generate_tags=1
     66 " Displays taglist results in a vertical window:
     67 let Tlist_Use_Horiz_Window=0
     68 " Shorter commands to toggle Taglist display
     69 nnoremap TT :TlistToggle
     70 map :TlistToggle
     71 " Various Taglist diplay config:
     72 let Tlist_Use_Right_Window = 0
     73 let Tlist_Compact_Format = 1
     74 let Tlist_Exit_OnlyWindow = 1
     75 let Tlist_GainFocus_On_ToggleOpen = 1
     76 let Tlist_File_Fold_Auto_Close = 1

Sample .vimrc:

:set wrap " Text wrapping

:set number " Line numbering
:set mouse=a " Mouse active
:set tabstop=4 " Tab as 4 spaces
:set expandtab " All tabs are spaces
:set autoindent " automatically indenting your code in structures like loops and procedures.
:set shiftwidth=4 " select a block of code and change it’s indentation level
:set shiftround " indent/outdent to nearest tabstops
syntax on


hi LineNr ctermfg=darkcyan
hi LineNr ctermfg=darkred


set noswapfile

set nobackup

" show matching brackets
autocmd FileType perl set showmatch
"set foldmethod=marker
"nmap 0v/{%zf

let perl_fold=1
let perl_fold_blocks=1


Example .vimrc

.vimrc

A collection of .vimrc files

Update VIM plugin

cscope for vim:
cscope for large project: Using Cscope on large projects




Cursor movement

  • h - move left
  • j - move down
  • k - move up
  • l - move right
  • w - jump by start of words (punctuation considered words)
  • W - jump by words (spaces separate words)
  • e - jump to end of words (punctuation considered words)
  • E - jump to end of words (no punctuation)
  • b - jump backward by words (punctuation considered words)
  • B - jump backward by words (no punctuation)
  • 0 - (zero) start of line
  • ^ - first non-blank character of line
  • $ - end of line
  • G - Go To command (prefix with number - 5G goes to line 5)
Note: Prefix a cursor movement command with a number to repeat it. For example, 4j moves down 4 lines.

From http://www.worldtimzone.com/res/vi.html

Insert Mode - Inserting/Appending text

  • i - start insert mode at cursor
  • I - insert at the beginning of the line
  • a - append after the cursor
  • A - append at the end of the line
  • o - open (append) blank line below current line (no need to press return)
  • O - open blank line above current line
  • ea - append at end of word
  • Esc - exit insert mode

Editing

  • r - replace a single character (does not use insert mode)
  • J - join line below to the current one
  • cc - change (replace) an entire line
  • cw - change (replace) to the end of word
  • c$ - change (replace) to the end of line
  • s - delete character at cursor and subsitute text
  • S - delete line at cursor and substitute text (same as cc)
  • xp - transpose two letters (delete and paste, technically)
  • u - undo
  • . - repeat last command

Marking text (visual mode)

  • v - start visual mode, mark lines, then do command (such as y-yank)
  • V - start Linewise visual mode
  • o - move to other end of marked area
  • Ctrl+v - start visual block mode
  • O - move to Other corner of block
  • aw - mark a word
  • ab - a () block (with braces)
  • aB - a {} block (with brackets)
  • ib - inner () block
  • iB - inner {} block
  • Esc - exit visual mode

Visual commands

  • > - shift right
  • < - shift left
  • y - yank (copy) marked text
  • d - delete marked text
  • ~ - switch case

Cut and Paste

  • yy - yank (copy) a line
  • 2yy - yank 2 lines
  • yw - yank word
  • y$ - yank to end of line
  • p - put (paste) the clipboard after cursor
  • P - put (paste) before cursor
  • dd - delete (cut) a line
  • dw - delete (cut) the current word
  • x - delete (cut) current character

Exiting

  • :w - write (save) the file, but don't exit
  • :wq - write (save) and quit
  • :q - quit (fails if anything has changed)
  • :q! - quit and throw away changes

Search/Replace

  • /pattern - search for pattern
  • ?pattern - search backward for pattern
  • n - repeat search in same direction
  • N - repeat search in opposite direction
  • :%s/old/new/g - replace all old with new throughout file
  • :%s/old/new/gc - replace all old with new throughout file with confirmations

Working with multiple files

  • :e filename - Edit a file in a new buffer
  • :bnext (or :bn) - go to next buffer
  • :bprev (of :bp) - go to previous buffer
  • :bd - delete a buffer (close a file)
  • :sp filename - Open a file in a new buffer and split window
  • ctrl+ws - Split windows
  • ctrl+ww - switch between windows
  • ctrl+wq - Quit a window
  • ctrl+wv - Split windows vertically
http://amix.dk/vim/vimrc.html


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Maintainer: 
"       Amir Salihefendic
"       http://amix.dk - amix@amix.dk
"
" Version: 
"       5.0 - 29/05/12 15:43:36
"
" Blog_post: 
"       http://amix.dk/blog/post/19691#The-ultimate-Vim-configuration-on-Github
"
" Awesome_version:
"       Get this config, nice color schemes and lots of plugins!
"
"       Install the awesome version from:
"
"           https://github.com/amix/vimrc
"
" Syntax_highlighted:
"       http://amix.dk/vim/vimrc.html
"
" Raw_version: 
"       http://amix.dk/vim/vimrc.txt
"
" Sections:
"    -> General
"    -> VIM user interface
"    -> Colors and Fonts
"    -> Files and backups
"    -> Text, tab and indent related
"    -> Visual mode related
"    -> Moving around, tabs and buffers
"    -> Status line
"    -> Editing mappings
"    -> vimgrep searching and cope displaying
"    -> Spell checking
"    -> Misc
"    -> Helper functions
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => General
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Sets how many lines of history VIM has to remember
set history=700

" Enable filetype plugins
filetype plugin on
filetype indent on

" Set to auto read when a file is changed from the outside
set autoread

" With a map leader it's possible to do extra key combinations
" like w saves the current file
let mapleader = ","
let g:mapleader = ","

" Fast saving
nmap <leader>w :w!<cr>


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => VIM user interface
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Set 7 lines to the cursor - when moving vertically using j/k
set so=7

" Turn on the WiLd menu
set wildmenu

" Ignore compiled files
set wildignore=*.o,*~,*.pyc

"Always show current position
set ruler

" Height of the command bar
set cmdheight=2

" A buffer becomes hidden when it is abandoned
set hid

" Configure backspace so it acts as it should act
set backspace=eol,start,indent
set whichwrap+=<,>,h,l

" Ignore case when searching
set ignorecase

" When searching try to be smart about cases 
set smartcase

" Highlight search results
set hlsearch

" Makes search act like search in modern browsers
set incsearch

" Don't redraw while executing macros (good performance config)
set lazyredraw

" For regular expressions turn magic on
set magic

" Show matching brackets when text indicator is over them
set showmatch
" How many tenths of a second to blink when matching brackets
set mat=2

" No annoying sound on errors
set noerrorbells
set novisualbell
set t_vb=
set tm=500


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Colors and Fonts
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Enable syntax highlighting
syntax enable

colorscheme desert
set background=dark

" Set extra options when running in GUI mode
if has("gui_running")
    set guioptions-=T
    set guioptions+=e
    set t_Co=256
    set guitablabel=%M\ %t
endif

" Set utf8 as standard encoding and en_US as the standard language
set encoding=utf8

" Use Unix as the standard file type
set ffs=unix,dos,mac


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Files, backups and undo
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Turn backup off, since most stuff is in SVN, git et.c anyway...
set nobackup
set nowb
set noswapfile


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Text, tab and indent related
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Use spaces instead of tabs
set expandtab

" Be smart when using tabs ;)
set smarttab

" 1 tab == 4 spaces
set shiftwidth=4
set tabstop=4

" Linebreak on 500 characters
set lbr
set tw=500

set ai "Auto indent
set si "Smart indent
set wrap "Wrap lines


""""""""""""""""""""""""""""""
" => Visual mode related
""""""""""""""""""""""""""""""
" Visual mode pressing * or # searches for the current selection
" Super useful! From an idea by Michael Naumann
vnoremap <silent> * :call VisualSelection('f')<CR>
vnoremap <silent> # :call VisualSelection('b')<CR>


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Moving around, tabs, windows and buffers
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Treat long lines as break lines (useful when moving around in them)
map j gj
map k gk

" Map  to / (search) and Ctrl- to ? (backwards search)
map <space> /
map <c-space> ?

" Disable highlight when  is pressed
map <silent> <leader><cr> :noh<cr>

" Smart way to move between windows
map <C-j> <C-W>j
map <C-k> <C-W>k
map <C-h> <C-W>h
map <C-l> <C-W>l

" Close the current buffer
map <leader>bd :Bclose<cr>

" Close all the buffers
map <leader>ba :1,1000 bd!<cr>

" Useful mappings for managing tabs
map <leader>tn :tabnew<cr>
map <leader>to :tabonly<cr>
map <leader>tc :tabclose<cr>
map <leader>tm :tabmove

" Opens a new tab with the current buffer's path
" Super useful when editing files in the same directory
map <leader>te :tabedit <c-r>=expand("%:p:h")<cr>/

" Switch CWD to the directory of the open buffer
map <leader>cd :cd %:p:h<cr>:pwd<cr>

" Specify the behavior when switching between buffers 
try
  set switchbuf=useopen,usetab,newtab
  set stal=2
catch
endtry

" Return to last edit position when opening files (You want this!)
autocmd BufReadPost *
     \ if line("'\"") > 0 && line("'\"") <= line("$") |
     \   exe "normal! g`\"" |
     \ endif
" Remember info about open buffers on close
set viminfo^=%


""""""""""""""""""""""""""""""
" => Status line
""""""""""""""""""""""""""""""
" Always show the status line
set laststatus=2

" Format the status line
set statusline=\ %{HasPaste()}%F%m%r%h\ %w\ \ CWD:\ %r%{getcwd()}%h\ \ \ Line:\ %l


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Editing mappings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Remap VIM 0 to first non-blank character
map 0 ^

" Move a line of text using ALT+[jk] or Comamnd+[jk] on mac
nmap <M-j> mz:m+<cr>`z
nmap <M-k> mz:m-2<cr>`z
vmap <M-j> :m'>+<cr>`mzgv`yo`z
vmap <M-k> :m'<-2 class="Special" span="span" style="color: #e0c060;"><
cr>`>my`if has("mac") || has("macunix") nmap <D-j> <M-j> nmap <D-k> <M-k> vmap <D-j> <M-j> vmap <D-k> <M-k> endif " Delete trailing white space on save, useful for Python and CoffeeScript ;) func! DeleteTrailingWS() exe "normal mz" %s/\s\+$//ge exe "normal `z" endfunc autocmd BufWrite *.py :call DeleteTrailingWS() autocmd BufWrite *.coffee :call DeleteTrailingWS() """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " => vimgrep searching and cope displaying """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " When you press gv you vimgrep after the selected text vnoremap <silent> gv :call VisualSelection('gv')<CR> " Open vimgrep and put the cursor in the right position map <leader>g :vimgrep // **/*.<left><left><left><left><left><left><left> " Vimgreps in the current file map <leader><space> :vimgrep // <C-R>%<C-A><right><right><right><right><right><right><right><right><right> " When you press r you can search and replace the selected text vnoremap <silent> <leader>r :call VisualSelection('replace')<CR> " Do :help cope if you are unsure what cope is. It's super useful! " " When you search with vimgrep, display your results in cope by doing: " cc " " To go to the next search result do: " n " " To go to the previous search results do: " p " map <leader>cc :botright cope<cr> map <leader>co ggVGy:tabnew<cr>:set syntax=qf<cr>pgg map <leader>n :cn<cr> map <leader>p :cp<cr> """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " => Spell checking """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " Pressing ,ss will toggle and untoggle spell checking map <leader>ss :setlocal spell!<cr> " Shortcuts using map <leader>sn ]s map <leader>sp [s map <leader>sa zg map <leader>s? z= """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " => Misc """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " Remove the Windows ^M - when the encodings gets messed up noremap <Leader>m mmHmt:%s/<C-V><cr>//ge<cr>'tzt'm " Quickly open a buffer for scripbble map <leader>q :e ~/buffer<cr> " Toggle paste mode on and off map <leader>pp :setlocal paste!<cr> """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " => Helper functions """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" function! CmdLine(str) exe "menu Foo.Bar :" . a:str emenu Foo.Bar unmenu Foo endfunction function! VisualSelection(direction) range let l:saved_reg = @" execute "normal! vgvy" let l:pattern = escape(@", '\\/.*$^~[]') let l:pattern = substitute(l:pattern, "\n$", "", "") if a:direction == 'b' execute "normal ?" . l:pattern . "^M" elseif a:direction == 'gv' call CmdLine("vimgrep " . '/'. l:pattern . '/' . ' **/*.') elseif a:direction == 'replace' call CmdLine("%s" . '/'. l:pattern . '/') elseif a:direction == 'f' execute "normal /" . l:pattern . "^M" endif let @/ = l:pattern let @" = l:saved_reg endfunction " Returns true if paste mode is enabled function! HasPaste() if &paste return 'PASTE MODE ' en return '' endfunction " Don't close window, when deleting a buffer command! Bclose call <SID>BufcloseCloseIt() function! BufcloseCloseIt() let l:currentBufNum = bufnr("%") let l:alternateBufNum = bufnr("#") if buflisted(l:alternateBufNum) buffer # else bnext endif if bufnr("%") == l:currentBufNum new endif if buflisted(l:currentBufNum) execute("bdelete! ".l:currentBufNum) endif endfunction





Tuesday, April 27, 2010

security awareness test





Ericsson Test


Tags: Ericsson, test, Security

Perl programming: system() cmd


Link ref:
String matching




Problem:

You need to use a user's input as part of a command, but you don't want to allow the user to make the shell run other commands or look at other files. If you just blindly call the system function or backticks on a single string containing a command line, the shell might be used to run the command. This would be unsafe.

Solution:
Unlike its single-argument version, the list form of the system function is safe from shell escapes. When the command's arguments involve user input from a form, never use this:

system("command $input @files"); # UNSAFE

Write it this way instead:

system("command", $input, @files); # safer

Thursday, April 8, 2010

build cmd




Programming in C
+ Marshall
umc:/vol/tmp/boot/liu.ini
/home/fhanka/Fnet/workIntOAM/umc_init_72.t

*.cc; *.h; *.c

cd /vobs/1bts_V1
cd /vobs/fw_V1

SIMENV for older release

View manager: vmgr &

serial -t 1bts70 liu
telnet 135.246.193.204 2002
serial -t 1bts71 liu
telnet 135.246.193.204 2018
serial -t 1bts72 liu
telnet 135.246.193.204 2026
serial 1bts78 liu

route add




If you want to access directly to Twiki using IE, FF on window desktop, please following these steps:




- open hosts file at folder: C:\WINDOWS\system32\drivers\etc



- add this statement: 10.128.208.102 btswww.nt.grp



- save and load this link for TWiki: http://btswww.nt.grp/NbgSwDevelopment/bin/login/Main, this link for load plan: http://btswww.nt.grp/NbgSwDevelopment/bin/view/ProjectManagement/WebHome



P/s: In case you don’t route to Nbg site please run this command first:



Open command line (Start -> Run -> cmd) and add the route to Nbg by command:



route -p add 10.128.0.0 mask 255.255.0.0 10.128.240.1





bashrc configuration



# .bashrc


# User specific aliases and functions

# Source global definitions
[ -f /etc/bashrc ] && . /etc/bashrc

#######################################
# user specific environment
#######################################

# for mc, cvs, svn, ...
export EDITOR=vim

# vim and gnome-terminal have support for 256 colours in fedora 8 at least
# Note debian/ubuntu users should install the ncurses-term package to support this
export TERM=xterm-256color

# setup default search path for python modules.
# Note we add this to the 'path' in .vimrc so the gf
# command will open any .py or .h files etc. in this dir
export PYTHONPATH=~/pb.o/libs/

#######################################
# change app defaults
#######################################

# highlight $HOST:$PWD prompt
PS1='\[\e[1m\]\h:\w\$\[\e[0m\] '

# Don't store duplicate adjacent items in the history
HISTCONTROL=ignoreboth

# adjust settings according to current terminal window width
# which may have changed while the last command was running
# (which is a common occurance for vim/less/etc.)
# Note this is already set in /etc/bashrc on Fedora 8 at least.
shopt -s checkwinsize

# GREP_COLOR=bright yellow on black bg.
# use GREP_COLOR=7 to highlight whitespace on black terminals
# LANG=C for speed. See also: http://www.pixelbeat.org/scripts/findrepo
alias grep='GREP_COLOR="1;33;40" LANG=C grep --color=auto'

alias ls="BLOCK_SIZE=\'1 ls --color=auto" #enable thousands grouping and colour
alias minicom='minicom -c on' #enable colour
alias cal='cal -3' #show 3 months by default
alias units='units -t' #terse mode
alias diff='LC_ALL=C TZ=GMT0 diff -Naur' #normalise diffs for distribution
alias lynx='lynx -force_html -width=$COLUMNS' #best settings for viewing HTML
alias links='links -force-html' #need to enable colour in config menu manually
alias xterm='xterm -fb "" -bg black -fg gray -fa "Sans Mono" -fs 10 +sb -sl 3000 -g 80x50+1+1'
alias sudo='sudo env PATH=$PATH' #work around sudo built --with-secure-path (ubuntu)
alias vim='vim -X' #don't try to contact xserver (which can hang on network issues)
alias gdb='gdb -tui' #enable the text window interface if possible

# I hate noise
set bell-style visible

# Tell less not to beep and also display colours
export LESS="-QR"

# Let me have core dumps
ulimit -c unlimited

#######################################
# shortcut aliases
#######################################

#just list directories
alias lld='ls -lUd */'

#what most people want from od (hexdump)
alias hd='od -Ax -tx1z -v'

# canonicalize path (including resolving symlinks)
alias realpath='readlink -f'

# make and change to a directory
md () { mkdir -p "$1" && cd "$1"; }

# quick dir listing with latest files/dirs at the bottom,
# prettify symlink arrows.
# using eval to precompute the tput sequences.
eval "
l() {
ls -lrt --color=always \"\$@\"

sed 's/ -> / $(tput bold)▪▶$(tput sgr0) /'
}"
 
 

srcCp




#!/usr/bin/sh


#DIRs="/uvobs"

echo Start searching files with patterns .............

echo "Starting time: `date`"

SROOT="/uvobs/1btsptf/core"

DIRs="$SROOT/rmt_app $SROOT/oam $SROOT/hdr $SROOT/usl"

for dir in $DIRs

do

echo Searching in $dir ...

find $dir \( -name '*.h' -o -name '*.c' -o -name '*.cpp' -o -name '*.hpp' -o -name '*.cc' -o -name '*.lh' \) -type f -exec cp -f --parents {} . \;

echo `date`

done

echo "Ending time: `date`"

echo Creating tarball ...

tar czf uvobs.tgz uvobs

echo Done! uvobs.tgz created.
 
 
 
Tags: source, Copy, bash, patterns

Wednesday, April 7, 2010

Clearcase useful commands




File: $HOME/.bashrc


alias ct=/usr/atria/bin/cleartool
alias sv='/usr/atria/bin/cleartool setview'
umask 022

See more
Tags: clearcase, setview, cleartool, bashrc


Bash useful command





1. /etc/profile.       Executed automatically at login. 
2. The first file found from this list:  ̃/.bash_profile,  ̃/.bash_login, or ̃/.pro- 
file. Executed automatically at login. 
3.  ̃/.bashrc is read by every nonlogin shell. However, if invoked assh, Bash instead 
reads $ENV,for POSIX compatibility.

Filename Metacharacters 
* Match any string of zero or more characters. 
? Match any single character. 
[abc...] Match any one of the enclosed characters; a hyphen can specify a range (e.g.,a-z,A-Z,0–9).  
[!abc...] Match any character not enclosed as above. 

 ̃           Home directory of the current user. 
 ̃name Home directory of user 'name'. 
 ̃+        Current working directory ($PWD). 
 ̃-         Previous working directory ($OLDPWD).




Redirection using file descriptors 
cmd>&n         Send cmd output to file descriptor n. 
cmd m>&n     Same as previous, except that output that would normally go to file descriptor  
                         m is sent to file descriptor n instead. 
cmd>&-           Close standard output. 
cmd<&n          Take input for cmd from file descriptor n. 
cmd m<&n       Same as previous, except that input that would normally come from file
                          descriptor m comes from file descriptor n instead. 
cmd<&-            Close standard input. 
cmd<&n-         Move input file descriptor n instead of duplicating it. 
cmd>&n-        Move output file descriptor n instead of duplicating it. 
Multiple redirection 
cmd2>file       Send standard error to file standard output remains the same 
                       (e.g., the screen). 
cmd>file2>&1      Send both standard error and standard output to file. 
cmd&>file       Same as previous. Preferred form. 
cmd>&file       Same as previous. 
cmd>f1 2>f2    Send standard output to file f1 and standard error to file f2. 
cmd | tee files    Send output of cmd to standard output (usually the terminal) and 
                            to files.  
cmd 2>&1 | tee files Send standard output and error output of cmd to standard output 
                                     (usually the terminal) and to files. 


stty -a | grep erase

Create a file, /etc/inputrc for system wide use or ~/.inputrc for personal use. Actually, this is the readline initialization file, readline is a library that some programs (bash, kvt) use to read input (try bind -v to see a list of readline key and function bindings). Cut and paste the following in the file to make the Delete key delete characters under the cursor, and make Home and End work as well:


"\e[3~": delete-char
# this is actually equivalent to "\C-?": delete-char
# VT
"\e[1~": beginning-of-line
"\e[4~": end-of-line
# kvt
"\e[H":beginning-of-line
"\e[F":end-of-line
# rxvt and konsole (i.e. the KDE-app...)
"\e[7~":beginning-of-line
"\e[8~":end-of-line

Remove tab and spaces
sed 's/[\t]//g' test.txt > out.txt
sed 's/[\x09]//g' test.txt > out.txt

Zip and Unzip
tar cvf - filenames

gzip > file.tar.gz
gtar cvzf file.tar.gz filenames
tar -pczf uvobs.tar.gz /uvobs/1btsptf/core
gzip -cd mc-4.7.0.4.tar.gz | tar xfv -

Tags: Tab, Delete. Home, End



puTTY multiple sessions




E:\Downloads\putty.exe -load "session_name"
E:\Downloads\pageant.exe E:\fullpath\private.ppk

See more (http://www.unixwiz.net/techtips/putty-openssh.html)

putty with timestamp:
E:\x86tool\utilities\putty-dekt1-&h-&y-&m-&d-&t.log
E:\x86tool\utilities\puttylog-&h-&y&m&d-&t.log

TimeStamp Format

specifierReplaced byExample
%aAbbreviated weekday name *Thu
%AFull weekday name *Thursday
%bAbbreviated month name *Aug
%BFull month name *August
%cDate and time representation *Thu Aug 23 14:55:02 2001
%dDay of the month (01-31)23
%HHour in 24h format (00-23)14
%IHour in 12h format (01-12)02
%jDay of the year (001-366)235
%mMonth as a decimal number (01-12)08
%MMinute (00-59)55
%pAM or PM designationPM
%SSecond (00-61)02
_MILMilliseconds (000-999)678
%UWeek number with the first Sunday as the first day of week one (00-53)33
%wWeekday as a decimal number with Sunday as 0 (0-6)4
%WWeek number with the first Monday as the first day of week one (00-53)34
%xDate representation *08/23/01
%XTime representation *14:55:02
%yYear, last two digits (00-99)01
%YYear2001
%ZTimezone name or abbreviationCDT
%%% sign%

Tags: putty, secure, ssh, OpenSSH, Unix access

Monday, April 5, 2010

back up a Karaoke cd+g disk




Karaoke disks are not like your normal audio cd's. It is the graphic part that is the hardest to copy. The first thing you need is a reader and or writer that likes Karaoke discs. Alot do not.


Very few cd roms read Karaoke cd's. I have not yet found one that does. I have to use my writer to READ and write the karaoke disks. Tested models are sony CRX120/140/160 series. Most Yamaha writers plus most lite-on writers will.

Next is the sofware you need. CDRWIN is excellent software (shouldn't be saying that on a clone cd forum). However, CloneCD will do it.

Friday, April 2, 2010

PLEX and AXE system




PLEX (Programming Language for EXchanges) is a special-purpose, pseudo-parallel and event-driven real-time programming language. Dedicated for AXE telephone exchanges, it was developed by Göran Hemdahl at Ericsson. Originally designed in the 1970s, it has been continuously evolving since then. The language has two variants: Plex-C used for AXE Central Processors (CP) and Plex-M used for Extension Module Regional Processors (EMRP).

Clearcase Client Commands





Configure user aliases:
File: $HOME/.bashrc

alias ct=/usr/atria/bin/cleartool
alias sv='/usr/atria/bin/cleartool setview'
umask 022

File: $HOME/.cshrc

alias ct /usr/atria/bin/cleartool
alias sv '/usr/atria/bin/cleartool setview'
umask 022


alias .. 'cd ..'
alias ... 'cd ../..'

alias shw 'ct lsco -rec -me -cview /vobs/HW'
alias sst 'ct lsco -rec -me -cview /vobs/HWStage'

alias ll 'ls -alt --color=auto'
alias ct 'cleartool'
alias ctll 'ct ls'
alias ctsv '/home/xviengu/bin/ctsv.sh'
alias ctrv 'ct rmview -tag'
alias sv 'ct setview'
alias ev 'ct endview'
alias scs 'ct setcs'
alias ccs 'ct catcs'
alias edcs 'ct edcs'
alias pwv 'ct pwv'
alias myview 'cleartool lsview | grep $USER'

cleartool lsview -long xviengu_apz15_dummy
[xviengu@seasx031 /home/xviengu]# cleartool lsview -long xviengu_apz15_dummy
Tag: xviengu_apz15_dummy
  Global path: /cc/seasna06_view11/xviengu_apz15_dummy.vws
  Server host: seasx012.rnd.as.sw.ericsson.se
  Region: ASUAB
  Active: NO
  View tag uuid:0e8a50d0.d4f111df.96e5.00:01:84:85:db:c4
View on host: seasx012.rnd.as.sw.ericsson.se
View server access path: /cc/seasna06_view11/xviengu_apz15_dummy.vws
View uuid: 0e8a50d0.d4f111df.96e5.00:01:84:85:db:c4
View owner: rnd.as.sw.ericsson.se/xviengu


cleartool rmview -vob /cc/seasna06_view11/ -uuid 0e8a50d0.d4f111df.96e5.00:01:84:85:db:c4


cleartool rmtag -view xviengu_apz15_dummy  <========== good
ct unregister -view /cc/seasna06_view11/xviengu_apz15_dummy.vws





See more: http://www.yolinux.com/TUTORIALS/ClearcaseCommands.html
https://publib.boulder.ibm.com/infocenter/cchelp/v7r1m2/index.jsp?topic=/com.ibm.rational.clearcase.ccrc.help.doc/topics/u_ccchangeset.htm

Tags: Clearcase commands, cmd, alias, cleartool, setview


Thursday, April 1, 2010

Disposable email services




Guerrilla Mail: disposable e-mail addresses which expire after 15 Minutes.


http://10minutemail.com/

http://www.mailinator.com/

http://www.mintemail.com/

https://addons.mozilla.org/vi/firefox/tag/disposable%20email
 
 
Tags: disposable, e-mail addresses, disposable e-mail addresses, Guerrilla Mail, 10minutemail, mailinator, mintemail
 
 

PLEX-C programming language




PLEX is an acronym for Programming Language for EXchanges and is a highlevel language developed by Ericsson in the 1970s, and extended in 1983. Programs in the AXE central processors use the Plex version Plex-C. The EMRP, which controls the subscriber stage, runs programs in Plex-M, a different dialect of Plex.

Plex is a high-level, real-time, language with very strict requirements regarding execution time.

Monday, March 29, 2010

DeviceIoControl





DeviceIoControl Function: Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.

Serial: CRT debug report




Report type: _CRT_WARN, _CRT_ERROR, _CRT_ASSERT

Required Header: crtdbg.h

_CRT_WARN: Warnings, messages, and information that does not need immediate attention.
_CRT_ERROR: Errors, unrecoverable problems, and issues that require immediate attention.
_CRT_ASSERT: Assertion failures (asserted expressions that evaluate to FALSE).

Serial: DCB structure




DCB sructure detects the management settings for the serial port of the connection device.

The most critical phase in serial communications programming is configuring the port settings with the DCB structure.

Thursday, March 25, 2010

Do not apply pointer arithmetic to pointers





Pointer arithmetic shall only be applied to pointers that address an array or array element (misra2004_17_1_PointerArithmeticOnNotPointers.rule)


Description:

"Pointer arithmetic shall only be applied to pointers that address an array or array element. Addition and subtraction of integers (including increment and decrement) from pointers that do not point to an array or array element results in undefined behaviour."

Benefits:

Rule makes the code more readable and less confusing.

Example:

void foo( int a[] ) {
   int* p1 = 0;
   int* p2;
   int* p3 = a;

   a++;     // OK
   p1++;    // Violation
   p2 = a;
   p2++;    // OK
   p3++;    // OK
}

Repair:

Do not apply pointer arithmetic to pointers.

References:
MISRA-C:2004 Guidelines for the use of the C language in critical systems

Chapter 6, Section 17
Author
ParaSoft


Tags: Pointer arithmetic, less confusing, more readable
 

switch shall have at least one case




Every switch statement shall have at least one case clause (misra2004_15_5_AvoidSwitchWithNoCase.rule)


Description

Every switch statement shall have at least one case.

Benefits:

Provides maintainability of 'switch' statement.

Example:

void foo(int i)
{

   switch(i)      /* Violation */
   {

       default:
           ;
   }

}

Repair:

void foo(int i)
{
   switch(i)      /* OK */
   {
     case 1:
     {

     }
     default:
           ;

   }

}

References:

MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 15

Author
ParaSoft
 
 
 
Tags: switch, case, maintainability, Guidelines, critical systems
 
 

Do not convert pointer to pointer




A cast should not be performed between a pointer to object type and a different pointer to object type (misra2004_11_4_DoNotConvertPointerToPointer.rule)


Description:

"A cast should not be performed between a pointer to object type and a different pointer to object type. Conversions of this type may be invalid if the new pointer type requires a stricter alignment."

Note: This rule skips casting of void type.

Benefits:

Prevents incorrect pointer alignment.

Example:

void foo( ) {
   int* pi;
   char* i;

   i = (char*) pi; // Violation
   i = (char*) &i; // Violation
}

Repair:

Do not convert pointer to different pointer.

References:
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 11

Author
ParaSoft


Tags: cast, pointer, void, pointer alignment, MISRA, critical systems


Avoid using unsafe string functions




Avoid using unsafe string functions (UsageOfStringFunctions.rule)


Description

This rule detects code that uses unsafe string functions from C library.

Benefits:

Prevents the use of functions which may cause buffer overflows.

According to David A. Wheeler (see reference below), "C functions users must avoid using dangerous functions that do not check bounds unless they've ensured that the bounds will never get exceed.

Functions to avoid in most cases (or ensure protection) include the functions strcpy(), strcat(), sprintf() (with cousin vsprintf()), and gets().

These should be replaced with functions such as strncpy(), strncat(), snprintf(), fgets(), respectively."

Example:

#include
void main( void )
{
char* str1 = "testcase";
char* str2 = "testcase";
char* str3=0;

str3 = strcat( str1, str2 ); // Violation
}

Repair:

#include
void main( void )
{
char* str1 = "testcase";
char* str2 = "testcase";
char* str3=0;

str3 = strncat( str1, str2, 16 ); // OK
}

References:
http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/dangers-c.html

Author
ParaSoft


Tags: Avoid, unsafe, string, function, unsafe string, C library, buffer overflows, dangerous functions, strncpy, strncat, snprintf, fgets


Wednesday, March 24, 2010

Modular programming in C




What is Modular programming ?

- A programming technique to break down program functions into separate modules/parts/layers.
- Module, have to accomplishes one function by containing the source codes and input/output variables needed to accomplish that function.

Tuesday, March 23, 2010

Do NOT check floats for equality




Don't check floats for equality; check for greater than or less than (EqualityFloatLeft.rule)


Description:
This rule checks whether you check floats for equality instead of checking for greater than or less than.

Benefits:

If you check floats for equality, you make your code more susceptible to rounding errors.

Example:

void func(float a, int b)
{
   if (a==b) { }     // Violation

   while (a!=b) { }  // Violation
}



Repair:

void func(float a, int b)
{
   if (a>=b) { }     // OK

   while (a<=b) { }  // OK
}

Author
ParaSoft


My comment for repairing:

void func(const float a, const int b)
{
    if ( a > b ) { }
    else if ( a < b ) {}
    else {}
    // while (a > b) { };
    // while (a < b) { };
}

Ref: http://www.c-faq.com/fp/fpequal.html
Tags: vav.vn, vav, float, float equality, check float values equality, floating point, absolute, epsilon






domain co.cc




http://www.zebrazone.co.cc/,
http://www.fansipan.co.cc/,
http://www.zebrazoo.co.cc/

altonjuve_shift_2_yahoo_dot_com



Avoid Directly Access Globals




Do not directly access global data from a constructor (AvoidDirectlyAccessGlobals.rule)


Description:

Directly accessing global data from a constructor is risky because the global object may not yet exist when the "other" static object is initialized. This rule detects if you directly access global data from a constructor.

Function call order




The value of an expression shall be the same under any order of evaluation that the standard permits (misra2004_12_2_4_FunctionsCallOrder.rule)


Description

"Apart from a few operators (notably the function call operator (), &&, , ?: and , (comma)) the order in which sub-expressions are evaluated is unspecified and can vary. This means that no reliance can be placed on the order of evaluation of sub-expressions, and in particular no reliance can be placed on the order in which side effects occur. Those points in the evaluation of an expression at which all previous side effects can be guaranteed to have taken place are called “sequence points”. Sequence points and side effects are described in sections 5.1.2.3, 6.3 and 6.6 of ISO 9899:1990 [2].

Note that the order of evaluation problem is not solved by the use of parentheses, as this is not a precedence issue." "Functions may have additional effects when they are called (e.g. modifying some global data). Dependence on order of evaluation could be avoided by invoking the function prior to the expression that uses it, making use of a temporary variable for the value.

Monday, March 22, 2010

Avoid indexing pointer




Array indexing shall be the only allowed form of pointer arithmetic (misra2004_17_4_AvoidIndexingPointerAsArray.rule)


Description:

"Array indexing is the only acceptable form of pointer arithmetic, because it is clearer and hence less error prone than pointer manipulation. This rule bans the explicit calculation of pointer values. Array indexing shall only be applied to objects defined as an array type. Any explicitly calculated pointer value has the potential to access unintended or invalid memory addresses. Pointers may go out of bounds of arrays or structures, or may even point to effectively arbitrary locations."

Drawbacks: For more complex code rule may not be able to check if there is indexed pointer which points to array. For such cases the rule may report false positives.

Dev-cpp: stray '\160' in program




The message "stray '\160' in program" when building by Dev-Cpp is occurred when using "Copy and Paste" action.

So, finally, DO NOT copy and paste source code. Please type line by line.


Avoid assignment in if




Avoid assignment in if statement condition (IfAssign.rule)


Description:

This rule checks whether your code has assignment within an if statement condition. This rule is enabled by default.

Benefits:

Legibility and maintainability.

Assignment in the context of an if statement is easily confused with equality.

Example:

void foo(int a, int b) {

  if ( a = b ) {}  // Violation

}

Repair:

void foo(int a, int b) {

  if ( a == b ) {} // OK
}

Author
ParaSoft




Avoid nested assignment statements





The value of an expression shall be the same under any order of evaluation that the standard permits (misra2004_12_2_5_AvoidNestedAssignment.rule)


Description

"Apart from a few operators (notably the function call operator (), &&, , ?: and , (comma)) the order in which sub-expressions are evaluated is unspecified and can vary. This means that no reliance can be placed on the order of evaluation of sub-expressions, and in particular no reliance can be placed on the order in which side effects occur. Those points in the evaluation of an expression at which all previous side effects can be guaranteed to have taken place are called “sequence points”. Sequence points and side effects are described in sections 5.1.2.3, 6.3 and 6.6 of ISO 9899:1990 [2].

Note that the order of evaluation problem is not solved by the use of parentheses, as this is not a precedence issue."

"Assignments nested within expressions cause additional side effects. The best way to avoid any chance of this leading to a dependence on order of evaluation is to not embed assignments within expressions.

For example, the following is not recommended:

x = y = y = z / 3;

x = y = y++;"

Benefits:

Rule prevents evaluation of expression dependent on compiler version.

Example:

void foo( int x, int y, int z ) {

   x = y = z / 3;  // Violation
}

Repair:

void foo( int x, int y, int z ) {
   y = z / 3;  // OK
   x = y;      // OK
}

References:

MISRA-C:2004 Guidelines for the use of the C language in critical systems

Chapter 6, Section 12

Author
ParaSoft

Struct vs Union




A structure is a collection of items of different types; and each data item will have its own memory location.

An union allocates for each item in a shared memory location i.e., only one memory location will be shared by the data items of union. Size of union will be the size of the biggest variable.





Do not reuse typedef names




Do not reuse typedef names (misra2004_5_3_DoNotReuseTypedefNames.rule)


Description

Typedef names shall not be reused.

Benefits:

Reuse of typedef names can lead to errors and confusion.

Example:

typedef int MyInt;
void foo()
{
 double MyInt;  /* Violation */
}

Repair:
typedef int MyInt;
void foo()
{
 double MyVar;  /* OK */
}

References:

MISRA-C:2004 Guidelines for the use of the C language in critical systems

Chapter 6, Section 5

Author
ParaSoft



Do not mix bit-fields




Do not mix bit-fields other data within the same structure (misra2004_3_5_BitFieldStructuresWithoutOtherData.rule)


Description

It is recommended that structures should be declared specifically to hold the sets of bit fields, and do not include any other data within the same structure.

Benefits:

Rule prevents from the potential pitfalls and areas of implementation-defined (i.e.non-portable) behaviour.

Example:

struct message {  /* Violation */
   signed int little: 4;
   unsigned int x_set: 1;

   int size;
};

Repair:

struct message {  /* OK */
   signed int little: 4;
   unsigned int x_set: 1;
};

References:

MISRA-C:2004 Guidelines for the use of the C language in critical systems

Chapter 6, Section 3

Author
ParaSoft


error information shall be tested




Violations:
misra2004-16_10: If a function returns error information, then that error information shall be tested

Description:

"A function (whether it is part of the standard library, a third party library or a user defined function) may provide some means of indicating the occurrence of an error. This may be via an error flag, some special return value or some other means. Whenever such a mechanism is provided by a function the calling program shall check for the indication of an error as soon as the function returns.

However, note that the checking of input values to functions is considered a more robust means of error prevention than trying to detect errors after the function has completed (see Rule 20.3). Note also that the use of errno (to return error information from functions) is clumsy and should be used with care (see Rule 20.5)."

Note:
Rules checks usage of function calls which returns int value and reports violation when this value is not assigned or checked.

Benefits:
Rule helps writing safety code.

Example:

int SomeFunctionReturningError( );

void foo( )  {
   SomeFunctionReturningError( );  // Violation
}

Repair:

int SomeFunctionReturningError( );

int foo( )  {

   int x;
   x = SomeFunctionReturningError( );        // OK
   if (SomeFunctionReturningError( ));       // OK

   switch (SomeFunctionReturningError( )) {  // OK

   }

   return SomeFunctionReturningError( );     // OK
}

References:
MISRA-C:2004 Guidelines for the use of the C language in critical systems

Chapter 6, Section 16

Author
ParaSoft


Labels