'분류 전체보기'에 해당되는 글 126건

  1. 2011.03.14 [PERL] 하나의 정규 표현식으로 복수개의 아이템 치환하기
  2. 2011.03.14 [LINUX] execl
  3. 2011.03.14 [BASH] String manipulation
  4. 2010.11.24 [IPHONE] Xcode template
  5. 2010.11.24 [Emacs] 실행 패스(exec-path) 설정
  6. 2010.08.29 [PERL] 특수 변수
  7. 2010.08.25 [IPHONE] Break on exception in Xcode. & Enable NSZombie
  8. 2010.08.24 [EMACS] Macro Record and Play
  9. 2010.08.18 [PERL] Regular Expression
  10. 2010.08.17 [PERL] UTF-8 encoding 으로 파일에 쓰기
  11. 2010.08.16 [PERL] Timer
  12. 2010.08.13 [SED] Replaces a certain character in a string with a newline in MAC OSX
  13. 2010.08.12 [FIND] find using regular expression (-regex)
  14. 2010.08.12 [BASH] 공백문자(space)가 포함된 파일패스 list 처리
  15. 2010.08.12 [BASH] rm -rf path/to/delete/*
  16. 2010.08.11 [SED] edit in place without backup
  17. 2010.08.05 [BASH] Builtin: test, [
  18. 2010.08.03 Quick Sort
  19. 2010.08.02 [IPHONE] There are three ways to access the contents of a NIB.
  20. 2010.07.30 [Windows] Keyboard type 3로 변경
  21. 2010.07.27 [BASH] 변수
  22. 2010.06.16 [MAC] Mac OS X 10.2 이후에서의 Local Hosts File 위치
  23. 2010.06.04 [MAKE] Target
  24. 2010.04.16 build된 SDK 사용시 W/ResourceType(31706): Unable to get buffer of resource asset file 에러
  25. 2010.04.16 ETC ...
  26. 2010.03.25 Emacs Javascript
  27. 2010.03.25 Gitosis를 이용한 Git server 설치
  28. 2010.02.13 Ubuntu 9.10 에서 JDK 5 설치
  29. 2010.01.26 Reference to Pointer
  30. 2010.01.21 emacs & cscope

[PERL] 하나의 정규 표현식으로 복수개의 아이템 치환하기

CS/Shell/Perl/Python 2011. 3. 14. 16:42
원문 : StackOverflow
참고 : 

#!/usr/bin/perl

use strict;
use warnings;

my %replace = (
    quick => "slow",
    lazy  => "energetic",
);

my $regex = join "|", keys %replace;
$regex = qr/$regex/;

my $s = "The quick brown fox jumps over the lazy dog";

$s =~ s/($regex)/$replace{$1}/g;

print "$s\n";


참고. $1 에 대해서:
/A(dam|nne|ndrew)/
와 같은 정규식이 있다고 할때, $1이 생성되고, 이는 dam, nne, ndrew등의 값을 가지게 된다. 만약 이후에 괄호가 있다면 그에 일치하는 값이 $2, $3, ...의 변수에 할당된다.

/A(?:dam|nne|ndrew)/
와 같이 ?:를 사용할 경우 해상 괄호에 대해서는 그에 일치하는 변수를 생성하지 않는다.

:

[LINUX] execl

CS/Linux 2011. 3. 14. 15:50
참고 : 
Man pages for execl, getenv


#include <unistd.h>

extern char **environ;

int execl (const char *path, const char *arg0, ... /*, (char *)0 */);
int execle(const char *path, const char *arg0, ... /*, (char *)0, char *const envp[] */);
int execlp(const char *file, const char *arg0, ... /*, (char *)0 */);

