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'
'CS'에 해당되는 글 76건
SSH login without passwordCS/Linux 2014. 3. 26. 15:01원문 : http://www.linuxproblem.org/art_9.html a@A 에서 b@B 로 password 없이 로그인 a@A:~> ssh-keygen -t rsa 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
이미지 파일 생성 / 마운트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 [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 styleCS/iPhone 2012. 1. 14. 22:41원문 : http://borkware.com/quickies/one?topic=UITableView
[IPHONE] Using Core DataCS/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의 구현에는 일반적으로 다른 클래스를 작성하는것과는 다르다.
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];
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] 나눔고딕 적용CS/iPhone 2011. 12. 29. 03:25참고 : http://kgriff.posterous.com/45359635
1. plist 에 폰트 등록 <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]; Ubuntu에서 고정 IP 설정CS/Linux 2011. 9. 8. 13:38/etc/network/interfaces
auto lo iface lo inet loopback
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 passwordCS/Linux 2011. 9. 8. 13:29원문 : http://linuxproblem.org/art_9.html
a@A:~> ssh-keygen -t rsa [MAKE] Functions for Transforming TextCS/Shell/Perl/Python 2011. 6. 8. 16:43원문 : GNU make
8.4 Functions for Conditionals 조건 표현을 제공하는 세 가지 함수가 있다. 모든 인자가 초기에 확장되지 않는다는 것이 이 세 함수의 중요한 면이다. 인자 중 확장되기를 원하는 인자만이 확장된다.
[MAKE] Conditional PartsCS/Shell/Perl/Python 2011. 6. 8. 15:18원문 GNU make
7.1 Example of a Conditional 다음 예제는 CC변수가 gcc인 경우에 make가 라이브러리들 중 하나의 셋을 사용하게 하고, gcc가 아닌 경우에는 다른 라이브러리 셋을 사용하게 한다. libs_for_gcc = -lgnu 혹은, 다음과 같이 변수를 조건부로 할당하고, 변수를 명시적으로 사용할 수도 있다 libs_for_gcc = -lgnu 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가지 지시자가 있다
7.3 Conditionals that Test Flags findstring 함수와 함께 MAKEFLAGS 변수를 사용하여 -t 와 같은 make command flags를 테스트하는 조건을 쓸 수 있다. 이것은 touch가 파일을 갱신하는데 충분하지 않을 때 유용하다. findstring 함수는 한 문자열이 다른 부분 문자열로 나타나는지 확인한다. 만약 '-t' 플래그에 대해서 테스트하길 원한다면, 첫번째 문자열로 't'를 사용하고 비교할 다른 문자열로 MAKEFLAGS의 값을 사용한다. 다음은 아카이브 파일을 갱신하는 것에대해 마킹하는것을 종료하기 위해 'ranlib -t'를 사용하는것을 어떻게 정리하는지를 보여준다. archive.a: ... [MAKE] How to Use VariablesCS/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 에서는 변수가 값을 갖도로 하는 네 가지 방법이 있다.
6.3 Advanced Features for Reference to Variables
특권 레벨 (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은 세그먼트나 게이트가 엑세스되고 있는 타입에 따라 다르게 해석된다.
: 세그먼트 셀렉터의 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:
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():
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:
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 stringCS/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 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. 방법 2. [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되지는 않음.
[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] execlCS/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 manipulationCS/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
${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 templateCS/iPhone 2010. 11. 24. 14:53Xcode template 위치 (Source)
/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Project Templates
User template 위치
${USER}/Library/Application Support/Developer/Shared/Xcode/Project Templates [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 NSZombieCS/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”. [PERL] Regular ExpressionCS/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] TimerCS/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"; } |