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

  1. 2014.08.05 [LINUX] burn a DVD ISO
  2. 2014.03.26 SSH login without password
  3. 2013.12.09 Linux NAT server forwarding [ubuntu]
  4. 2013.08.13 [SHELL] 특수 변수
  5. 2013.03.04 [Linux] Emacs tomorrow theme
  6. 2013.03.04 [Linux] gnome-terminal 256 color 사용
  7. 2012.11.01 Linux IO Stack Diagram
  8. 2012.11.01 이미지 파일 생성 / 마운트
  9. 2012.02.10 Apache + mod_wsgi + Django install from source
  10. 2012.01.24 [IPHONE] UUID 생성
  11. 2012.01.14 [IPHONE] TableViewCell style
  12. 2012.01.13 [IPHONE] UI Element size
  13. 2012.01.12 [IPHONE] Using Core Data
  14. 2011.12.29 [IPHONE] Core Data Core Competencies
  15. 2011.12.29 [IPHONE] 나눔고딕 적용
  16. 2011.10.18 [Linux] CPU 관련 정보 보기
  17. 2011.10.13 [Mac] Mac USB to Serial (RS232)
  18. 2011.09.08 Ubuntu에서 고정 IP 설정
  19. 2011.09.08 SSH login without password
  20. 2011.07.28 Ubuntu에서 패키지 잠그기/풀기
  21. 2011.07.28 http proxy 사용
  22. 2011.07.27 [MAC] 맥에서 USB에 부팅가능한 이미지 만들기 (bootable USB stick) 1
  23. 2011.06.08 [MAKE] Functions for Transforming Text
  24. 2011.06.08 [MAKE] Conditional Parts
  25. 2011.06.08 [MAKE] How to Use Variables
  26. 2011.05.25 특권 레벨 (Privilege ring level)
  27. 2011.05.20 Why not mmap?
  28. 2011.04.24 [BASH, PERL] Multiline string
  29. 2011.04.15 [PERL] 최소 일치 정규 표현식 (Non-greedy regular expression)
  30. 2011.03.14 [JAVASCRIPT] location.href 와 location.replace()

[LINUX] burn a DVD ISO

TIPs 2014. 8. 5. 16:26


# wodim --devices

# wodim -v dev=/dev/sg1 speed=4 -eject /path/to/file.iso


:

SSH login without password

CS/Linux 2014. 3. 26. 15:01

원문 : http://www.linuxproblem.org/art_9.html


a@A 에서 b@B 로 password 없이 로그인

a@A:~> ssh-keygen -t rsa
a@A:~> cat .ssh/id_rsa.pub | ssh b@B 'cat >> .ssh/authorized_keys'


:

Linux NAT server forwarding [ubuntu]

CS/Network 2013. 12. 9. 20:52

원문 :

http://www.linuxrookie.com/?p=160

http://www.howtoforge.com/nat_iptables


private interface : eth1

public   interface : eth0


1. Open the forward option

# echo 1 > /proc/sys/net/ipv4/ip_forward

or

# vim /etc/sysctl.conf  change net.ipv4.ip_forward = 0,let 0 to 1


2. Config NAT rules

# iptables –t nat –A POSTROUTING –s 192.168.100.0/24 –o eth0 –j MASQUERADE

# iptables –A FORWARD –i eth1 –j ACCEPT


3. Permanently update iptables

# apt-get install iptables-persistent

# iptables-save > /etc/iptables/rules.v4



:

[SHELL] 특수 변수

CS/Shell/Perl/Python 2013. 8. 13. 10:27

원문 : http://unixhelp.ed.ac.uk/scrpt/scrpt2.2.2.html


 Name 

 Description

 $1 - $9

 위치 파라미터의 값

 $0

 현재 실행되고 있는 command의 이름

 $#

 위치 파라미터의 개수

 $?

 가장 마지막에 실행된 command의 exit status

 $$

 현재 shell의 pid

 $!

 background 에서 가장 마지막에 실행된 pid

 $-

 the current options supplied to this invocation of the shell

 $*

 a string containing all the arguments to theshell, starting at $1

 $@

 same as above, except when quoted


:

[Linux] Emacs tomorrow theme

TIPs 2013. 3. 4. 18:03

링크:

https://github.com/chriskempson/tomorrow-theme/tree/master/GNU%20Emacs

https://code.google.com/p/princess-alist/source/browse/trunk/home/xiaogaozi/.emacs.d/site-lisp/color-theme-tomorrow.el?r=123

color-theme-tomorrow.el


(setq load-path (cons (expand-file-name "~/.emacs.d") load-path))

(load-library "color-theme-tomorrow")

(color-theme-tomorrow-night)


현재 터미널이 256 칼라가 아니라면

$ tput colors

8

256 color 설정

export TERM="xterm-256color"


:

[Linux] gnome-terminal 256 color 사용

TIPs 2013. 3. 4. 17:46


export TERM="xterm-256color"


:

Linux IO Stack Diagram

CS/Linux 2012. 11. 1. 22:33
:

이미지 파일 생성 / 마운트

CS/Linux 2012. 11. 1. 22:06

# dd if=/dev/zero of=disk.img bs=4k count=1024

# mkfs.ext3 -F disk.img


# mount -o loop disk.img mount_point

or

# losetup /dev/loop0 disk.img

# mount /dev/loop mount_point


:

Apache + mod_wsgi + Django install from source

Develop/Web 2012. 2. 10. 20:43

OpenSSL (필요한 경우만)


http://www.openssl.org/
http://httpd.apache.org/docs/2.0/mod/mod_ssl.html
 

# ./config --prefix=/path/to/openssl
# make; make install 

# openssl genrsa -des3 -out server.key 1024
# openssl req -new -key server.key -out server.csr
# openssl x509 -req -days 90 -in server.csr -signkey server.key -out server.crt

 


Apache


http://httpd.apache.org/

[mpm-worker]
# ./configure --prefix=/path/to/apache --enable-so --with-mpm=worker

[mpm-worker, ssl]
# ./configure --prefix=/path/to/apache  --enable-so --with-mpm=worker \
> --enable-ssl --with-ssl=/path/to/openssl

(debug mode)
--enable-maintainer-mode

# make; make install 


extra/httpd-wcgi.conf 생성
http://blog.stannard.net.au/2010/12/11/installing-django-with-apache-and-mod_wsgi-on-ubuntu-10-04/ 
http://gauryan.blogspot.com/2010/10/apache-django-modwsgi.html
http://bryanhelmig.com/setting-up-ubuntu-10-04-with-apache-memcached-ufw-mysql-and-django-1-2-on-linode/ 
https://code.djangoproject.com/wiki/django_apache_and_mod_wsgi 
http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango 

LoadModule wsgi_module modules/mod_wsgi.so


NameVirtualHost *:80

<VirtualHost *:80>

    ServerName localhost

    DocumentRoot /app/foo


    <Location />
        Order allow,deny

        Allow from all

    </Directory>


    # setting 에서 static file을 /app/foo/static 으로 한 경우 
    Alias /static /app/foo/static
    <Location /static>
        Order allow,deny
        Allow from all
    </Location> 


    WSGIScriptAlias / /app/foo/django.wsgi

</VirtualHost>


httpd.conf 파일 수정

DocumentRoot /path/to/document/root
ServerName MyServerName:80 
<Directory "/path/to/document/root">
    ... 
 
</Directory>

Include conf/extra/httpd-mpm.conf
Include conf/extra/httpd-default.conf
Include conf/extra/httpd-wcgi.conf  


포트 막혀있는 경우 80번 열어주기

/etc/sysconfig/iptables 에 다음 추가

-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT

# /etc/init.d/iptables restart
혹은
# service iptables restart 




Python


http://python.org/getit/ 

# ./configure --prefix=/path/to/python \
--enable-shared

# make; make install 




mod_wsgi


http://code.google.com/p/modwsgi/wiki/QuickInstallationGuide
http://code.google.com/p/modwsgi/wiki/PerformanceEstimates

# ./configure --with-apxs=/path/to/httpd/bin/apxs \
> --with-python=/path/to/pythton/bin/python

 

# make; make install 



Django


https://www.djangoproject.com/download/

# python setup.py install




Sample Project


# cd /app/
# django-admin.py startproject foo
# cd /app/foo
# ls
__init__.py  __init__.pyc  manage.py  settings.py  urls.py  urls.pyc

# cat > django.wsgi
import os

import sys

sys.path.append('/app/')

os.environ['DJANGO_SETTINGS_MODULE'] = 'foo.settings'


import django.core.handlers.wsgi

application = django.core.handlers.wsgi.WSGIHandler()



:

[IPHONE] UUID 생성

CS/iPhone 2012. 1. 24. 17:52
원문 : http://stackoverflow.com/questions/7016311/how-to-generate-unique-identifier

+ (NSString *)uuid

{

    CFUUIDRef uuidRef = CFUUIDCreate(NULL);

    CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);

    CFRelease(uuidRef);

    return [(NSString *)uuidStringRef autorelease];

}

 
:

[IPHONE] TableViewCell style

CS/iPhone 2012. 1. 14. 22:41
원문 : http://borkware.com/quickies/one?topic=UITableView

 
:

[IPHONE] UI Element size

CS/iPhone 2012. 1. 13. 13:33
:

[IPHONE] Using Core Data

CS/iPhone 2012. 1. 12. 23:20
원문 : http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreData/cdProgrammingGuide.html

Managed Object

Custom implementation

- NSManagedObject의 서브클래스에 대해 작성하는 accessor methods의 구현에는 일반적으로 다른 클래스를 작성하는것과는 다르다.
  • 만약 custom instance variable을 제공하지 않는다면, primitive accessor method를 사용하여 internal store로 값을 저장하고, internal store로 부터 property value를 가져오게 된다. 
  • NSManagedObject 는 modeld properties에 대해서 automatic KVO  change notification 을 비활성화 하며, primitive accessor methods는 access notification method와 change notification method를 invoke하지 않는다.
  • Entity model에서 정의되지 않은 property들의 accessor method에서, automatic change notification을 활성화 하거나 적절한 change notification method를 invoke할 수 있다.

Creating

NSManagedObject *newEmployee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee"

                                                             inManagedObjectContext:context];


NSManagedObject *newEmployee = [[NSManagedObject alloc] initWithEntity:employeeEntity

                                        insertIntoManagedObjectContext:context];



Entity Description

NSManagedObjectContext *context = <#Get a context#>;

NSManagedObjectModel *managedObjectModel = [[context persistentStoreCoordinator] managedObjectModel];

NSEntityDescription *employeeEntity = [[managedObjectModel entitiesByName] objectForKey:@"Employee"];


NSManagedObjectContext *context = <#Get a context#>;

NSEntityDescription *employeeEntity = [NSEntityDescription entityForName:@"Employee"

                                                  inManagedObjectContext:context];



Deleting

NSManagedObjectContext *context = <#Get a context#>;

[context deleteObject:managedObject];


- managed object context에 deleteObject: 메세지를 보내면, context는 NSManagedObjectContextObjectsDidChangeNotification 통지를 post한다.
- 만약 object가 동일한 transaction에서 create되고 delete 된다면, managed object context의 deletedObject 의 결과 array나 NSManagedObjectContextDidSaveNotification 통지의 deleted object set에 나타나지 않을 것이다. 



To-many relationships

NSMutableSet *employees = [aDepartment mutableSetValueForKey:@"employees"];

[employees addObject:newEmployee];

[employees removeObject:firedEmployee];


// or


[aDepartment addEmployeesObject:newEmployee];

[aDepartment removeEmployeesObject:firedEmployee];


- mutableSetValueForKey: 에 의해 리턴되는 값과 dot accessor method에 의해 리턴되는 값의 차이를 이해하는 것은 중요하다.
- mutableSetValueForKey:는  mutable proxy object를 리턴한다.
- 만약 그것의 내용을 바꾼다면, relationship에 대한 적절한 KVO change 통지를 emit 할 것이다. 
- dot accessor 는 단순히 set을 리턴한다.
- 만약 [aDepartment.employees addObject:newEmployee] 와 같이 한다면, KVO change notification은  emit 되지 않을 것이며, inverse relationship은 적절하게 update되지 않을 것이다. 
- dot 은 accessor method를 invoke 하기 떄문에, [[aDepartment employees] addObject:newEmployee]; 도 같은 결과이다. 



Manipulating Relationships and Object Graph Integrity

- Core Data 는 object graph의 consistency를 관리하기 때문에, 관계의 한쪽 끝만을 변경하면 다른 면은 Core Data 가 관리해 준다.


anEmployee.department = newDepartment;

or

[newDepartment addEmployeeObject:anEmployee]; 



Managed Object Context

Undo management

- 각 managed object context는 undo manager를 유지한다.
- Undo 비활성화

[context processPendingChanges]; // Flush operations for which you want undos

[[context undoManager] disableUndoRegistration];


// Make changes for which undo operations are not to be recorded

// ...


[context processPendingChanges]; // Flush operations for which you do not want undos

[[context undoManager] enableUndoRegistration];




Managed Object Model

Runtime에  NSManagedObjectModel 얻기

[[<#A managed object context#> persistentStoreCoordinator] managedObjectModel];
[[<#A managed object#> entity] managedObjectModel];  



Fetch

Fetching managed objects

NSManagedObjectContext *context = [self managedObjectContext];

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Employee"

                                                     inManagedObjectContext:context];

NSFetchRequest *request = [[NSFetchRequest alloc] init];

[request setEntity:entityDescription];


NSNumber *minimumSalary = ...;

NSPredicate *predicate = [NSPredicate predicateWithFormat:

                          @"(lastName LIKE[c] 'Worsley') AND (salary > %@)", minimumSalary];

[request setPredicate:predicate];


NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES];

[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];

[sortDescriptor release];


NSError *error = nil;

NSArray *array = [context executeFetchRequest:request error:&error];
[request release];
 

- transient properties에 기반한 predicate를 사용해서 fetch할 수는 없다.

 

Template 사용

NSManagedObjectModel *model = <#Get a model#>;

NSFetchRequest *requestTemplate = [[NSFetchRequest alloc] init];

NSEntityDescription *publicationEntity = [[model entitiesByName] objectForKey:@"Publication"];

[requestTemplate setEntity:publicationEntity]; 

NSPredicate *predicateTemplate = [NSPredicate predicateWithFormat:

                                  @"(mainAuthor.firstName like[cd] $FIRST_NAME) AND \

                                  (mainAuthor.lastname like[cd] $LST_NAME) AND \

                                  (publicationDate > $DATE)"]; 

[requestTemplate setPredicate:predicateTemplate]; 

[model setFetchRequestTemplate:requestTemplate forName:@"PublicationsForAuthorSinceDate"]; 

[requestTemplate release];

 

NSError *error = nil;

NSDictionary *substitutionDictionary = [NSDictionary dictionaryWithObjectsAndKeys:

                                        @"Fiona", @"FIRST_NAME",

                                        @"Verde", @"LAST_NAME",

                                        [NSDate dateWithTimeIntervalSinceNow:-31356000], @"DATE",

                                        nil];

NSFetchRequest *fetchRequest = [model fetchRequestFromTemplateWithName:@"PubliccationsForAuthorSinceDate"

                                                 substitutionVariables:substitutionDictionary]; 

NSManagedObjectContext *context = <#Get a managed object context#>;

NSArray *results = [context executeFetchRequest:fetchRequest error:&error];



Retrieving specific objects

NSManagedObjectContext *context = [self managedObjectContext];

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Employee"

                                                     inManagedObjectContext:context];

NSFetchRequest *request = [[NSFetchRequest alloc] init];

[request setEntity:entityDescription];

[request release];


NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self == %@", targetObject];

[request setPredicate:predicate];


NSError *error = nil;

NSArray *array = [context executeFetchRequest:request error:&error];


:

[IPHONE] Core Data Core Competencies

CS/iPhone 2011. 12. 29. 21:39
:

[IPHONE] 나눔고딕 적용

CS/iPhone 2011. 12. 29. 03:25
참고 : http://kgriff.posterous.com/45359635

1. plist 에 폰트 등록

<key>UIAppFonts</key>
<array>
<string>NanumGothicExtraBold.ttf</string>
<string>NanumGothicBold.ttf</string>
<string>NanumGothic.ttf</string>
</array>

혹은  "Fonts provided by application" 에 추가

OTF는 시뮬러에터에서는 동작하나, Device 에서 동작 안하는듯. (확인 필요)

2. 사용

[UIFont fontWithName:@"NanumGothicExtraBold" size:22.0];
[UIFont fontWithName:@"NanumGothicBold" size:22.0];
[UIFont fontWithName:@"NanumGothic" size:22.0]; 



Device 에서 보았을 때, 그다지 깔끔하지 않은 것 같음. OTL...

:

[Linux] CPU 관련 정보 보기

TIPs 2011. 10. 18. 08:10
1. cat /proc/cpuinfo
2. lscpu
3. /sys/devices/system/cpu/cpuN 밑의 정보 보기
4. dmesg 에서 보기
:

[Mac] Mac USB to Serial (RS232)

TIPs 2011. 10. 13. 18:27
Driver Download : http://www.ftdichip.com/FTDrivers.htm

확인 : ls /dev/tty.*

연결 : screen /dev/tty.usbserial-xxxxx 115200
 
:

Ubuntu에서 고정 IP 설정

CS/Linux 2011. 9. 8. 13:38
/etc/network/interfaces

auto lo

iface lo inet loopback


auto eth0

iface ethX inet static

address X.X.X.X

netmask 255.255.255.0

gateway X.X.X.X

dns-nameservers 8.8.8.8


/etc/resolv.conf

nameserver 8.8.8.8


:

SSH login without password

CS/Linux 2011. 9. 8. 13:29
원문 : http://linuxproblem.org/art_9.html

a@A:~> ssh-keygen -t rsa
a@A:~> ssh b@B mkdir -p .ssh
a@A:~> cat .ssh/id_rsa.pub | ssh b@B 'cat >> .ssh/authorized_keys'


:

Ubuntu에서 패키지 잠그기/풀기

TIPs 2011. 7. 28. 14:38
원문 : http://nice295.egloos.com/1305825

1. Hold

# echo -e "package hold" | dpkg --set-selections


2.  Unhold

# echo -e "package unhold" | dpkg --set-selections


3. 확인 

#dpkg --get-selections | grep hold

 
:

http proxy 사용

TIPs 2011. 7. 28. 14:26
원문 : http://nice295.egloos.com/1305825

1. .bashrc에 아래 추가

export http_proxy=http://<your_PROXY_SERVER>:<port>



2. /etc/apt/apt.conf에 아래 추가(다른 app를 위한 것)

Acquire::http::Proxy "http://<your_PROXY_SERVER>:<port>";


:

[MAC] 맥에서 USB에 부팅가능한 이미지 만들기 (bootable USB stick)

TIPs 2011. 7. 27. 15:35
원문 : http://renevanbelzen.wordpress.com/2009/10/14/creating-a-bootable-usb-stick-with-mac-os-x-in-10-easy-steps/

USB 삽입 후

1. USB 디바이스 이름 확인.
$ diskutil list

2. 언마운트
$ diskutil unmountDisk /dev/diskN

3. 복사
$ sudo dd if=/path/to/file.dmg of=/dev/diskN bs=1m

4. 추출
diskutil eject /dev/diskN

:

[MAKE] Functions for Transforming Text

CS/Shell/Perl/Python 2011. 6. 8. 16:43
원문 : GNU make

8.4 Functions for Conditionals

 
조건 표현을 제공하는 세 가지 함수가 있다. 모든 인자가 초기에 확장되지 않는다는 것이 이 세 함수의 중요한 면이다. 인자 중 확장되기를 원하는 인자만이 확장된다.
  1. $(if condition, then-part [,else-part])
    if함수는 함수적 문맥에서 조건적 확장에 대한 지원을 제공한다.
    첫 번째 인자인 condition은 먼저 모든 시작과 끝의 공백 문자를 제거하고, 그 이후에 확장된다. 만약 확장이 non-empty 문자열이라면 그 조건은 참으로 간주되며, 그렇지 않은 경우 거짓으로 간주된다.
    만약 조건이 참이라면 두 번째 인자인 then-part가 평가되고, 이것이 if 함수 전체 평가의 결과로 사용된다.
    만약 조건이 거짓이라면 세 번째 인자인 else-part가 평가되고, 이것이 If 함수 전체 평가의 결과로 사용된다. 만약 세 번째 인자가 없다면, if 함수는 아무것도 평가하지 않는다.
    주의할 것은 오직 the-part나 else-part만 평가되고, 두 부분이 모두 평가되지 않는다는 것이다. 따라서 side-effect가 발생할 수 있다.
     
  2. $(or condition1 [, condition2 [, condition3 ...]])
    or 함수는 "short-circuiting" OR 연산을 제공한다. 각 인자는 순서대로 확장된다. 만약 인자가 non-empty 문자열로 확장된다면 처리는 멈추고 그 확장의 결과가 결과 문자열이 된다. 만약 모든 인자가 확장되었고 모두가 거짓(empty)이라면, 확장의 결과는 빈 문자열이다.

  3.  $(and condition1 [, condition2 [, condition3 ...]])
    or 함수는 "short-circuiting" AND 연산을 제공한다. 각 인자는 순서대로 확장된다. 만약 인자가 empty 문자열로 확장된다면 처리는 멈추고 그 확장의 결과가 결과 문자열이 된다. 만약 모든 인자가 non-empty string으로 확장되었다면, 확장의 결과는 마지막 인자의 확장이 된다.
.
:

[MAKE] Conditional Parts

CS/Shell/Perl/Python 2011. 6. 8. 15:18
원문 GNU make
 

7.1 Example of a Conditional 


다음 예제는 CC변수가 gcc인 경우에 make가 라이브러리들 중 하나의 셋을 사용하게 하고, gcc가 아닌 경우에는 다른 라이브러리 셋을 사용하게 한다.

libs_for_gcc = -lgnu
normal_libs =

foo: $(objects)
ifeq ($(CC),gcc)
    $(CC) -o foo $(objects) $(libs_for_gcc)
else
    $(CC) -o foo $(objects) $(normal_libs)
endif

 
 혹은, 다음과 같이 변수를 조건부로 할당하고, 변수를 명시적으로 사용할 수도 있다

libs_for_gcc = -lgnu
normal_libs =

ifeq ($(CC),gcc)
    libs=$(libs_for_gcc)
else
    libs=$(normal_libs)
endif

foo: $(objects)
    $(CC) -o foo $(objects) $(libs) 

 

7.2 Syntax of Conditionals


syntax는 else가 없는 다음의 가장 간단한 형태부터 else를 포함한 두가지 형태가 있다.

conditional-directive
text-if-true
endif

conditional-directive
text-if-true
else
text-if-false
endif

conditional-directive
text-if-true
else
text-if-false
else
text-if-false
endif


조건을 테스트하는데는 다음의 4가지 지시자가 있다
  1. ifeq
    • iffeq (qrg1, arg2)
    • ifeq 'arg1' 'arg2'
    • ifeq "arg1" "arg2"
    • ifeq "arg1" 'arg2
    • 'ifeq 'arg1' "arg2"
      arg1과 arg2에 있는 변수의 참조를 모두 확장하여 그들을 비교한다. 만약 일치한다면 text-if-true 가 적용된다.
       
  2. ifneq
    • ifneq (qrg1, arg2)
    • ifneq 'arg1' 'arg2'
    • ifneq "arg1" "arg2"
    • ifneq "arg1" 'arg2'
    • ifneq 'arg1' "arg2"
      arg1과 arg2에 있는 변수의 참조를 모두 확장하여 그들을 비교한다. 만약 일치하지 않는다면 text-if-true 가 적용된다.
       
  3. ifdef variable-name
    name은 변수에 대한 레퍼런스가 아니라 변수의 이름을 나타낸다.

    bar = true
    foo = bar
    ifdef $(foo)
        frobozz = yes
    endif 

    $(foo)는 확장되어 bar가 되고, bar는 참조가 아니라 이름으로 간주된다. 


    만약 variable-name이 non-empty 값이 아니라면 text-if-true 가 적용된다.

    ifdef는 변수를 확장하여 그 값이 비어있는지는 확인하지 않는다(그 이름이 정의 되어 있는지만 확인). non-empty인지 확인하기 위해서는 ifeq($(foo),)를 사용한다.

    bar =
    foo = $(bar)
    ifdef foo
        frobozz = yes
    else
        frobozz = no
    endif

    sets ‘frobozz’ to ‘yes’, while:
    foo =
    ifdef foo
        frobozz = yes
    else
        frobozz = no
    endif

    sets ‘frobozz’ to ‘no’.

     
  4. ifndef variable-name 
    만약  vraiable-name이 empty 값이라면, text-if-true 가 적용된다.

7.3 Conditionals that Test Flags


findstring 함수와 함께 MAKEFLAGS 변수를 사용하여 -t 와 같은 make command flags를 테스트하는 조건을 쓸 수 있다. 
이것은 touch가 파일을 갱신하는데 충분하지 않을 때 유용하다.
findstring 함수는 한 문자열이 다른 부분 문자열로 나타나는지 확인한다. 만약 '-t' 플래그에 대해서 테스트하길 원한다면, 첫번째 문자열로 't'를 사용하고 비교할 다른 문자열로 MAKEFLAGS의 값을 사용한다.
다음은 아카이브 파일을 갱신하는 것에대해 마킹하는것을 종료하기 위해 'ranlib -t'를 사용하는것을 어떻게 정리하는지를 보여준다.

archive.a: ...
ifneq (,$(findstring t,$(MAKEFLAGS)))
    +touch archive.a
    +ranlib -t archive.a
else
    ranlib archive.a
endif

'+' 접미어는 명령행 라인이 '-t' 플래그를 사용했음에도 불구하고 실행될 수 있게 하기 위해 "recursive" 하다는 것을 표시한다. (Section 5.7 Recursive Use of make 참고)
:

[MAKE] How to Use Variables

CS/Shell/Perl/Python 2011. 6. 8. 06:52
원문 : GNU make

6.1 Basics of Variable References


변수 이름에는 대문자를 사용하는 것이 관행이다.
하지만, makefile 안에서 internal purpose 을 수행하는 것은 소문자를 사용하고,  암묵적인 규칙을 제어하는 파라매터나 컴맨드 옵션에서 사용자가 오버라이드 해야만 하는 파라메터에 대해서는 대문자로 예약할 것을 것을 권장 한다.

$(foo) 나 ${foo} 와 같이 변수 이름을 () 나 {}로 감사고 $를 붙여서 참조할 수 있다.

6.2 The Two Flavors of Variables


GNU make 에서는 변수가 값을 갖도로 하는 네 가지 방법이 있다.
  1. recursive expanded variable 
    이 종류의 변수는 '='를 통해서 정의하거나(Section 6.5 [Setting Variables] 참고), define 지시자를 통해서 정의될 수 있다.
    만약 다른 변수에 대한 참조를 포함하고 있다면, 이 참조는 이 변수가 치환될 때마다 확장된다.

    foo = $(bar)
    bar = $(ugh)
    ugh = Huh?

    all:;echo $(foo)
    에서 $(foo)는 $(bar)로 확장되고, 이것은 다시 $(ugh)로  확장되어, 최종적으로 Huh? 로 확장될 것이다.


    이 종류의 변수는 모든 다른 make에서도 지원한다. 하지만

    CFLAGS = $(include_dirs) -O
    include_dirs = -Ifoo -Ibar

    CFLAGS = $(CFLAGS) -O 

    와 같이 한 경우, 변수 확장에 의해 무한 루프를 돌게 된다.

  2. expanded variable
    변수가 정의될 때 어떤 다른 변수나 함수에 대한 참조를 확장하여 한번만 스캔 되고 확장된다. 즉, 이 변수가 정의 되었을 때의 값을 가진다.

    x := foo
    y := $(x) bar
    x := later
    는,
    y := foo bar
    x := later 
    와 같다.  


  •  ?=를 이용해서 변수가 정의되어 있지 않을때만 정의할 수 있다.

    FOO ?= bar 는

    ifeq ($(origin FOO), undefined)
        FOO = bar
    endif

    와 동일하다. 


     만약 bar 가 정의되어 있지 않았을 때 FOO = bar 와 같이 한다면, FOO는 empty value로 정의된 상태가 된다.

  •  +=를 이용하여 이미 정의된 변수의 값에 추가로 문자를 더할 수 있다.

    objects = main.o foo.o bar.o utils.o
    objects += another.o


    +=를 사용하는 것은 :=를 다음과 같이 사용하는 것과 유사하다. 

    objects = main.o foo.o bar.o util.o
    objects := $(objects) another.o 

     
    만약 +=로 덧붙일 변수가 이전에 정의되어 있지 않았다면, +=는 =(recursively-expanded variable)과 동일하게 동작한다. 

6.3 Advanced Features for Reference to Variables


  • substitution reference
    지정한 대치값으로 변수의 값을 치환한다.  $(var:a=b) 혹은 ${var:a=b}와 같은 형식으로 사용되며, var 변수에 있는 a로 끝나는(다음에 whitespace가 나오는 a) 모든 a를 b로 치환한다.

    foo := a.o b.o c.o
    bar := $(foo:.o=.c)

    는 bar 를 a.c b.c c.c 로 치환한다.

    이는, 사실상 patsubst(Section 8.2 [Functions for String Substitution and Analysis] 참고) 함수 확장의 축약형이다. patsubst 함수의 모든 기능을 사용하기 위해서는 $(var:%a=%b)와 같이 %를 덧붙임 형태를 사용해야 한다. 

    foo := a.o b.o c.o
    bar := $(foo:%.o=%.c) 

    는 $(patsubst .o,.c,$(var))와 동일하다. 


  • computed variable name (nested variable reference)
     변수들은 변수의 안에 있는 이름으로 참조될 수 있다. 이를 computed variable name 혹은 nested variable reference라고 한다. 예를 들어

    x = y
    y = z
    a :=$($(x))

    에서 $($(x)는 $(y)가 되어, 결국 z가 된다.


    혹은 재귀적으로

    x = $(y)
    y = z
    z = Hello
    a := $($(x))

    에서 $($(x)) 는 $($(y))가 되고, 이것은 $(z) 가 되어, 결국 Hello가 된다. 


    Nested variable 참조는 변경된 참조나 함수 실행(Chapter 8 [Functions for Transforming Text] 참고) 등을 포함할 수 있다. 예를 들어 subst 함수를 사용하여

    x = variable1
    variable2 := Hello
    y = $(subst 1,2,$(x))
    z = y
    a := $($($(z))))

    $($($(z)))는 $($(y))가 되고, y는 variable2의 값을 가지게 되기 때문에,  $(variable2)가 되어, 결국 Hello를 정의하게 된다. 


    computed variable name은 하나의 변수 참조로 이루어질 필요는 없다. 예를 들어

    a_dirs := dira dirb
    1_dirs := dir1 dir2

    a_files :=filea fileb
    1_files :=file1 file2

    ifeq "$(use_a)" "yes"
        a1 := a
    else
        a1 := 1
    endif

    ifeq "$(use_dirs)" "yes"
        df := dirs
    else
        dif := files
    endif

    dirs := $($(a1)_$(df))

    $(a1) 이 a를 정의하고 $(df)가 dirs를 정의한다면, a_dirs가 되어 dirs 는 $(a_dirs)가 되어 결국,
    dirs := dira dirb
    를 정의하게 된다.

     
    computed variable name은 치환 참조에서도 사용될 수 있다.

    a_objects := a.o b.o c.o
    1_objects := 1.o 2.o c.o

    sources := $($(a1)_objects:.o=.c)
    는 a1이 어떤것을 가리키느냐에 따라

    sources := a.c b.c c.c
    혹은
    sources :=1.c 2.c 3.c
    가 될 수 있다. 


    또한, computed variable name을 변수 대입의 왼편이나 define 지시자에서 사용할 수 있다.

    dir = foo

    $(dir)_sources := $(wildcard $(dir)/*.c)

    define $(dir)_print = 
     
    lpr $($(dir)_sources)

    endef

    이는 foo_sources와 foo_print를 정의한다. 



:

특권 레벨 (Privilege ring level)

CS/Common 2011. 5. 25. 14:19
원문 : Intel 64 and IA-32 Architectures Software Developer's Manual Volume 3A

권한 레벨은 세그먼트 디스크립터의 세그먼트 셀렉터가 세그먼트 레지스터로 로드될 때 체크된다.

CPL (Current Privilege Level)
: 현재 실행되고 있는 태스크의 특권 레벨로, CS, SS 세그먼트 레지스터 0, 1 번째 비트.
: 일반적으로 CPL은 명령어가 페치되는 코드 세그먼트의 특권 레벨과 동일하다. 
: 프로세서는 프로그램 컨트롤이 다른 권한 레벨을 가진 코드 세그먼트로 전이될 때 CPL을 변경한다.
: CPL은 conforming 코드 세그먼트에 접근할 때 약간 다르게 취급된다. Confirming 코드 세그먼트는 confirming 코드의 DPL보다 같거나 더 작은 권한(숫자적으로 높은)을 가진 어떤 다른 권한 레벨에서 접근될 수 있다.
: CPL은 프로세서가 CPL과 다른 권한 레벨을 가진 conforming 코드 세그먼트에 접근할 때 변경되지 않는다. 


DPL (Descriptor Privilege Level)
: 세그먼트나 게이트 디스크립터가 포함하고 있는 필드.
: 세그먼트나 게이트의 특권레벨.
: 현재 실행되고 있는 코드가 세그먼트나 게이트에 접근하려고 할 때, 세그먼트나 게이트의 DPL은 CPL과 세그먼트가 게이트의 RPL과 비교된다.
: DPL은 세그먼트나 게이트가 엑세스되고 있는 타입에 따라 다르게 해석된다.
  • Data segment - DPL은 프로그램이나 태스크가 세그먼트에 엑세스를 허용해야만 하는 가장 낮은 권한 레벨(숫자상으로 가장 높은)을 가리킨다. 예를 들어, 만약 데이터 세그먼트의 DPL이 1이라면, 0이나 1의 CPL에서 동작하고 있는 프로그램만이 세그먼트에 엑세스 할 수 있다.
  • Nonconforming code segment (without using call gate) - DPL은 프로그램이나 태스크가 세그먼트에 엑세스하기 위해 가져야 하는 권한 레벨을 가리킨다. 예를 들어 만약 nonconforming 코드 세그먼트의 DPL이 0이라면 CPL 0에서 수행되는 프로그램만이 이 세그먼트에 엑세스 할 수 있다.
  • Call gate - DPL은 현재 수행되고 있는 프로그램이나 태스크가 될 수 있고 여전히 콜 게이트에 접근할 수 있는 가장 낮은 레벨(숫자상으로 가장 높은)을 가리킨다. (data segment와 같은 규칙)
  • Conforming code segment and nonconforming code segment accessed through a call gate - DPL은 프로그램이나 태스크가 세그먼트에 엑세스를 허용해야만 하는 가장 높은 레벨(숫자상으로 가장 낮은)을 가리킨다. 예를 들어, 만약 conforming 코드 세그먼트의 DPL이 2 이고, 프로그램이 0이나 1의 CPL에서 동작하고 있다면 세그먼트에 엑세스 할 수 없다.
  • TSS - DPL은 현재 실행되고 있는 프로그램이나 태스크가 될 수 있거나 여전히 TSS에 접근 할 수 있는 가장 낮은 권한 레벨(숫자상으로 가장 높은)을 가리킨다. (data segment와 같은 규칙)
RPL (Requested Privilege Level)
: 세그먼트 셀렉터의 0, 1 번째 비트.
: 세그먼트 셀렉터에 할당된 override된 권한 레벨이다.
: 프로세서는 세그먼트의 접근이 허용되는지 판단하기 위해 CPL과 함께 RPL을 체크한다. 
: 비록 세그먼트의 접근을 요청하는 프로그램이나 태스크가 세그먼트에 접근하기 위한 충분한 권한을 가지고 있더라도, 만약 RPL이 충분한 권한 레벨을 가지고 있지 않다면, 접근은 거부된다. 즉, 세그먼트 셀렉터의 RPL이 CPL보다 낮은 권한 레벨(숫자상으로 높은)인 경우, RPL은 CPL을 override 한다. (반대도 마찬가지이다.)
: 5.10.4 Checking Caller Access Privileges (ARPL Instruction) 참고
: RPL은 만약 프로그램 자체가 세그먼트에 대한 엑세스 권한을 가지고 있지 않다면 에플리케이션 프로그램 대신에 권한 코드(privileged code)가 세그먼트에 접근하지 않는 것을 보장하기 위해 사용된다.


발번역 주의. 이놈의 영어... ㅜㅜ 







:

Why not mmap?

CS/Linux 2011. 5. 20. 10:36
원문 : http://useless-factor.blogspot.com/2011/05/why-not-mmap.html

mmap() is a beautiful interface. Rather than accessing files through a series of read and write operations, mmap() lets you virtually load the whole file into a big array and access whatever part you want just like you would with other RAM. (It lets you do other things, too—in particular, it's the basis of memory allocation. See the man page for details.) In this article, I'll be discussing mmap() on Linux, as it works in virtual memory systems like x86.

mmap() doesn't actually load the whole file in when you call it. Instead, it loads nothing in but file metadata. In the memory page table, all of the mapped pages are given the setting to make a page fault if they are read or written. The page fault handler loads the page and puts it into main memory, modifying the page table to not fault for this page later. In this way, the file is lazily read into memory. The file is written back out through the same writeback mechanism used for the page cache in buffered I/O: after some time or under some memory pressure, the contents of memory are automatically synchronized with the disk.

mmap() is a system call, implemented by the kernel. Why? As far as I can tell, what I described above could be implemented in user-space: user-space has page fault handlers and file read/write operations. But the kernel allows several other advantages:
  • If a file is being manipulated by mmap() as well as something else at the same time, the kernel can keep these in sync. 
  • The kernel can do it faster, with specialized implementations for different file systems and fewer context switches between kernel-space and user-space.
  • The kernel can do a better job, using its internal statistics to determine when to write back to disk and when to prefetch extra pages of the file. 
One situation where mmap() looks useful is databases. What could be easier for a database implementor than an array of "memory" that's transparently persisted to disk? Database authors often think they know better than the OS, so they like to have explicit control over caching policy. And various file and memory operations give you this, in conjunction with mmap():
  • mlock() lets you force a series of pages to be held in physical memory, and munlock() lets you release it. Memory locking here is basically equivalent to making part of the file present in the user-space cache, when no swap is configured on the server.

    Memory locking can be dangerous in an environment with many processes running because the out-of-memory killer (OOM killer) might some other process as a result of your profligate use of memory. However, the use of cgroups or virtualization can mitigate this possibility and provide isolation.
  • madvise() and posix_fadvise let you give the OS hints about how to behave with respect to the file. These can be used to encourage things to be pulled into memory or pushed out. MADV_DONTNEED is a quick call to zero a series of pages completely, and it could be translated into TRIM on SSDs.
  • fdatasync() lets a a process force some data onto the disk right now, rather than trusting writeback to get it there eventually. This is useful for implementing durable transactions.
Great! And in Linux, you can open up a raw block device just by opening a file like /dev/hda1 and use mmap() straight from there, so this gives database implementors a way to control the whole disk with the same interface. This is great if you're a typical database developer who doesn't like the OS and doesn't trust the file system.

So this sounds like a nice, clean way to write a database or something else that does serious file manipulation. Some databases use this, for example MongoDB. But the more advanced database implementations tend to open the database file in O_DIRECT mode and implement their own caching system in user-space. Whereas mmap() lets you use the hardware (on x86) page tables for the indirection between the logical address of the data and where it's stored in physical memory, these databases force you to go through an extra indirection in their own data structures. And these databases have to implement their own caches, even though the resulting caches often aren't smarter than the default OS cache. (The logic that makes the caching smarter is often encoded in an application-specific prefetcher, which can be done pretty clearly though memory mapping.)

A problem with mmap()

High-performance databases often get lots of requests. So many requests that, if they were to spawn a thread for each one of them, the overhead of a kernel task per request would slow them down (where task means 'thread or process', in Linux terminology). There's a bit of overhead for threads:
  • Each thread must have its own stack, which takes up memory (though this is mitigated by the lazy allocation of physical memory to back stacks, which is done by default) 
  • Some Linux CPU schedulers use a lot of CPU themselves. So blocking and then getting resumed has a certain amount of overhead. In particular, overhead is incurred so that the scheduler can be completely fair, and so that it can load-balance between cores.
To solve these issues, database implementors often respond to each request with a user-level coroutine, or even with an explicitly managed piece of state sent around through various callbacks.

Let's say we have a coroutine responding to a database request, and this coroutine wants to read from the database in a location that is currently stored on disk. If it accesses the big array, then it will cause a memory fault leading to a disk read. This will make the current task block until the disk read can be completed. But we don't want the whole task to block—we just want to switch to another coroutine when we have to wait, and we want to execute that coroutine from the same task.

The typical way around this problem is using asynchronous or non-blocking operations. For non-blocking I/O, there's epoll, which works for some kinds of files. For direct I/O on disk, Linux provides a different interface called asynchronous I/O, with system calls like io_submit. These two mechanisms can be hooked up with an eventfd, which is triggered whenever there are AIO results, using the undocumented system call io_set_eventfd. The basic idea is that you set up a bunch of requests in an object, and then you have a main loop, driven by epoll, where you repeatedly ask for the next available event. The coroutine scheduler resumes the coroutine that had the event complete on it, and executes that coroutine until it blocks again. Details about using this mechanism are a bit obtuse, but not very deep or complicated.

A proposed solution

What the mmap() interface is missing is a non-blocking way to access memory. Maybe this would take the form of a call based around mlock, like

int mlock_eventfd(const void *addr, ssize_t len, int eventfd);


which would trigger the eventfd once the memory from addr going length len was locked in memory. The eventfd could be placed in an epoll loop and then the memory requested would be dereferenced for real once it was locked. A similar mechanism would be useful for fdatasync.

We could implement mlock_eventfd in user-space using a thread pool, and the same goes for fdatasync. But this would probaly eliminate the performance advantages of using coroutines in the first place, since accessing the disk is pretty frequent in databases.

As databases and the devices that underlie them grow more complex, it becomes difficult to manage this complexity. The operating system provides a useful layer of indirection between the database and the drive, but old and messy interfaces make the use of the OS more difficult. Clean, high-level OS interfaces which let applications take full advantage of the hardware and kernel-internal mechanisms and statistics would be a great boon to further database development, allowing the explosion of new databases and solid-state drives to be fully exploited.
:

[BASH, PERL] Multiline string

CS/Shell/Perl/Python 2011. 4. 24. 15:50
참고:
http://serverfault.com/questions/72476/clean-way-to-write-complex-multi-line-string-to-a-variable

BASH

cat <<EOF

This is

Multiline

String.

EOF

read -d '' VAL<<EOF

This is

Multiline

String.

EOF


PERL

my $VALUE =<<ENDVALUE;

This is

Multiline

String.

ENDVALUE

my $VALUE = "This is

Multiline

String.

";


:

[PERL] 최소 일치 정규 표현식 (Non-greedy regular expression)

CS/Shell/Perl/Python 2011. 4. 15. 13:14
원문: http://www.bayview.com/blog/2003/02/12/non-greedy-regular-expressions/

$src = "www.google.com"

$www = ($src =~ /(.*)\./ && 1);
과 같이 할 경우 기본적으로 greedy matching이 되기 때문에
$www = "www.google" 이 된다.

방법 1.

$www = ($src =~ /([^.]*)\./ && 1);


방법 2.
.*? 혹은 .+? 를 사용하여 Non-greedy matching 시킨다.

$www = ($src =~ /(.*?)\./ && 1);



:

[JAVASCRIPT] location.href 와 location.replace()

CS/JavaScript/HTML/CSS 2011. 3. 14. 17:17
원문:

location.href
1. 프로퍼티
2. 현재 Page의 전체 URL
3. set 할 경우 URL이 바뀌게 되므로, history에 push.

location.replace()
1. 메소드
2. 현재 Document를 바꿈(replace).
3. URL을 바꾸는 것이 아니라, 같은 URL에 대해서 Document만 바뀌는 것이므로, history에 push되지는 않음.
: