Showing posts with label script. Show all posts
Showing posts with label script. Show all posts

Friday, March 20, 2015

[vim] auto complete matlab flow control [for, if, while] with indentation in vim

Okay, it turns out just combining some keys is good enough :(

:inoremap <c-n><c-n> <esc>yyp^d$a
:inoremap <c-c><c-c> <esc>yyp^d$aend<esc>kyyp^d$a
 
hit ctrl-c twice (holding ctrl) in the edit mode , use ctrl-n twice to go next line

------------------------------------------------------------------- no need something huge --------------------------
"=============================================================================
" matlabFlowComplete.vim v0.0
" Author: Xianmin Hu <xianmin.hu@gmail.com>
" http://scriptdemo.blogspot.com
" Last Change: 19-Mar-2015.
"=============================================================================
"
"key cc : to complete for, if and while flow
"key nn : go to next line with proper indentation

:function! CompleteMatlabFlow()
" complete for, while and if flow control with proper indentation
: let isValidForWhileIf=0
: let tmpline=substitute(getline(".")," \\+"," ","g")
: let tmpline=substitute(tmpline," \\+$","","g")
: call setline(".",tmpline)
: let tmpline=substitute(tmpline,"^ \\+","","g")
: let clinesp=split(tmpline," ")
: unlet tmpline
: execute "normal! o"
: execute "normal! kk^"
: if len(clinesp) > 1
:    if clinesp[0] == "for" && len(clinesp)>2
:       let isValidForWhileIf=1
:       if len(clinesp)==3
:          let newcline="for " . clinesp[1] . " = " . clinesp[2] . ":1:" . clinesp[2]
:       elseif len(clinesp)==4
:         if clinesp[2]<clinesp[3]
:            let newcline=clinesp[0] . " " . clinesp[1] . " = " . clinesp[2] . ":" . clinesp[3]
:         else
:           let newcline=clinesp[0] . " " . clinesp[1] . " = " . clinesp[2] . ":-1:" . clinesp[3]
:        endif
:      elseif len(clinesp)>=5
:       let newcline=clinesp[0] . " " . clinesp[1] . " = " . clinesp[2] . ":" . clinesp[3] . ":" . clinesp[4]
:      endif
:      let cpos = col(".")
:      let preline=split(getline(".")," ")
:      if len(preline) > 0
:         if preline[0] == "for"
:            let cpos += 4
:         elseif preline[0] == "while"
:            let cpos += 6
:         elseif preline[0] == "if"
:            let cpos += 3
:         endif
:      endif
:      while cpos > 1
:               let newcline = " " . newcline
:               let cpos -= 1
:       endwhile
:       execute "normal! j"
:       call setline(".",newcline)
:       execute "normal! yyp"
:       execute "normal! ^d$"
:       call setline(".",getline(".") . "end")
:       execute "normal! jdd"
:       execute "normal! kyykpd$i "
:       unlet newcline
:       unlet cpos
:    endif
"
:    if (clinesp[0] == "if" || clinesp[0] == "while") && len(clinesp)>1
:       let isValidForWhileIf=1
:       let cpos = col(".")
:       let preline=split(getline(".")," ")
:       if len(preline) > 0
:          if preline[0] == "for"
:             let cpos += 4
:          elseif preline[0] == "while"
:             let cpos += 6
:          elseif preline[0] == "if"
:             let cpos += 3
:          endif
:       endif
:       let padStr=""
:       while cpos > 1
:           let padStr = " " . padStr
:           let cpos -= 1
:      endwhile
:      execute "normal! j^0d^"
:      call setline(".", padStr . getline("."))
:      execute "normal! yyp^d$"
:      call setline(".",getline(".") . "end")
:      execute "normal! jdd"
:      execute "normal! kyykpd$i "
:      unlet padStr
:      unlet cpos
:   endif
:   unlet clinesp
: endif
: if isValidForWhileIf < 1
:    execute "normal! u"
:    execute "normal! $"
: endif
: unlet isValidForWhileIf
:endfunction

:function! GoMatlabNext()
" go next line and use same indent from previous line
: execute "normal! yyp"
: execute "normal! ^d$a"
:endfunction

:nmap cc :call CompleteMatlabFlow()<CR>a
:nmap nn :call GoMatlabNext()<CR>a
Example:
1) type "for a 1 4", then run cc in normal mode, ==>
for a = 1:4

end
2) type "for a 4 1", then run cc in normal mode, ==>
for a = 4:-1:4

end
3) type "for a 2 4 12", then run cc in normal mode, ==>
for a = 2:4:12

end
4) type "while a =4", then run cc in normal mode, ==>
while a=4

end

5) auto-indent
if you have"
%==============
if isLoop==1
for n loopStart loopStep loopEnd (run cc in normal mode)
end

it will result in:
%==============
if isLoop==1
   for n = loopStart:loopStep:loopEnd
         
   end
end

Friday, March 13, 2015

[matlab] relocate an object in the figure window

function movePosition(myh,myfrac,opt)
% move an object to a new location relative to current axes
% usage:
%      movePosition(obj-handle,fraction,opt)
%             opt: 'x' ==> x-coordiante is given in fraction of xlim
%                    'y' ==> y-coordiante is given in fraction of ylim
%                  'xy' ==> both x,y-coordiante is given in fraction
%                                (could be a 2-element vector)
% http://scriptdemo.blogspot.ca

if nargin~=3
   help movePosition
   return
end
if numel(myh)>1
   for nh=1:numel(myh)
       movePosition(myh(nh),myfrac,opt);
   end
   return
end
if ~ishandle(myh)
   error('need a valid object handle')
end

oriPos=get(myh,'position');
if isempty(oriPos)
    error('no position attribute is available')
end
if isnumeric(opt)
   oriPos(1)=myfrac;
   oriPos(2)=opt;
else
   switch lower(opt)
    case {'x'}
        cXLim=get(gca,'xlim');
        oriPos(1)=oriPos(1)+myfrac*(cXLim(2)-cXLim(1));
    case {'y'}
        cYLim=get(gca,'ylim');
        oriPos(2)=oriPos(2)+myfrac*(cYLim(2)-cYLim(1));
    case {'xy'}
        if numel(myfrac)==1
            myfrac=[myfrac myfrac];
        end
        cXLim=get(gca,'xlim');
        oriPos(1)=oriPos(1)+myfrac(1)*(cXLim(2)-cXLim(1));
        cYLim=get(gca,'ylim');
        oriPos(2)=oriPos(2)+myfrac(2)*(cYLim(2)-cYLim(1));
    otherwise
        error(['unknown opt: ',opt])
   end
end
set(myh,'position',oriPos);

[matlab] show available tags

function showtags(figH)
% to show all the tags in figure(s)
% usage:
%        showtags([figure_handles])
% e.g.,
%        showtags(gcf)
% http://scriptdemo.blogspot.ca

if nargin==1
   availableTag=unique(get(findobj(figH),'tag'));
   availableTagC=unique(get(findobj(figH),'Tag'));
else
   availableTag=unique(get(findobj(),'tag'));
   availableTagC=unique(get(findobj(),'Tag'));
end
if sum(~cellfun('isempty',availableTag))~=0
    disp('Available tags: ')
    disp(availableTag)
end
if sum(~cellfun('isempty',availableTagC))~=0
    disp('Available Tags: ')
    disp(availableTagC)
end

Wednesday, August 6, 2014

[Bash] sum numbers in an array

#!/bin/bash
# sum all/part the numbers in an array using bc
# usage:
#           mysum number-array [index0 index1]
#           Note: the index starts from 1
# e.g.,
#      myA=(34 23 32.5 33.2 25)
#      mysum "${myA[*]}" ==> 147.7
#      mysum "${myA[*]}" 1 2 ==> 57
#      mysum "${myA[*]}" 2 4 ==> 88.7
#      mysum "12 23 12" ==> 47
#
# http://scriptdemo.blogspot.com

isDebug=0
if [ $# -eq 0 ]; then
   sed -n '3,8p' `which mysum`
   exit
else
  myA=($1)
  [ ${isDebug} -eq 1 ] && echo ${myA[*]}
  [ ${isDebug} -eq 1 ] && echo "narg: $#"
  if [ $# -eq 1 ]; then
     if [ ${isDebug} -eq 1 ]; then
        echo "sum: `echo ${myA[*]} | sed 's/\ /+/g' | bc -l`"
     else
        echo "`echo ${myA[*]} | sed 's/\ /+/g' | bc -l`"
     fi
  elif [ $# -eq 2 ]; then
     ind0=`expr $2 - 1`
     nC=`expr ${#myA[*]} - ${ind0}`
     if [ ${isDebug} -eq 1 ]; then
        echo "sum: `echo ${myA[*]:${ind0}:${nC}} | sed 's/\ /+/g' | bc -l`"
     else
        echo "`echo ${myA[*]:${ind0}:${nC}} | sed 's/\ /+/g' | bc -l`"
     fi
  elif [ $# -eq 3 ]; then
     ind0=`expr $2 - 1`
     nC=`expr $3 - ${ind0}`
     if [ ${isDebug} -eq 1 ]; then
        echo "sum: `echo ${myA[*]:${ind0}:${nC}} | sed 's/\ /+/g' | bc -l`"
     else
        echo "`echo ${myA[*]:${ind0}:${nC}} | sed 's/\ /+/g' | bc -l`"
     fi
  fi

Wednesday, June 19, 2013

[Bash] text to html using vim built-in function TOhtml

#!/bin/bash
# convert a text file to html using vim built-in function TOhtml
# usage:
#            toHTML text-files
# http://scriptdemo.blogspot.com

if [ $# -eq 0 ]; then
   sed -n '3,4p' `which toHTML`
   exit
else
   for mytxt in $*
   do
      if [ -e ${mytxt} ]; then
         vim -c 'syntax on|TOhtml' -c 'wq|q!' ${mytxt}
      else
         echo "${mytxt} is not found"
      fi
   done
fi

Friday, May 3, 2013

[Matlab] remove the water bodies in a m_map figure

function m_nolakes(lakeColor)
% delete the water bodies patches in figures created by m_map
%           default lakeColor is white ([1 1 1])
% usage:
%           m_nolakes(lakeColor)
%           http://scriptdemo.blogspot.com

if nargin==0
   lakeColor=[1 1 1];
elseif nargin~=1
   help m_nolakes
   return
end

gshhstypes={'c','l','i','h','f'};
for nt=1:numel(gshhstypes)
    eval(['hw=findobj(gcf,''type'',''patch'',''tag'',''m_gshhs_',gshhstypes{nt},''',''facecolor'',lakeColor);']);
    if ~isempty(hw)
       delete(hw);
    end
end
hw=findobj(gcf,'type','patch','tag','m_coast','facecolor',lakeColor);
if ~isempty(hw)
   delete(hw);
end

Sunday, April 7, 2013

[Bash] extractBib: extract bib items from a source bibtex database for a given tex file

#!/bin/bash
# extract bib items from a source bibtex database for a given tex file
# usage:
#          extractBib tex-file bibtex-database output-bibtex-file
# e.g.,
#          extractBib mypaper.tex mybibtexdatabase.bib mypaper.bib
# http://scriptdemo.blogspot.com

function getkeys()
{
   texfile=$1
   mykeys=`grep "cite.*{.*}" ${texfile} | sed -e 's/\ //g' | awk '{for (i=1; i<=NF;i++) {if ($i ~ /cite/) {print $i}}}' | sed -e 's/\}/\n/g' | awk -F\{ '{print $2}' | sed -e 's/\,/\n/g' | sed '/^[\ ]*[\ ]*$/d' | sort | uniq | sed '/^\\\\/d' | sed '/:/d'` 
   echo ${mykeys}
}

if [ $# -eq 3 ]; then
   texfile=$1; bibfile=$2; outfile=$3
elif [ $# -eq 2 ]; then
   texfile=$1; bibfile=$2; outfile="extractbib_"$1
else
   echo "usage:"
   echo "          extractBib tex-file bibtex-database output-bibtex-file"
   exit
fi

# make sure no overwrite
[ -e ${outfile} ] && echo "${outfile} exists alreay! exit" && exit

allkeys=`getkeys ${texfile}`
if [ ${#allkeys[*]} -ne 0 ]; then
   touch ${outfile}
   for eachkey in ${allkeys[*]}
   do
       #echo ${eachkey}
       sed -ne "/${eachkey}/,/^[\ ]*\}$/p" ${bibfile} >> ${outfile}
   done
fi

Thursday, February 14, 2013

[Matlab] show a normal random heart

% Just for fun, not really useful....
% @ http://scriptdemo.blogspot.com 
clear; close all;
r=0.618; n=10000; re=sqrt(1-r*r);
x=normrnd(0,1,n,1);
y=x*r+normrnd(0,1,n,1)*re;y(x<0)=-y(x<0);
plot(x,y,'o','markerEdgeColor',[1 0 1],'markerFaceColor','none');
axis equal tight off;
set(gcf,'MenuBar','none','color','w')

Tuesday, November 20, 2012

[Bash] change current workspace by calling a script function

# to change current path using a customized script function
# instead of using alias. Need put this function in .bashrc
#    e.g.,
#            mycd ex1 ==> cd ~/scripttest/ex1
#            mycd ex2 ==> cd ~/scripttest/ex2
#            mycd eX2 ==> cd ~/scripttest/ex2
#   @ http://scriptdemo.blogspot.com 

function mycd (){
 if [ $# -ne 1 ]; then
    echo "Usage:"
    echo " mycd foldername"
 else
    targetF=`echo $1 | awk '{print tolower($1)}'`
    targetP=${HOME}/scripttest/${targetF}
    if [ -d ${targetP} ]; then
       eval "cd ${targetP}"
    else
       echo "${targetP} does not exist!"
    fi
    unset targetF
 fi
}

Monday, August 27, 2012

[Matlab] bar/tube plot along a 3d path

function hbarplot=barplot(x,y,z,varargin)
% plot a 3d surface/tube centered at (x,y,z)
% usage:
%           hbarplot=barplot(x,y,z,varargin)
%           varargin:
%                       'v' : the cdata values, same size as z
%                       'n' : N-isogon as the basic shape
%                       'r' : radius of the N-isogon
%    e.g.,
%          zz=0:0.5:10;
%          hh=barplot(cos(zz/10*pi),5,zz,'v',randn(1,numel(zz))+sin(zz/10*pi),'n',4,'r',sin(zz/10*pi)); view(3)
%          http://scriptdemo.blogspot.com

clc;
myN=3; myR=0.5; isV=0;
if nargin>3
   while(size(varargin,2)>0)
      switch lower(varargin{1})
      case {'v','cdata','colordata','facecolordata'}
          v=varargin{2};
          varargin(1:2)=[];
          isV=1;
      case {'n','nshape'}
          myN=varargin{2};
          varargin(1:2)=[];
      case {'r','radius'}
          myR=varargin{2};
          varargin(1:2)=[];
      otherwise
          error(['Not defined properties!',varargin{1}])
      end
   end
elseif nargin==0
   % demo case
   zz=0:0.5:10;
   hbarplot=barplot(cos(zz/10*pi),5,zz,'v',randn(1,numel(zz))+sin(zz/10*pi),'n',4,'r',sin(zz/10*pi));
   view(-150,30);
   return
elseif nargin<3
   help barplot
   return
end

[xx,yy,zz]=getMeshN(x,y,z,myR,myN);
if isV==0
   hbarplot=surface(xx',yy',zz');
else
   if numel(v)==numel(z)
      vv=repmat(reshape(v,[],1),1,size(xx,2));
   end
   hbarplot=surface(xx',yy',zz');
   set(hbarplot,'cdata',vv');
end
set(hbarplot,'tag','barplot','linestyle','none','facecolor','interp');
axis off equal
set(gcf,'color','w');

function [xx,yy,zz]=getMeshN(x0,y0,z,myR,N)
if nargin==3
   myR=0.5;
   N=3;
elseif nargin==4
   N=3;
elseif nargin~=5
   error('Usage: [xx,yy,zz]=getMeshN(x,y,z,myR,N)');
end
z=reshape(z,[],1);
numZ=numel(z);

myAng=linspace(0,2*pi,N+1);
xslab=cos(myAng); yslab=sin(myAng);
%N=numel(xslab)-1; % could be other shape as well.

if numel(x0)==1
   x0=repmat(x0,numZ,N+1);
elseif numel(x0)==numZ
   x0=repmat(reshape(x0,[],1),1,N+1);
end
if numel(y0)==1
   y0=repmat(y0,numZ,N+1);
elseif numel(y0)==numZ
   y0=repmat(reshape(y0,[],1),1,N+1);
end

if numel(myR)==1
   xx=repmat(xslab*myR,numZ,1)+x0;
   yy=repmat(yslab*myR,numZ,1)+y0;
else
   myR=repmat(reshape(myR,[],1),1,N+1);
   xx=repmat(xslab,numZ,1).*myR+x0;
   yy=repmat(yslab,numZ,1).*myR+y0;
end
zz=repmat(z,1,N+1);




Sunday, August 26, 2012

[Matlab] fill a specific-value region with a given color

function FillIt(lon,lat,Land,FillC,TagType,FillValue)
% To fill a specific-value region with a given color
% Usage:
%            FillIt(lon,lat,Land,FillC,TagType,FillValue)
%                   TagType: could be 'RU' or 'LD', 
%                                 to fill right-up square or left-down square
%                   FillValue: nan [default] or specific value to fill with color [FillC]
%            Note: lon, lat, Land must be the same size
%      e.g.,
%            FillIt(lon,lat,lsmask,[0.0 0.3 0.3],'RU')
%      http://scriptdemo.blogspot.com

if nargin==0
   %demo
   load topo topo;
   topo(topo>0)=nan;
   xx=1:360; yy=1:180;
   [xx,yy]=meshgrid(xx,yy);
   FillIt(xx,yy,topo,[0.4 0.3 0.4],'RU');
   set(gca,'tickdir','out','linewidth',2,'xminortick','on','yminortick','on','box','on','fontweight','bold');
   set(gcf,'color','w'); axis equal; axis tight;
   return
end

if nargin==3
   FillC=[0.3 0.3 0.3];
   TagType='RU';
   FillValue='nan';
elseif nargin==4
   TagType='RU';
   FillValue='nan';
elseif nargin==5
   FillValue='nan';
elseif nargin~=6
   help FillIt;
   return
end

if numel(lon)~=numel(lat)
   disp('lon and lat must be the same size')
   return
end
if numel(lon)~=numel(Land)
   disp('lon/lat and land must be the same size')
   return
end

[Ny,Nx]=size(Land);
if ischar(FillValue)
   if strcmpi(FillValue,'nan')
      [Indy,Indx]=find(isnan(Land));
   else
      disp(['invalid fill value: ',FillValue])
      return
   end
elseif isnumeric(FillValue)
      [Indy,Indx]=find(Land==FillValue);
else
      disp('invalid fill value')
      return
end

switch upper(TagType)
   case 'RU'
      % Right Up
      % 4----3
      % |      |
      % 1----2
      Indx(Indy==Ny)=[];Indy(Indy==Ny)=[];
      Indy(Indx==Nx)=[];Indx(Indx==Nx)=[];
      Fillx(1,:)=lon((Indx-1)*Ny+Indy);
      Fillx(2,:)=lon((Indx)*Ny+Indy);
      Fillx(3,:)=lon((Indx)*Ny+Indy+1);
      Fillx(4,:)=lon((Indx-1)*Ny+Indy+1);
      Fillx(5,:)=lon((Indx-1)*Ny+Indy);

      Filly(1,:)=lat((Indx-1)*Ny+Indy);
      Filly(2,:)=lat((Indx)*Ny+Indy);
      Filly(3,:)=lat((Indx)*Ny+Indy+1);
      Filly(4,:)=lat((Indx-1)*Ny+Indy+1);
      Filly(5,:)=lat((Indx-1)*Ny+Indy);
   case 'LD'
      % Left Down
      % 2----1
      % |     |
      % 3----4
      Indx(Indy==1)=[];Indy(Indy==1)=[];
      Indy(Indx==1)=[];Indx(Indx==1)=[];
      Fillx(1,:)=lon((Indx-1)*Ny+Indy);Filly(1,:)=lat((Indx-1)*Ny+Indy);
      Fillx(2,:)=lon((Indx-2)*Ny+Indy);Filly(2,:)=lat((Indx-2)*Ny+Indy);
      Fillx(3,:)=lon((Indx-2)*Ny+Indy-1);Filly(3,:)=lat((Indx-2)*Ny+Indy-1);
      Fillx(4,:)=lon((Indx-1)*Ny+Indy-1);Filly(4,:)=lat((Indx-1)*Ny+Indy-1);
      Fillx(5,:)=lon((Indx-1)*Ny+Indy);Filly(5,:)=lat((Indx-1)*Ny+Indy);
   otherwise
     disp('Not defined Fill Type')
     help FillIt
     return
end

if ~ishold; hold on; end
hf=patch(Fillx,Filly,FillC);
set(hf,'linestyle','none','tag','fillIt');

Friday, August 24, 2012

[Matlab] show 2d mesh grid

function ShowGridLine(lon,lat,NSkip,LineC,LineS,LineM)
% To show a 2d mesh-grid defined by given grid points
% similar to the function mesh?
% Example:
%          ShowGridLine(lon,lat,2,'k','-','.')
%          http://scriptdemo.blogspot.com
%

if (nargin>3)
    if exist('LineC','var')~=1 LineC='k'; end
    if exist('LineS','var')~=1 LineS='-'; end
    if exist('LineM','var')~=1 LineM='none'; end
elseif (nargin>=2)
    if exist('NSkip','var')==1
        if ischar(NSkip) LineC=NSkip; clear NSkip; end
    end
    if exist('NSkip','var')~=1 NSkip=5; end
    if exist('LineC','var')~=1 LineC='k'; end
    if exist('LineS','var')~=1 LineS='-'; end
    if exist('LineM','var')~=1 LineM='none'; end
elseif (nargin==0)
    close all;
    [xx,yy]=meshgrid(1:19,1:19);
    ShowGridLine(xx,yy,1,'k','-');
    plot(4,4,'o','markerfacecolor','k','markersize',4,'markeredgecolor','k');
    plot(16,16,'o','markerfacecolor','k','markersize',4,'markeredgecolor','k');
    plot(4,16,'o','markerfacecolor','k','markersize',4,'markeredgecolor','k');
    plot(16,4,'o','markerfacecolor','k','markersize',4,'markeredgecolor','k');
    set(gcf,'color','w');
    set(gca,'xtick',2:2:18,'ytick',2:2:18,'ydir','r','xaxislocation','top')
    axis equal; axis tight;
    xlabel('Go Board','fontweight','bold','fontsize',18,'color','red');
    return
else
    help ShowGridLine
    return
end

[N1,N2]=size(lat);
if ~ishold hold on; end
for NL=1:NSkip:N2
    hp=plot(lon(:,NL),lat(:,NL));
    set(hp,'color',LineC,'linestyle',LineS,'Marker',LineM)
end
for NL=1:NSkip:N1
    hp=plot(lon(NL,:),lat(NL,:));
    set(hp,'color',LineC,'linestyle',LineS,'Marker',LineM,'tag','gridLines')
end
Demo:

ShowCalendar