int execv (const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execve(const char *path, char *const argv[], char *const envp[]);
int execvP(const char *file, const char *search_path, char *const argv[]);

만약 exec()계열의 함수가 리턴을 한다면, 에러가 발생한 것이다. 이 때 리턴 값은 -1 이고 errno변수값이 설정된다.

execlp(), execvp() 함수는 PATH환경변수에 지정된 패스에서 file을 찾는다. 
만약 이 변수가 지정되지 않았다면, <paths.h>에 지정되어 있는 _PATH_DEFPATH 에 따라 지정된다.(일반사용자- /usr/bin:/bin)
execvP()는 탐색 경로를 인자에 지정한다.

char *const envp[] = {"SOMEKEY1=somevalue1", "SOMEKEY2=somevalue2", NULL};
char * const argv[] = {"/usr/bin/uname", "-a", NULL};

execl ("/usr/bin/uname",      "/usr/bin/uname",      "-a", NULL);
execle("/path/to/executable", "/path/to/executable",       NULL, envp);
execlp("uname",               "uname",               "-a", NULL);

execv ("/usr/bin/uname",    argv);
execvp("uname",             argv);
execve("/usr/bin/uname",    argv, envp);
evecvP("uname", "/usr/bin", argv);








:

[BASH] String manipulation

CS/Shell/Perl/Python 2011. 3. 14. 13:42
참고


1. String Length

${#string}



2. Substring Extraction

${string:position}
$string에서 position에 있는 substring
만약 $string 파라메터가 "*"나 "@"이면 position에서 시작하는 위치 매개변수를 추출해 낸다.
${string:position:length}
$string에서 position부터 length까지의 substring

stringZ=abcABC123ABCabc
#           0123456789.....
#           0-based indexing.

echo ${stringZ:0}                            # abcABC123ABCabc
echo ${stringZ:1}                            # bcABC123ABCabc
echo ${stringZ:7}                            # 23ABCabc

echo ${stringZ:7:3}                         # 23A



3. Substring Removal

${string#substring}
$string의 앞 부분에서 가장 짧게 일치하는 $substring을 삭제
${string##substring}
$string의 앞 부분에서 가장 길게 일치하는 $substring을 삭제

stringZ=abcABC123ABCabc
#           |------|                shortest
#           |----------------|    longest

echo ${stringZ#a*C}       # 123ABCabc
echo ${stringZ##a*C}     # abc

${string%substring}
$string의 뒷 부분에서 가장 짧게 일치하는 $substring을 삭제
${string%%substring}
$string의 뒷 부분에서 가장 길게 일치하는 $substring을 삭제

stringZ=abcABC123ABCabc
#                                    ||    shortest
#              |------------------|    longest

echo ${stringZ#b*c}       # abcABC123ABCa
echo ${stringZ##b*c}     # a



4. Substring Replacement

${string/substring/replacement}
처음 일치하는 $substring을 $replacement로 대치. $string 자체가 변화되지는 않는다.
${string//substring/replacement}
일치하는 모든 $substring을 $replacement로 대치. $string 자체가 변화되지는 않는다.

stringZ=abcABC123ABCabc
echo ${stringZ/abc/xyz}       # xyzABC123ABCabc
                                            # Replaces first match of 'abc' with 'xyz'.

echo ${stringZ//abc/xyz}      # xyzABC123ABCxyz
                                            # Replaces all matches of 'abc' with # 'xyz'.

# Can the match and replacement strings be parameterized?
match=abc
repl=000
echo ${stringZ/$match/$repl}  # 000ABC123ABCabc
#                     ^           ^            ^^^
echo ${stringZ//$match/$repl} # 000ABC123ABC000
#                      ^          ^            ^^^               ^^^

# What happens if no $replacement string is supplied?
echo ${stringZ/abc}           # ABC123ABCabc
echo ${stringZ//abc}          # ABC123ABC

${string/#substring/replacement}
$substring이 $string의 맨 앞에서 일치하면 $replacement로 대치.
${string/%substring/replacement}
$substring이 $string의 맨 뒤에서 일치하면 $replacement로 대치.

stringZ=abcABC123ABCabc

echo ${stringZ/#abc/XYZ}          # XYZABC123ABCabc
                                                  # Replaces front-end match of 'abc' with 'XYZ'.

echo ${stringZ/%abc/XYZ}          # abcABC123ABCXYZ
                                                   # Replaces back-end match of 'abc' with 'XYZ'.

:

[IPHONE] Xcode template

CS/iPhone 2010. 11. 24. 14:53
Xcode template 위치 (Source)
/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Project Templates

User template 위치
${USER}/Library/Application Support/Developer/Shared/Xcode/Project Templates
:

[Emacs] 실행 패스(exec-path) 설정

TIPs 2010. 11. 24. 00:05

설정값 보기

C-h v exec-path



설정 (PATH, exec-path)

(setenv "PATH" (concat (getenv "PATH") ":/opt/local/bin"))
(setq exec-path (append exec-path '("/opt/local/bin")))



General Variables 확인
M-: (info "(emacs)General Variables")
:

[PERL] 특수 변수

CS/Shell/Perl/Python 2010. 8. 29. 23:58
원문 : Perl 프로그래밍 (2nd Ed)

전역 특수 변수

$_
: 기본 입력 및 패턴 일치 공간. 다음 각 쌍은 동일한 효과를 갖는다.
while (<>) { ... }
while (defined($_ = <>)) { ...}
/^Subject:/
$_ =~ /^Subject:/
chop
chop($_)

$.
: 가장 최근에 읽은 파일 핸들의 현재 입력 행 번호.
: 명시적으로 파일 핸들을 닫으면 이 값을 리셋하는 효과가 있다.
: <>는 명시적으로 파일 핸들을 닫지 않으므로, ARGV로 지정된 파일에 대해서는 행 번호는 계속 증가한다.
: $.를 지역화하는 것은 Perl이 최근에 읽어 들인 파일 핸들을 지역화하는 효과가 있다.

$/
: 입력 레코드 구분자로 기본값은 개행 문자이다.
: 만약 널 문자열로 지정되면 빈 줄(blank line)을 구획문자로 취급한다.
: 여러 개의 글자를 구획문자로 사용하기 위해서 여러 개의 글자로 이루어진 문자열을 지정할 수도 있다.
undef $/;
$_ = <FH>;          # whole file now here

$,
: print 연산자에 적용되는 출력 필드 구분자이다.
: 보통 print 연산자는 쉼표로 구분된 필드를 출력한다.
: awk에서와 비슷하게 동작하도록 하려면, awk의 OFS 변수를 지정해서 출력될 필드를 구분하는 것과 마찬가지 방법으로 이 변수를 지정하면 된다.

$\
: print 연산자에 적용되는 출력 레코드 구분자이다.
: 보통 print 연산자는 쉼표로 구분된 필드를 출력하며, 뒤에는 개행 문자나 레코드 구분자가 없다고 가정한다.
: awk에서와 비슷하게 동작하도록 하려면, awk의 ORS 변수를 지정해서 print의 마지막 부분에 출력될 내용을 지정하는 것과 같이 이 변수를 지정하면 된다.

$*
: 이 변수는 겹 따옴표 문자열에서 치환되는 리스트 값에 적용된다는 점만 제외하고는 $,와 동일하다.
: 기본값은 스페이스 이다.

$;
: 다차원 배열 연산에서의 첨자 구분자이다. 
: 만약 다음과 같이 해쉬 요소를 참조하는 경우
$foo{$a, $b, $c}
실제로는 다음을 의미한다.
$foo{join($;, $a, $b, $c)}

: 그러나 다음과 같이 할 경우
@foo{$a, $b, $c}
실제로는 다음을 의미하게 되므로 주의하여야 한다.
($foo{$a}, $foo{$b}, $foo{$c})

$^L
: 쪽 넘김시 출력될 내용을 지정한다.
: 기본값은 "\f" 이다.

$:
: 문자열이 나뉘어 질 때 출력서식문에서 ^로 시작하는 연속 필드를 채우는데 사용되는 문자의 세트를 지정한다.
: 기본값은 "\n-" 이다.

$^A
: format 행에 대한 write accumulator의 현재값을 나타낸다.
: formline을 포함하는 출력서식문을 사용하여 결과를 $^A에 넣도록 할 수 있다.
: 출력서식을 알아낸 다음 write는 $^A의 내용을 출력한 다음 $^A를 비운다. 따라서 formline을 사용하지 않고서는 $^A의 값을 알아낼 수 없다.

$?
:  가장 최근에 닫은 파이프, 백틱(`) 명령, 혹은 system 연산자 등에서 반환된 결과를 담고 있다.
: 실제로 이 값은 wait(2) 시스템 호출에 의해 반환된 상태이므로, 서브프로세스의 종료값은 실제로 ($? >> 8)에 해당한다.
: 따라서 많은 시스템에서 $? & 255 하면 프로세스로부터 어떤 시그널이나 코어 덤프의 발생 여부를 알 수 있다.

$!
: 숫자 구문에서 사용될 경우 현재 실행중인 Perl에서 errno변수의 현재 값을 재공한다.
: 문자열 구문에서 사용될 경우, 해당되는 시스템 오류 문자열을 제공한다.

$@
: 가장 최근의 eval 명령어를 수행한 결과 발생한 문법 오류 메세지를 담고 있다.
: 최근 eval 명령어가 정상적으로 수행되어 오류가 발생하지 않았다면 널 값을 갖는다.

$$
: Perl이 현재 스크립트를 수행하는 프로세스 번호

$<
: 현재 프로세스의 실 user ID (uid)
: set-id 루틴을 지원할 때만 지정할 수 있다.

$>
: 현재 프로세스의 유효 uid
: set-id 루틴을 지원할 때만 지정할 수 있다.

$(
: 현재 프로세스의 실 GID
: set-id 루틴을 지원할 때만 지정할 수 있다.

$)
: 현재 프로세스의 유효 GID
: set-id 루틴을 지원할 때만 지정할 수 있다.

$0
: 현재 수행 중인 Perl 스크립트를 포함하고 있는 파일의 이름.
: $0에 값을 대입하여 ps 프로그램이 참조하는 영역을 변경할 수 있다.
: 이것은 현재 수행중인 프로그램을 숨기는 것보다 현재 프로그램의 상태를 나타내는 방법으로 유용하게 쓰인다. 그러나 모든 시스템에서 이처럼 동작하지는 않는다.

$]
: 현재 Perl의 버전 + 패치레벨/1000을 반환한다.

$^D
: 디버깅 플래그의 현재 값

$^F
: 시스템 파일 기술자(system file descriptor)의 최대값으로, 기본적으로 2 이다.

$^H
: 특정 pragmatic 모듈에 의해 활성화 되는 내부 컴파일러 힌트값 (이 값은 무시하고 pragma문을 사용하라)

$^I
: inplace_edit 확장의 현재 값. inplace 편집을 활성화하려면 undef를 사용한다.
 
$^O
: 현재 Perl 바이너리가 컴파일된 시스템 운영체제 이름. Config 모듈 대신 사용할 수 있는 간단한 방법이다.

$^P
: 디버거가 자기 자신을 디버그하지 않도록 클리어하는 내부 플래그.
: 사용자가 이 값을 클리어하여 확실하게 디버그를 하지 않도록 할 수 있다.

$^T
: 1970년부터 시작하여 해당 스크립트가 실행된 시간을 초 단위로 환산한 값.
: -M, -A, -C와 같은 파일 테스트 연산자는 이 값에 근거한다.

$^W
: 현재 경고 스위치의 값

$^X
: 실행된 Perl 바이너리 자신의 이름. C엑서의 argv[0]에 해당

$ARGV
: <ARGV>로부터 읽어 들일 때 현재 파일의 이름



전역 특수 변수 

@ARGV
: 해당 스크립트에 대한 명령어 행 파라미터를 담고 있는 배열.
: $#ARGV는 파라미터의 수-1 을 담고 있고, $ARGV[0]는 프로그램의 이름이 아니라 전달된 첫 번째 파라미터를 담고 있다는 것을 주의.
: 프로그램의 이름은 $0을 참조 하라.

@INC
: Perl 스크립트가 do EXPR, require, use 구조를 사용할 때 참조해야 하는 위치 리스트를 담은 배열.
: 초기에는 -I 명령어 행 스위치에 해당하는 값과, 기본 Perl 라이브러리의 위치를 포함하고 있다.
: 현재 디렉토리를 참조하려면 "."를 추가하면 된다.
: 실행시 @INC 리스트를 변경할 필요가 있을 때는, 시스템과 관련된 라이브러리 모듈을 제대로 불러 들이기 위해 다음과 같이 lib모듈을 사용해야만 한다.
use lib '/mypath/libdir/';
use SomeMod;

@F
: -a 스위치가 사용되얼을 때 입력 행이 split되어 입력되는 배열.
: -a 스위치가 사용되지 않으면 이 배열은 특별한 의미가 없다.

%INC
: do나 require를 통해 포함된 각 파일의 파일명을 담고 있는 해쉬.
: 키는 사용자가 지정하는 파일명이고, 값은 실제로 해당 파일을 찾은 위치를 갖고 있다.
: require 명령을 사용할 때, 이 값을 참조하여 주어진 파일의 포함 여부를 결정한다.

%ENV
: 현재 환경 변수의 값.
: %ENV의 값을 변경하면 자식 프로세스의 환경을 바꾸게 된다.
: 환경 변수에서 특정한 값을 없애려면 undef 대신 delete를 사용해야 한다.

%SIG
: 다양한 시그널을 처리하기 위한 시그널 핸들러에 의해 사용되는 해쉬.
sub handler {
    local($sig) = @_;
    print "Caught a SIG$sig--shutting down\n";
    close(LOG);
    exit(0);
}
$SIG{INT} = 'handler';
$SIG{QUIT} = 'handler';

$SIG{INT} = 'DEFAULT';      # restore default action
$SIG{QUIT} = 'IGNORE';      # ignore SIGQUIT

: $SIG{__WARN__} 로 지정된 루틴은 경고 메세지가 출력될 때 호출된다. 경고 메세지는 첫 번째 파라메터로 전달된다. 
- 후크가 존재하면 일반적으로 STDERR로 출력되던 경고 메세지가 출력되지 않게 된다.
: $SIG{__DIE__} 로 지정된 루틴은 치명적 예외 처리가 수행될 때 호출된다. 오류 메세지는 첫 번째 파라메터로 전달된다.
- 후크 루틴에서 반환될 때, 후크 루틴 자신이 goto나 루프 종료, die등에 의해 종료되지 않는 경우, 예외 처리 루틴은 마치 해당 후크가 없었던 것처럼 동작한다.
- __DIE__ 핸들러는 호출된 동안 명시적으로 비활성되어, __DIE__ 핸들러에서 실제 die를 호출할 수 있게 된다.



전역 특수 파일 핸들

ARGV
: @ARGV에 포함된 명령어 행 파일명에 대해 반복적으로 수행되는 특수한 파일 핸들.
: 보통 널 파일 핸들 <>로 표히된다.

STDERR
: 임의의 패키지에서 표준 오류를 위한 특수 파일 핸들.

STDIN
: 임의의 패키지에서 표준 입력을 위한 특수 파일 핸들.

STDOUT
: 임의의 패키지에서 표준 출력을 위한 특수 파일 핸들.

DATA
: 스크립트를 포함하는 파일에서 __END__ 토큰 다음에 나타나는 임의의 내용을 참조하는 특수 파일 핸들.
: 혹은, __DATA__ 를 찾는 같은 패키지에서 데이터를 읽는 동안 필요로 하는 파일 내에 __DATA__ 토큰 바로 다음에 나타나는 임의의 내용을 위한 파일 핸들.

_
: 가장 최근의 stat, lstat, 파일 테스트 연산 결과에 관한 정보를 캐쉬하기 위해 사용되는 특수 파일 핸들.



정규 표현식 특수 변수

$digit
: 가장 최근에 일치된 순서대로 괄호에 해당하는 일치된 문자열을 포함하고 있다. (\digit 와 같은 형태로도 사용된다.)

$&
: 가장 최근에 성공적으로 일치된 문자열이며, 블록 내에서 감추어져 일치된 내용이나 현재 블록에서 eval로 둘러 싸여 있는 내용은 포함하지 않는다.

$`
: 가장 최근에 성공적으로 일치된 문자열의 앞부분에 해당하는 문자열이며, 블록 내에서 감추어져 일치된 내용이나 현재 블록에서 eval로 둘러 싸여 있는 내용은 포함하지 않는다.

$'
: 가장 최근에 성공적으로 일치된 문자열의 뒷부분에 해당하는 문자열이며, 블록내에서 감추어져 일치된 내용이나 현재 블록에서 eval로 둘러 싸여 있는 내용은 포함하지 않는다.

$+
: 가장 최근의 일치 패턴에 의해 마지막 괄호로 일치된 문자열이며, 실제로 어떤 교대 문자열이 일치되었는지를 모를 경우에 유용하다.



파일 핸들 특수 변수 

$|
: 0이 아닌 값으로 지정하면 핸재 선택된 출력 채널로 매번 write 나 print가 행해질 때마다 fflush을 수행하도록 한다.
: 기본값은 0이며, 이것은 많은 시스템에서 터미널로 출력을 의미하는 경우 STDOUT은 기본적으로 라인 버퍼링으로, 그 밖의 경우 블록 버퍼링으로 처리되는 것을 의미한다.
: 이 변수의 값을 지정하는 것은 rsh에서 Perl 스크립트를 실행하면서 그 출력 결과를 보고 싶을 때와 같은 경우 유용하다.

$%
: 현재 선택된 출력 채널의 현재 쪽 번호

$=
: 현재 선택된 출력 채널의 출력 가능한 줄의 수. 기본값은 60

$-
: 현재 선택된 출력 채널의 쪽에서 남아 있는 줄 수

$~
: 현재 선택된 출력 채널에 적용될 출력서식의 이름. 기본값은 파일 핸들의 이름

$^
: 현재 선택된 출력 채널에 적용될 머리글 출력서식의 이름. 기본값은 파일 핸들에  _TOP을 붙인 것
:

[IPHONE] Break on exception in Xcode. & Enable NSZombie

CS/iPhone 2010. 8. 25. 09:23
참조 

Break on exception in Xcode.
Double-Click for symbol > “objc_exception_throw

Enable NSZombie
1. Double-click an executable in the Executables group of your Xcode project.
2. Click the Arguments tab.
3. In the “Variables to be set in the environment:” section, make a variable called “NSZombieEnabled” and set its value to “YES”.
:

[EMACS] Macro Record and Play

TIPs 2010. 8. 24. 00:49
원문 : The Geek Stuff

High Level Steps to Record and Play inside Emacs
1. Start recording a macro by pressing ctrl+x (
2. Perform any actions inside the Emacs editor that you would like to record.
   
   High Level Steps for Naming and Saving emacs macro, and playing it later
   A. Press Ctrl+x Ctrl+k n
   B. Give name-of-macro, and press ENTER

3. Stop recording by pressing ctrl+x )

4. Play the last recorded macro by pressing ctrl+x e
or    
C. Run the named macro by pressing, M-x name-of-macro

:

[PERL] Regular Expression

CS/Shell/Perl/Python 2010. 8. 18. 00:11
원문 : Perl 프로그래밍 (2nd Ed)
참고 : http://gypark.pe.kr/wiki/Perl/%EC%A0%95%EA%B7%9C%ED%91%9C%ED%98%84%EC%8B%9D

m/PATTERN/gimosx
/PATTERN/gimosx

n. /를 구분자로 사용할 경우 패턴 앞에 위치하는 m은 지정하지 않아도 된다. m을 사용하는 경우, 영문자나 공백 문자가 아닌 임의의 문자를 구분자로 사용할 수 있다.

n. 주어진 문자열에서 패턴을 검색하고, 그 결과로 스칼라 구문에서 참(1)이나 거짓("")을 반환한다.

n. 스칼라가 아니라 리스트 값을 필요로 하는 구문에 사용될 경우, 일치된 결과는 패턴 내에서 괄호로 지정된 재참조 문자열의 리스트를 반환한다.
만약, 패턴 일치가 실패하면, 널 리스트가 반환된다. 패턴이 일치했더라도 패턴 내에 괄호로 지정된 재참조 문자열이 없으면 리스트값 (1) 이 반환된다.
if (($F1, $F2, $F3) = ($foo =~ /^\s*(\S+)\s+(\S+)\s*(.*)/))

n. =~ 나 =!에 문자열을 지정하지 않았을 경우에는 기본 문자열 변수 $_를 검색한다.


변환자 g 
: 전역 패턴 일치(global pattern matching)를 지정한다. 즉, 주어진 문자열 내에서 가능한 여러 번 패턴 일치를 찾게 된다.
: 만약, 괄호가 하나도 없는 경우는 마치 전체 패턴을 괄호로 둘러싼 것과 같이 일치된 문자열 모두로 이루어진 리스트를 반환하다.
: 스칼라 구문에서 사용하면 매번 주어진 문자열과 일치할 때마다 참을 반환하고, 일치가 모두 끝나면 거짓을 반환한다.
($one, $five, $fifteen) = (`uptime` =~ /(\d+\.\d+)/g);

변환자 i
: 대소문자를 구별 없이 패턴 일치

변환자 m
: 문자열을 여러 줄로 취급(^와 $는 \n과 일치)

변환자 s
: 문자열을 한 줄로 취급(^와 $는 \n을 무시, 그러나 .는 \n과 일치)

변환자 x
: 정규 표현식을 분석할 때 역슬래쉬가 붙지 않은 공백 문자나, 문자 클래스 내에 들어있는 공백 문자를 무시하도록 한다.
: 공백문자와 주석문을 이용해 패턴의 가독성을 늘릴 때 사용

변환자 o
: 패턴을 한 번만 컴파일



s/PATTERN/REPLACEMENT/egimosx

n. 주어진 문자열에서 PATTERN을 찾으면, 일치된 것을 REPLACEMENT와 바꾸고 실제 교환된 것의 개수를 반환한다.
/g 변환자를 사용할 경우에는 교환된 개수가 1 보다 클 수 있다.
일치되지 않은 경우에는 거짓(0)을 반환한다.

n. 임의의 비 알파벳 문자, 비 공백 문자를 / 대신 구분자로 사용할 수 있다.
만약, PATTERN을 괄호 등과 같이 한 쌍으로 이루어진 구분자로 묶을 경우, REPLACEMENT는 PATERN에서 사용한 것과 다른 구분자를 사용할 수 있다.
s(foo)(bar)
혹은
s<foo>/bar/

n. 만약 구분자로 홑 따옴표를 사용하면, PATTERN이나 REPLACEMENT에 해당하는 부분에서 변수 치환은 일어나지 않는다.
홑 따옴표 이외의 문자를 구분자로 사용하는 경우에는 $를 문자열의 마지막 여부를 판단하는 문자가 아니라 변수로 생각하여, 패턴 검색시마다 변수 치환이 일어난다.


변환자 e
: 오른쪽의 내용을 표현식으로 평가한다.
$_ = 'abc123xyz';
s/d+/$&*2/e;                               # yields 'abc246xyz'
s/\d+/sprintf("%5d", $&)/e;          # yields 'abc  246xyz'
s/\w/$& x 2/eg;                            # yields aabbcc112233xxyyzz'



tr/SEARCHLIST/REPLACEMENTLIST/cds
y/SEARCHLIST/REPLACEMENTLIST/cds

n. y는 tr과 같은 표현이다.

n. SEARCHLIST에 주어진 문자별로 하나씩 살펴보면서, SEARCHLIST에 속하는 문자가 발견되면 해당 문자를 REPLACEMENTLISTd에 해당하는 문자와 바꾼다.

n. 실제로 교환되거나 지워진 글자의 숫자를 반환한다.

n. 한 글자에 대해 여러 가지로 변환될 수 있을 경우에는 가장 처음 것만이 사용된다.
$_ = "AAABCAADEFS";
tr/AAA/XYZ/;                                 # $_ 는 'XXXBCXXDEFS'


변환자 c
: SEARCHLIST의 문자 세트가 반전된다.
: 즉, 실제로는 SEARCHLIST에 포함되지 않은 문자에 대해서 검색이 이루어진다.

변환자 d
:  SEARCHLIST에 지정되어있으나 REPLACEMENTLIST에 주어지지 않은 글자(즉, 찾았으나 교환되지 않은 문자)는 삭제된다.
: 만약 d 변환자를 사용하지 않은 경우, 만일 REPLACEMENTLIST가 SEARCHLIST 보다 짧으면 REPLACEMENTLIST의 마지막 글자가 필요한 숫자만큼 반복된다.
$_ = "abc123";
tr/ab/A/;                                      # $_ 는 "AAc123"
tr/ab/A/d;                                    # $_ 는 "Ac123"


변환자 s
: 같은 글자로 변환되는 일련의(연속되는) 문자는 한 글자로 압축된다. 



위치 문자

: 문자열의 시작에서 일치 (/m 사용시 행의 시작에서 일치)

: 문자열의 끝에서 일치 (/m 사용시 행의 끝에서 일치)

\b
: 단어의 경계에서 일치 (\w 와 \W 사이)

\B 
: 단어 경계를 제외한 곳에서 일치

\A 
: 문자열의 시작에서 일치

\Z 
: 문자열의 끝에서 일치

\G 
: 이전의 m//g가 남긴 부분에서 일치

(?:...)
: (...)와 같은 기능을 하나 재참조 문자열을 만들지는 않는다.

(?=...) 
:  ...부분과 미리 일치(패턴에는 포함되지 않음)

(?!...) 
: ...부분과 미리 불일치 (패턴에는 포함되지 않음)
: /foo(?!bar)/는 "bar"가 바로 뒤에 오지 않는 임의의 "foo"와 일치한다.
: 하지만 /(?!foo)bar/ 와 같이 하여 "bar"앞에 "foo"가 아닌 것이 오는 것과 일치하도록 할 수는 없다.
: 위의 예는 다음과 같이 처리할 수 있다.
if (/foo/ and $` !~ /bar$/)



문자 클래스

\a : 알람(비프 음)
\n : 개행 문자
\r : carriage return
\f : formfeed
\t : 탭 문자
\e : 이스케이프 문

\d : [0-9]
\D : [^0-9]

\w : [a-zA-Z_0-9]
\W : [^a-zA-Z_0-9]

\s : [ \t\n\r\f]
\S : [^ \t\n\r\f]



반환자

$+
: 맨 마지막 괄호와 일치한 것을 반환한다.

$&
: 일치된 전체 문자열을 반환한다.

$`
: 일치된 문자열 앞의 모든 것을 반환한다.
:

[PERL] UTF-8 encoding 으로 파일에 쓰기

CS/Shell/Perl/Python 2010. 8. 17. 01:30
참고 
http://www.ahinea.com/en/tech/perl-unicode-struggle.html

문자(옥텟)열을 저장하기 위해 파일을 열 때 UTF-8로 encoding을 지정

open(FILE, ">:encoding(UTF-8)", "data");


:

[PERL] Timer

CS/Shell/Perl/Python 2010. 8. 16. 12:44
#!/usr/bin/perl                                                                                                                                                 

use Time::HiRes qw(ITIMER_REAL setitimer);

$SIG{ALRM} = sub {
    print "Alarm\n";
};


setitimer(ITIMER_REAL, 0.1, 5);
while (1)
{
    sleep ;
    print "Main Loop\n";
}
:

[SED] Replaces a certain character in a string with a newline in MAC OSX

CS/Shell/Perl/Python 2010. 8. 13. 21:57
참조 : http://www.computing.net/answers/unix/sed-newline/5640.html

리눅스에서는
$ echo Hello_World | sed 's/_/\n/'
Hello
World
로 정상적으로 동작한다.

그러나 Mac OSX의 sed(GNU sed 가 아닌 전통적인 sed - OSF1) 에서는 new line을 직접 quote시켜 주면 된다고 한다. 워~
$ echo Hello_World | sed 's/_/\
> /'




:

[FIND] find using regular expression (-regex)

CS/Shell/Perl/Python 2010. 8. 12. 14:46
find manpage

-regex pattern
: True if the whole path of the file matches pattern using regular expression.  
: To match a file named "./foo/xyzzy", you can use the regular expression ".*/[xyz]*" or ".*/foo/.*", but not "xyzzy" or "/foo/".

manpage에 잘 나와있는데, 제대로 읽어보지도 않고 고생만 했다.
find 시 항상 하던데로 매칭을 "*.html" 과 같이 한것이 원인이었다.
-name과 같이 명시적으로 파일 이름만을 매칭 시키는 것이 아니기 때문에, 전체 패스를 매칭 시켜야 한다.

다음은, html, htm, xhtml, xhtm 파일을 매칭시키는 구문
HTML_FILES=$(find "$SOURCE_WWW_PATH" -iregex ".*\.x\{0,1\}html\{0,1\}")


혹은 -E(extended regular expression)을 사용하여
HTML_FILES=$(find -E "$SOURCE_WWW_PATH" -iregex ".*\.x?html?")

:

[BASH] 공백문자(space)가 포함된 파일패스 list 처리

CS/Shell/Perl/Python 2010. 8. 12. 14:09
FILES=$(find path -name "*.gz")
으로 파일을 찾아 루프로 넘기는 경우

for file in "$FILES"
do
    ...
done

FILES에 공백 문자가 포함된 경우("/root/some path/somefile")
file에는 /root/some 과 path/somefile 이 넘어오게 된다.

이런 경우, find는 \n으로 각 파일패스를 구분하므로, 구분자를 바꾸어 준다.

FILES=$(find path -name "*.gz")
IFS=$'\n"
for file in "$FILES"
do
    ...
done


:

[BASH] rm -rf path/to/delete/*

CS/Shell/Perl/Python 2010. 8. 12. 14:02
path/to/delete 폴더 밑의 모든 파일,폴더를 삭제할 경우

#!/bin/bash
$folders="/path/to/delete"
rm -rf "$folder/*"

과 같이 /* 까지 quote 시키면 삭제되지 않는다. 
(*이 재해석 되는 것인지... 그렇다고 rm -rf '/path/to/delete/*' 로 quote를 해주어도 동작하지 않는것을 보면 globbing 문제 때문인것 같지는 않은데...)

#!/bin/bash
$folders="/path/to/delete"
rm -rf "$folder"/*

* 부분을 quote시키지 않은 경우 정상적으로 동작한다.

:

[SED] edit in place without backup

CS/Shell/Perl/Python 2010. 8. 11. 16:20

man page:
-i 
extension
: Edit files in-place, saving backups with the specified extension. 
: If a zero-length extension is given, nobackup will be saved. It is not recommended to give a zero-length extension when in-place editing files, asyou risk corruption or partial content in situations where disk space is exhausted, etc.

-i 를 사용할 경우 extension이 지정되어야 하므로
$ sed -i -e 's/string/sub/' file
과 같이 사용할 경우 extension이 없어 error가 발생한다.

따라서, 다음과 같이
$ sed -i '' -e 's/string/sub/' file
zero-length extension을 지정하여 백업 파일을 생성하지 않고 in place editing을 할 수 있다.
:

[BASH] Builtin: test, [

CS/Shell/Perl/Python 2010. 8. 5. 09:58
참조

Evaluate a conditional expression expr. Each operator and operand must be a separate argument. Expressions are composed of the primaries described below in Bash Conditional Expressions. test does not accept any options, nor does it accept and ignore an argument of -- as signifying the end of options. 

When the [ form is used, the last argument to the command must be a ]. 

Expressions may be combined using the following operators, listed in decreasing order of precedence. The evaluation depends on the number of arguments; see below. 

! expr
: True if expr is false. 

( expr )
: Returns the value of expr. This may be used to override the normal precedence of operators. 

expr1 -a expr2
: True if both expr1 and expr2 are true. 

expr1 -o expr2
: True if either expr1 or expr2 is true.


산술 비교

val1 -eq val2 
: 변수 val1과 변수 val2 같은 경우 true

val1 -ne val2 
: 변수 val1과 변수 val2 다른 경우 true

val1 -qt val2 
: 변수 val1이 변수 val2 보다 큰 경우 true

val1 -lt val2 
: 변수 val1이 변수 val2 보다 작은 경우 true

val1 -ge val2 
: 변수 val1이 변수 val2 보다 크거나 같은 경우 true

val1 -le val2 
: 변수 val1이 변수 val2 보다 작거나 가은 경우 true


파일 검사

-e 
: 존재하는 파일인 경우 true

-b 
: 파일이 존재하고 블록장치(플로피, 시디롬, ...)인 경우 true

-c 
: 파일이 존재하고 캐릭터 장치 파일인 경우 true

-d 
: 파일이 존재하고 디렉토리인 경우 true

-h
: 파일이 심볼릭 링크

-L
: 파일이 심볼릭 링크

-S
:파일이 소켓

-t
: 파일 디스크립터가 터미널 디바이스와 연관이 있음
: 스크립트의 표준입력([ -t 0 ])이나 표준출력([ -t 1 ])이 터미널인지 아닌지를 확인하는데 쓸 수 있습니다.

-f 
: 파일이 존재하고 보통 파일(디렉토리나 디바이스 파일이 아님)인 경우 true

-h 
: 파일이 존재하고 한 개 이상의 심볼릭 링크가 설정된 경우 true

-p 
: 파일이 존재하고 파이프인 경우 true

-s 
: 파일이 존재하고 0보다 큰 경우 true

-g 
: 파일이 존재하고 SetGID가 설정된 경우 true

-u 
: 파일이 존재하고 SetUID가 설정된 경우 true

-k 
: 파일이 존재하고 Sticky bit가 설정된 경우 true

-r 
: 파일이 존재하고 읽기 가능한 경우 true

-w 
: 파일이 존재하고 쓰기가 가능한 경우 true

-x 
: 파일이 존재하고 실행 가능한 경우 true

-O
: 자신이 소유자임

-G
: 그룹 아이디가 자신과 같음

-N
: 마지막으로 읽힌 후에 변경 됐음

file1 -nt file2
: file1 파일이 file2 파일보다 최신임

file1 -ot file2
: file1 파일이 file2 파일보다 예전것임

file1 -ef file2
: file1 파일과 file2 파일이 같은 파일을 하드 링크하고 있음

문자열 비교
-z string 
: 문자열의 길이가 0인 경우 true

-n string 
: 문자열의 길이가 0이 아닌 경우 true

string1 = string2 
: 문자열 string1과 string2가 일치하는 경우

string1 != string2 
: 문자열 string1과 string2가 일치하지 않는 경우

string : 문자열이 NULL이 아닌 경우

:

Quick Sort

CS/Algorithm 2010. 8. 3. 04:24
 function quicksort(array, left, right)
     var pivot, leftIdx = left, rightIdx = right
     if right > left // only sort if there are >= 2 elements
         pivot = (left + right) / 2
         while leftIdx <= pivot and rightIdx >= pivot
             while array[leftIdx] < array[pivot] and leftIdx <= pivot
                 leftIdx = leftIdx + 1
             while array[rightIdx] > array[pivot] and rightIdx >= pivot
                 rightIdx = rightIdx - 1;
             swap array[leftIdx] with array[rightIdx]
             leftIdx = leftIdx + 1
             rightIdx = rightIdx - 1
             if leftIdx - 1 == pivot
                 pivot = rightIdx = rightIdx + 1
             else if rightIdx + 1 == pivot
                 pivot = leftIdx = leftIdx - 1
         quicksort(array, left, pivot - 1)
         quicksort(array, pivot + 1, right)
void quick_sort(int arr[], int l, int r)
{
	if (l < r) {
		int i=l, j=r, pivot=l+(r-l)/2;
		while (i < j) {
			while (i < pivot && arr[i] <= arr[pivot]) 
				++i;
			while (j > pivot && arr[j] >= arr[pivot])
				--j;
			swap_arr(arr, i, j);
			++i, --j;
			if (i-1 == pivot)
				pivot = j = j+1;
			else if (j+1 == pivot)
				pivot = i = i-1;
		}
		qsort_2(arr, l, pivot-1);
		qsort_2(arr, pivot+1, r);
	}
}



  // left is the index of the leftmost element of the array
  // right is the index of the rightmost element of the array (inclusive)
  //   number of elements in subarray: right-left+1
  function partition(array, left, right, pivotIndex)
     pivotValue := array[pivotIndex]
     swap array[pivotIndex] and array[right] // Move pivot to end
     storeIndex := left 
     for i  from  left to right - 1 // left ≤ i < right 
         if array[i] ≤ pivotValue
             swap array[i] and array[storeIndex]
             storeIndex := storeIndex + 1
     swap array[storeIndex] and array[right] // Move pivot to its final place
     return storeIndex
 procedure quicksort(array, left, right)
     if right > left // subarray of 0 or 1 elements already sorted
         select a pivot index //(e.g. pivotIndex := left + (right - left)/2)
         pivotNewIndex := partition(array, left, right, pivotIndex)
         // element at pivotNewIndex is now at its final position and never moved again
         //   and guarantees termination: recursive calls will sort smaller array
         // recursively sort elements on the left of pivotNewIndex
         quicksort(array, left, pivotNewIndex - 1)
         // recursively sort elements on the right of pivotNewIndex
         quicksort(array, pivotNewIndex + 1, right)


int partition(int arr[], int l, int r, int pivot)
{ int pivot_val = arr[pivot]; int sorted_index = l, i; swap_arr(arr, pivot, r); for (i=l; i < r; ++i) { if (arr[i] <= pivot_val) { swap_arr(arr, i, sorted_index); sorted_index++; } } swap_arr(arr, sorted_index, r); return sorted_index; } void quick_sort(int arr[], int l, int r) { if (l < r) { int pivot = partition(arr, l, r, (l+r)/2); qsort_1(arr, l, pivot-1); qsort_1(arr, pivot+1, r);; } }

:

[IPHONE] There are three ways to access the contents of a NIB.

CS/iPhone 2010. 8. 2. 09:40

원문 :

Cocoa-dev mailing list

subject : [iPhone] Nib Loading Question


There are three ways to access the contents of a NIB.


1. Via -[UIViewController initWithNibName:bundle:], which connects the

references to outlets in File's Owner (the view controller itself). If a root object in the NIB doesn't have a link to the owner's outlet, that object is adrift and goes away at the next autorelease drain.


2. Via -[NSBundle loadNibNamed:owner:options:], you specify an owner object,

which again gets its IBOutlets filled in from links to File's Owner in the NIB. No link, no object.


3. By taking the NSArray returned by -[NSBundle loadNibNamed:owner:options:],

usually with owner: set to nil (though that's not required). The array contains all the root objects in the NIB.


Let's simplify for a beginner, concentrating only on how the nib's top-level objects are accessed, and for a moment ignoring the question of how the nib gets loaded in the first place.


There are *two* ways to access to the top-level objects of a nib: either through the NSArray returned by -[NSBundle loadNibNamed:owner:options:], or through a chain of outlets rooted in the instance that owns the nib at the time it loads (represented in the nib by the file's owner proxy). You (the beginner) will almost certainly use the latter. Back your outlets by a retain-policy setter (typically thru a property and synthesized accessors), since otherwise the loaded object will vanish in a puff of smoke and you'll crash when you send a message to a dangling pointer.

:

[Windows] Keyboard type 3로 변경

TIPs 2010. 7. 30. 09:30
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\i8042prt\Parameters]

LayerDriver KOR= kbd101a.dll -> kbd101c.dll
OverrideKeyboardSubtype= 3 -> 5

OverrideKeyboardIdentifier --> PCAT_101CKEY
OverrideKeyboardType --> 8
:

[BASH] 변수

CS/Shell/Perl/Python 2010. 7. 27. 14:42

원문 : 고급 Bash 스크립팅 가이드

1. 위치 매개 변수

$0, $1, $2, etc.
: 위치 매개변수로서, 명령어줄에서 스크립트로 넘겨지거나 함수로 넘겨지거나 set 명령어로 강제로 설정됨.

$#
: 명령어줄 인자의 갯수나 위치 매개변수들

$*
: 한 낱말로 표시되는 위치 매개변수들 모두

$@
: $*과 똑같지만 각 매개변수는 쿼우트된 문자열로 취급됩니다. 즉, 해석되거나 확장없이 있는 그대로 넘겨집니다. 그 결과로 각 인자는 각각이 서로 다른 낱말로 구분돼서 표시됩니다.


2. 내장 변수

$GROUPS
: 현재 사용자가 속해 있는 그룹. /etc/passwd에 적혀 있는 현재 사용자의 그룹 아이디 값을 보여줍니다.

$HOME
: 사용자의 홈 디렉토리로, 보통은 /home/username (예 9-10 참고)

$IFS
: 입력 필드 구분자
: 디폴트는 공백문자(빈칸, 탭, 뉴라인)지만 콤마로 구분된 데이타 파일을 파싱하려는 경우처럼 변경이 가능. $*는 $IFS의 첫번째 문자를 사용하는 것에 주의
ex)
$ bash -c 'set w x y z; IFS=":-;"; echo "$*"'
w:x:y:z

$PATH
:실행 파일의 경로, 보통은 /usr/bin/, /usr/X11R6/bin/, /usr/local/bin, 등등.

$PPID
: 어떤 프로세스의 부모 프로세스의 프로세스 아이디(pid)

$UID
: 사용자 아이디 값. /etc/passwd에 저장되어 있는 현재 사용자의 사용자 식별 숫자

$PS1
: 명령어줄에서 볼 수 있는 메인 프롬프트.

$PS2
: 2차 프롬프트로, 추가적인 입력이 필요할 때 ">" 로 표시됨.

$PS3
: 3차 프롬프트로 select 루프문에서 표시됨.

$PS4
: 4차 프롬프트로, 스크립트에 -x 옵션이 걸려서 실행될 때 스크립트의 매 줄마다 "+"로 표시됨.

$PWD
: 작업 디렉토리(현재 있는 디렉토리)


3. 특수 매개변수

$-
: 스크립트로 넘겨진 플래그들

$!
: 백그라운드로 돌고 있는 가장 최근 작업의 PID (process id)

$_
: 바로 이전에 실행된 명령어의 제일 마지막 인자로 설정되는 특수 변수.

$?
: 명령어나 함수, 스크립트 자신의 종료 상태.

$$
: 스크립트 자신의 프로세스 아이디로 보통 임시 파일 이름을 만들 때 사용.

:

[MAC] Mac OS X 10.2 이후에서의 Local Hosts File 위치

TIPs 2010. 6. 16. 11:47

/private/etc/hosts
:

[MAKE] Target

CS/Shell/Perl/Python 2010. 6. 4. 10:29
Internal Macro
원문 : KLDP

$*
: 확장자가 없는 현재의 목표 파일(Target)

$@
: 현재의 목표 파일(Target)

$<
: 현재의 목표 파일(Target)보다 더 최근에 갱신된 파일 이름

$?
:현재의 목표 파일(Target)보다 더 최근에 갱신된 파일이름

:

build된 SDK 사용시 W/ResourceType(31706): Unable to get buffer of resource asset file 에러

CS/Android 2010. 4. 16. 14:01
원문 : Using the Android SDK tools

When building you might run into the Unable to get buffer of resource asset file error. 
The root cause of this is that the new android resource file resources.arsc is larger than the aapt tool allows. 
You can exchange the .arsc file inside android.jar with an older version or patch the aapt tool by editing frameworks/base/include/utils/Asset.h.
Change both lines UNCOMPRESS_DATA_MAX = 1 * 1024 * 1024 to something bigger. As the new resources file currently has a size of 2.3Mb you should change the lines (both lines mind you) to at least 3*1024*1024.
:

ETC ...

CS/Android 2010. 4. 16. 13:57
1. 부분 compile
참조 : android pub
$source build/envsetup.sh
$mmm packages/apps/Contacts
$make snod
$make sdk

2. tools/emulator 환경설정(빌드 이미지)
export ANDROID_PRODUCT_OUT=/android_source_path/out/target/product/generic

3. eclipse .classpath 위치
$cp /android_source_path/development/ide/eclipse/.classpath /android_source_path/.
(eclipse에서 직접 android 소스 받는 방법 추가)

4. .apk
설치 : adb install apkfilename
삭제 : adb uninstall pakeagename
재설치 : adb install -r apkfilename
:

Emacs Javascript

TIPs 2010. 3. 25. 10:50
참고 : Emacs 패키지 설치하기

download : http://www.emacswiki.org/emacs/JavaScriptMode
(setq load-path (cons (expand-file-name "~/.emacs.d") load-path))
(load-library "javascript")


:

Gitosis를 이용한 Git server 설치

TIPs 2010. 3. 25. 10:43
[Local]
: 인증키 생성 후 Server에 전달
$ ssh-keygen -t rsa

[Server]
: Local의 Admin의 계정 생성
$ sudo adduser \
    --system \
    --shell /bin/sh \
    --gecos 'git version control' \
    --group \
    --disabled-password \
    --home /var/git \
    git

: Gitosis 초기화. 여기서 rsa는 Local에서 복사한 rsa를 사용.
$ sudo -H -u git gitosis-init < /path/to/id_rsa.pub

[Local]
: 복제
$ pwd
/home/cwpark/xxx
$ git clone git@192.168.0.6:gitosis-admin.git

: 그룹 추가 (example)
[group android]
writable = android
members = newmember

newmember는 android에 writable.
gitosis.conf 에 멤버(newmember) 추가하고, 해당 멤버의 RSA얻어와 keydir/newmember.pub 로 저장

: Commit
$ git commit -a -m "comment"

: Push
$ git push



01. repo/new$ git init
02. repo/new$ git remote add origin git@192.168.0.6:android.git
03. 하나의 commit 생성
04. repo/new$ git push origin master (git push origin master:refs/heads/master)



* key 확장자 .pub 확인
* 시간 동기화 확인 : rdate -s time.bora.net

:

Ubuntu 9.10 에서 JDK 5 설치

TIPs 2010. 2. 13. 15:25
1. Repository 추가
deb http://ko.archive.ubuntu.com/ubuntu/ jaunty multiverse
deb http://ko.archive.ubuntu.com/ubuntu/ jaunty-updates multiverse

2. Package install
# aptitude install sun-java5-jdk

3. Version 관리
# update-alternatives --config java
# update-alternatives --config javac

4. 환경변수 설정
export JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun

* sun에서 Down받아 설치하는 방법
1. jdk1.5.0_XX.bin 다운 받아 실행하여 압축 해제
2. /usr/local/jdk1.5.0_XX 로 move
3 update-alternatives --install "/usr/bin/java" "java" "/usr/local/jdk1.5.0XX/bin/java" 1
  or
  /usr/local/jdk1.5.0_XX를 Symbolic Link로 만들고 PATH에 추가 -0-

:

Reference to Pointer

CS/C/C++ 2010. 1. 26. 03:51
일단 간단한 예제는...
void set_p(int* p, int val)   { p = new int(val); }
void set_pr(int*& p, int val) { p = new int(val); }

int main(void)
{
    int *a;

    // set_p(a, 10);
    set_pr(a, 10);
    cout << *a << endl;    

    // ...

    return 0;
}

WebKit Code에서 사용된 예,
if (JSGlobalObject*& headObject = head()) {
        d()->prev = headObject;
        d()->next = headObject->d()->next;
        headObject->d()->next->d()->prev = this;
        headObject->d()->next = this;
} else {
        headObject = d()->next = d()->prev = this;
}
head()가 NULL인 경우 처리가 참 깔끔하게 된다...
:

emacs & cscope

TIPs 2010. 1. 21. 12:05
참조 :
KLDP
http://www.cs.cmu.edu/cgi-bin/info2www?(emacs)Find%20Tag
Ubuntu forums
Blog

ETAGS

tag 생성
$ find . -name '*.[csSh]' | etags -
$ find . -name '*.cc' -or -name '*.h' | etags -

M-. TAG        Find first definition of TAG (`find-tag').
M-*            Pop back to where you previously invoked `M-.' and friends.
C-u M-.        Find next alternate definition of last tag specified.
C-u - M-.      Go back to previous tag found.
C-M-. PATTERN  Find a tag whose name matches PATTERN (`find-tag-regexp').
C-u C-M-.      Find the next tag whose name matches the last pattern used.
C-x 4 . TAG    Find first definition of TAG, but display it in another window (`find-tag-other-window').
C-x 5 . TAG    Find first definition of TAG, and create a new frame to select the buffer (`find-tag-other-frame').



CSCOPE

cscope download : http://cscope.sourceforge.net/
emacs el package load : (require ‘xcscope)
xcscope.el : /usr/share/emacs/site-lisp
Database 생성 : cscope-index-files

C-c s s     Find symbol.
C-c s d     Find global definition.
C-c s g     Find global definition (alternate binding).
C-c s G     Find global definition without prompting.
C-c s c     Find functions calling a function.
C-c s C     Find called functions (list functions called from a function).
C-c s t     Find text string.
C-c s e     Find egrep pattern.
C-c s f     Find a file.
C-c s i     Find files #including a file.

: