일단 어제 오늘 이틀동안 고민한 끝에 Doku Wiki를 사용하기로 했습니다. 데이터의 처리가 Full Text로 되어있는 점과 플러그인이 많은 점이 매력적이었습니다.

 다만 단점이라면 WYGWYG Editor가 좀 딸린다는 건데... 스프링노트를 쓰다 다시 넘어오니 심하게 불편하네요. ㅜ_ㅜ)/~ 그래도 일단 적응 되면 괜찮을 것 같으니 써보렵니다. ^^)/~

 아아~ 이제 한동안 걱정없겠군요. ;)

 ps) 아래는 Doku wiki의 Stand Alone 버전과 목차를 만들어 주는 플러그인입니다.
 RSS를 돌다가 재미있는 글을 발견했습니다. 외국 사이트인데 언패킹(Unpacking)을 쉽게하는 방법에 대해서 적어놨더군요. 원문은 http://www.websense.com/securitylabs/blog/blog.php?BlogID=176에서 볼 수 있습니다.

 위 링크의 내용을 간단히 요약하자면 다음과 같습니다.
1. 패커(Packer)들은 실행파일이 시작되었을 때 실행파일의 내용을 복원해야하므로 복원 함수를 호출합니다. 단 복원 후에 정상적인 실행을 위해서는 레지스터의 상태가 그대로 보존되어야 하기 때문에 레지스터의 값을 우선 스택에 보관합니다. 이때 PUSH 명령을 사용합니다.
2. 복원 함수를 호출해서 실행 파일을 복원합니다.
3. 복원이 끝난 뒤에 레지스터의 값을 복원 함수를 호출하기 전의 레지스터 값으로 복원합니다. 이때 POP 명령을 사용합니다.

 위의 과정을 보면 PUSH와 POP이 쌍을 이룬다는 것을 알 수 있고, POP이 되어 모든 레지스터의 복원이 끝난 상태는 실행파일 복원이 끝난 상태라고 볼 수 있습니다. 이러한 약간의 팁을 이용해서 스택 포인터(ESP)에 브레이크 포인터를 걸고 계속 체크해 나가는 방법입니다.
사용자 삽입 이미지

사용자 삽입 이미지

 하지만 레지스터를 보관하기 위해서 꼭 PUSH/POP을 써야하는 것은 아니기 때문에 한계는 있지만, 괜찮은 아이디어 같습니다. ;)  또 이렇게 잡 지식이 하나 늘었군요. ^^)/~

 
 회사에서 일을 하다보면 중간 중간에 메모를 하고 싶은 충동을 마구 느낍니다. 종이에 적어놓자니 나중에 못 찾을 꺼 같고, 그렇다고 메모장 프로그램에 적어 놓자니 너무 정리가 안되보입니다. 결국 위키(Wiki)를 깔아서 쓸 마음을 먹고 아파치 웹서버를 깔까 했었는데, 웹서버없이도 동작하는 위키가 있더군요.


 일단 설치해서 써봤는데, 나쁘지는 않습니다. ;) 하지만 간단한 웹서버를 사용하다보니 파일 업로드 기능 및 일부 기능이 정상적으로 동작하지 않는군요. ㅜ_ㅜ...

 아아~ 결국 아파치를 깔아야한단 말입니까... ㅜ_ㅜ...
 뭐 좀 편히 되는 것이 없네요. ㅜ_ㅜ)/~


 휴일을 맞아 방청소를 해놓고 오후 느즈막한 시간부터 인텔 문서를 붙잡고 읽기 시작했습니다. 워낙 영어가 부족한지라 이해가 잘 안되서 테스트 코드 위주로 볼려고 이곳 저곳 뒤졌습니다. Pseudo 코드는 발견했지만 전체적인 흐름의 일부분만 되어있어서 크게 도움이 안되더군요. 결국 차분히(??) 읽었습니다. ㅜ_ㅜ

 문서를 읽어가면서 여기저기 줄치고, 제가 만든 OS 프레임워크(http://kkamagui.tistory.com/category/OS%20Kernel(Intel,%20ARM) 참고)를 이용해서 테스트를 진행하다가 재미있는 사실을 알아냈습니다. VMware(코어 2개로 설정)를 사용해서 테스트했기 때문에 실제 PC와 동일할지는 알 수 없습니다만, 전원이 켜지고 BIOS가 시스템을 초기화하는 동안 BIOS가 CPU에 있는 모든 코어를 초기화 하고 ID를 할당해준다는 것입니다.
 
 인텔 문서에 의하면 CPU는 BIOS 코드에 의해 BSP(Bootstrap Processor)와 AP(Application Processor)로 나누어 설정된다고 합니다. 그리고 BSP는 초기화된 후 OS 코드를 실행하며, AP는 초기화된 후 인터럽트를 대기하면서 HLT 루프를 돈다고 되어있습니다. 실제로 테스트 코드를 넣어서 플래그를 확인해보니 APIC가 활성화되어 있었습니다. @0@)/~!!! 사실 간단히 코드를 작성해서 플래그만 확인해본 것이라 확실한 것은 아닙니다만, 일단 알아낸 것이니 포스팅합니다. ^^;;;
사용자 삽입 이미지

CPUID, APIC ID 및 APIC Enable 정보


 만약 진짜로 AP가  인터럽트를 대기하며 HLT 루프를 돈다면, BSP가 어떤 방식으로 AP가 태스크를 실행하도록 할 수 있을까요? 지금 추측하기로는 AP쪽의 인터럽트 백터를 조작하고 인터럽트를 발생시켜서 인터럽트 서비스 루틴(ISR)을 통해 태스크 또는 커널 코드를 실행하도록 하는 것이 아닐까 합니다. 이부분은 나중에 좀 더 시간을 내서 확인해 봐야할 것 같습니다.

 어이쿠, 또 밤이 깊었네요~ 이만 자야겠습니다. 다들 좋은 밤 되세요 ^^)/~

ps) 인텔 문서를 분석한다고, NDS 프로그램을 수정하지 못했군요.
죄송합니다. ㅜ_ㅜ 일단 내일이라도 짬을 내서 수정하도록 하겠습니다. (_ _)


 옛날에 AMD 듀얼코어를 사면서 인텔 패치도 본적이 있었는데, 오늘 갑자기 생각나서 급히 정리해 놓습니다. 앞으로 XP를 얼마나 쓰게 될지는 모르겠지만, 그래도 백업을 해둬야 할 것 같아서... 듀얼 코어 패치를 하면 성능이 조금 개선된다고 하던데, 글쎄요... ^^;;; 잘 모르겠습니다.
 설치 방법은 아주 간단하고 아래와 같습니다. ^^)/~

1. 아래의 파일을 모두 받습니다.
2. WindowsXP-KB896256-v4-x86-KOR.exe 파일을 실행해서 설치합니다. 그리고 재부팅하지 않음을 선택해서 3번 단계로 넘어갑니다.
3. windowsxp_kb896256_enable-enflenfl1014.reg 파일을 더블 클릭해서 레지스트리에 병합해 줍니다.
4. 마지막으로 [시작]->[실행]->"C:\boot.ini"를 실행하셔서 맨 마지막에 /usepmtimer 를 추가해 줍니다.
[boot loader]
timeout=30
default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS
[operating systems]
multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Microsoft Windows XP Professional" /noexecute=optin /fastdetect /usepmtimer


 다들 알고계신 내용일텐데... 역시나 뒷북성 포스트를... ^^;;;

 인터넷 익스플로어에서 파이어폭스로 넘어온지 이제 한 6개월 정도가 됐습니다. 파이어폭스의 꽤 괜찮은 성능과 다양한 플러그인때문에 만족하면서 쓰고 있습니다. 하지만 Active X로 도배된 우리나라 사이트를 방문할때 불편한 것은 어쩔 수 없었습니다.

 그래서 플러그인 목록을 뒤졌는데, 재미있는 것을 발견했습니다. IE Tab이라는 것인데요, 이미 많은 분들이 쓰고 계시더군요(뒷북성 포스트를... ㅜ_ㅜ). 파일은 https://addons.mozilla.org/ko/firefox/addon/1419 에서 받을 수 있습니다. 설치를 끝내고 나면 마우스 오른쪽 버튼을 눌렀을때 아래와 같이 표시됩니다.

사용자 삽입 이미지

 상당히 좋네요~ ^ㅡ^)/~~ 대만족입니다~
 파이어 폭스 만세~!!!



12 문자셋(Character Set) 자동 탐지

 원문 :  http://www.mozilla.org/projects/intl/UniversalCharsetDetection.html

 

A composite approach to language/encoding detection

 

Shanjian Li (shanjian@netscape.com)
Katsuhiko Momoi (momoi@netscape.com)
Netscape Communications Corp.

[Note: This paper was originally presented at the 19th International Unicode Conference (San Jose). Since then the implementation has gone through a period of real world usage and we made many improvements along the way. A major change is that we now use positive sequences to detect single byte charsets, c.f. Sections 4.7 and 4.7.1.  This paper was written when the universal charset detection code was not part of the Mozilla main source. (See Section 8). Since then, the code was checked into the tree. For more updated implementation, see our open source code at Mozilla Source Tree. - The authors. 2002-11-25.]

1. Summary:


This paper presents three types of auto-detection methods to determine encodings of documents without explicit charset declaration.  We discuss merits and demerits of each method and propose a composite approach in which all 3 types of detection methods are used in such a way as to maximize their strengths and complement other detection methods. We argue that auto-detection can play an important role in helping transition browser users from frequent uses of a character encoding menu into a more desirable state where an encoding menu is rarely, if ever, used.  We envision that the transition to the Unicode would have to be transparent to the users.  Users need not know how characters are displayed as long as they are displayed correctly -- whether it’s a native encoding or one of Unicode encodings.  Good auto-detection service could help significantly in this effort as it takes most encoding issues out of the user’s concerns.

2. Background:


Since the beginning of the computer age, many encoding schemes have been created to represent various writing scripts/characters for computerized data. With the advent of globalization and the development of the Internet, information exchanges crossing both language and regional boundaries are becoming ever more important. But the existence of multiple coding schemes presents a significant barrier.  The Unicode has provided a universal coding scheme, but it has not so far replaced existing regional coding schemes for a variety of reasons. This, in spite of the fact that many W3C and IETF recommendations list UTF-8 as the default encoding, e.g. XML, XHTML, RDF, etc. Thus, today's global software applications are required to handle multiple encodings in addition to supporting Unicode.

The current work has been conducted in the context of developing an Internet browser. To deal with a variety of languages using different encodings on the web today, a lot of efforts have been expended. In order to get the correct display result, browsers should be able to utilize the encoding information provided by http servers, web pages or end users via a character encoding menu. Unfortunately, this type of information is missing from many http servers and web pages. Moreover, most average users are unable to provide this information via manual operation of a character encoding menu. Without this charset information, web pages are sometimes displayed as ‘garbage’ characters, and users are unable to access the desired information. This also leads users to conclude that their browser is mal-functioning or buggy.

As more Internet standard protocols designate Unicode as the default encoding, there will undoubtedly be a  significant shift toward the use of Unicode on web pages. Good universal auto-detection can make an important contribution toward such a shift if it works seamlessly without the user ever having to use an encoding menu.  Under such a condition, gradual shift to Unicode could be painless and without noticeable effects on web users since for users, pages simply display correctly without them doing anything or paying attention to an encoding menu.  Such a smooth transition could be aided by making encodings issues less and less noticeable to the users. Auto-detection would play an important role for such a scenario.

3. Problem Scope:

 

3.1. General Schema

Let us begin with a general schema. For most applications, the following represents a general framework of auto-detection use:

Input Data ->  Auto-detector -> Returns results

An application/program takes the returned result(s) from an auto-detector and then uses this information for a variety of purposes such as setting the encoding for the data, displaying the data as intended by the original creator, pass it on to other programs, and so on.

The auto-detection methods discussed in this paper use an Internet Browser application as an example. These auto-detection methods, however, can be easily adapted for other types of applications.

3.2.  Browser and auto-detection


Browsers may use certain detection algorithms to auto-detect the encoding of web pages. A program can potentially interpret a piece of text in any number of ways assuming different encodings, but except in some extremely rare situations, only one interpretation is desired by the page’s author.  This is normally the only reasonable way for the user to see that page correctly in the intended language.

To list major factors in designing an auto-detection algorithm, we begin with certain assumptions about input text and approaches to them.  Taking web page data as an example,

1. Input text is composed of words/sentences readable to readers of a particular language.  (= The data is not gibberish.)

2. Input text is from typical web pages on the Internet. (= The data is usually not from some dead or ancient language.)

3. The input text may contain extraneous noises which have no relation to its encoding, e.g. HTML tags, non-native words (e.g. English words in Chinese documents), space and other format/control characters.

To cover all the known languages and encodings for auto-detection is nearly an impossible task. In the current approaches, we tried to cover all popular encodings used in East Asian languages, and provided a generic model to handle single-byte encodings at the same time. The Russian language encodings was chosen as an implementation example of the latter type and also our test bed for single-byte encodings.

4. Target multi-byte encodings include UTF8, Shift-JIS, EUC-JP, GB2312, Big5, EUC-TW, EUC-KR, ISO2022-XX, and HZ.

5. Providing a generic model to handle single-byte encodings – Russian language encodings (KOI8-R, ISO8859-5, window1251, Mac-cyrillic, ibm866, ibm855) are covered in a test bed and as an implementation example.

4. Three Methods of Auto-detection:

 

4.1. Introduction:


In this section, we discuss 3 different methods for detecting the encoding of text data. They are 1) Coding scheme method, 2) Character Distribution, and 3) 2-Char Sequence Distribution. Each one has its strengths and weaknesses used on its own, but if we use all 3 in a complementary manner, the results can be quite satisfying.

4.2. Coding Scheme Method:


This method is probably the most obvious and the one most often tried first for multi-byte encodings. In any of the multi-byte encoding coding schemes, not all possible code points are used. If an illegal byte or byte sequence (i.e. unused code point) is encountered when verifying a certain encoding, we can immediately conclude that this is not the right guess. A small number of code points are also specific to a certain encoding, and that fact can lead to an immediate positive conclusion. Frank Tang (Netscape Communications) developed a very efficient algorithm to detecting character set using coding scheme through a parallel state machine.  His basic idea is:

For each coding scheme, a state machine is implemented to verify a byte sequence for this particular encoding. For each byte the detector receives, it will feed that byte to every active state machine available, one byte at a time. The state machine changes its state based on its previous state and the byte it receives. There are 3 states in a state machine that are of interest to an auto-detector:

  •  START state: This is the state to start with, or a legal byte sequence (i.e. a valid code point) for character has been identified.
  •  ME state:  This indicates that the state machine identified a byte sequence that is specific to the charset it is designed for and that there is no other possible encoding which can contain this byte sequence. This will to lead to an immediate positive answer for the detector.
  •  ERROR state: This indicates the state machine identified an illegal byte sequence for that encoding. This will lead to an immediate negative answer for this encoding. Detector will exclude this encoding from consideration from here on.

In a typical example, one state machine will eventually provide a positive answer and all others will provide a negative answer.

The version of PSM (Parallel State Machine) used in the current work is a modification of Frank Tang's original work. Whenever a state machine reaches the START state, meaning it has successfully identified a legal character, we query the state machine to see how many bytes this character has. This information is used in 2 ways.

  • First, for UTF-8 encoding, if several multi-byte characters are identified, the input data is very unlikely to be anything other than UTF-8. So we count the number of multi-byte characters identified by the UTF-8 state machine. When it reaches a certain number (= the threshold), conclusion is made.  
  • Second, for other multi-byte encodings, this information is fed to Character Distribution analyzer (see below) so that the analyzer can deal with character data rather than raw data.

 

4.3. Character Distribution Method:


In any given language, some characters are used more often than other characters. This fact can be used to devise a data model for each language script. This is particularly useful for languages with a large number of characters such as Chinese, Japanese and Korean. We often hear anecdotally about such distributional statistics, but we have not found many published results. Thus for the following discussions, we relied mostly on our own collected data.

4.3.1. Simplified Chinese:



Our research on 6763 Chinese characters data encoded in GB2312 shows the following distributional results:

Number of Most Frequent Characters Accumulated Percentage
10 0.11723
64 0.31983
128 0.45298
256 0.61872
512 0.79135
1024 0.92260
2048 0.98505
4096 0.99929
6763 1.00000

     Table 1.  Simplified Chinese Character Distribution Table

 

4.3.2. Traditional Chinese:


Research by Taiwan’s Mandarin Promotion Council conducted annually shows a similar result for traditional Chinese encoded in Big5.

Number of Most Frequent Characters

Accumulated Percentage

10

0.11713

64

0.29612

128

0.42261

256

0.57851

512

0.74851

1024

0.89384

2048

0.97583

4096

0.99910

   

     Table 2. Traditional Chinese Character Distribution Table


4.3.3. Japanese:


We collected our own data for Japanese, then wrote a utility to analyze them.  The following table shows the results:

Number of Most Frequent Characters Accumulated Percentage
10 0.27098
64 0.66722
128 0.77094
256 0.85710
512 0.92635
1024 0.97130
2048 0.99431
4096 0.99981
  1.00000

       Table 3.  Japanese Character Distribution Table

4.3.4.  Korean:


Similarly for Korean, we collected our own data from the Internet and run our utility on it. The results are as follows:

Number of Most Frequent Characters Accumulated Percentage
10 0.25620
64 0.64293
128 0.79290
256 0.92329
512 0.98653
1024 0.99944
2048 0.99999
4096 0.99999
   

      Table 4.  Korean Character Distribution Table

 

 

4.4. General characteristics of the distributional results:


In all these four languages, we find that a rather small set of coding points covers a significant percentage of characters used in our defined application scope.  Moreover, closer examination of those frequently used code points shows that they are scattered over a rather wide coding range.  This gives us a way to overcome the common problem encountered in the Coding Scheme analyzer, i.e. different national encodings may share overlapping code points.  Because the most frequently occurring sets for these languages have the characteristics described above, the overlap problem between different encodings in the Code Scheme Method will be insignificant in the Distribution Method.

4.5. Algorithm for analysis:


In order to identify characteristics of a language based on the character frequency/distribution statistics, we need an algorithm to calculate a value from a stream of text input. This value should show the likelihood of this stream of text being in a certain character encoding. A natural choice might be to calculate this value based on each character’s frequency weight. But from our experiment with various character encodings, we find that this approach is not necessary and it uses too much memory and CPU power. A simplified version provides a very satisfactory result, and uses much less resources and runs faster.  

In the current approach, all characters in a given encoding are classified into 2 categories, “frequently used” and “not frequently used”.  If a character is among the top 512 characters in the frequency distribution table, it is categorized as a “frequently used” character. The number 512 is chosen because it covers a significant amount of accumulated percentages in any of the 4 language input text while only occupying a small percentage of coding points. We count the number of characters in either category in a batch of input text, and then calculate a float value we call Distribution Ratio.  

The Distribution Ratio is defined as follows:

Distribution Ratio = the Number of occurrences of the 512 most frequently used characters divided by the Number of occurrences of the rest of the characters.

Each of the multi-byte encodings tested actually shows a distinct Distribution Ratio. From this ratio then, we can calculate the confidence level of the raw input text for a given encoding. Following discussions for each encoding should make this clearer.

4.6. Distribution Ratio and Confidence Level:


Let us look at the 4 language data to see the differences in Distribution Ratios.  Note first that we use the term Distribution Ratio in two ways. An “ideal” Distribution Ratio is defined for language scripts/character sets rather than for encodings.  If a language script/character set is represented by more than one encodings, then, for each encoding, we calculate the “actual” Distribution Ratio in the input data by sorting characters into “frequently used” or “not frequently used” categories. This value is then compared against the ideal Distribution Ratio of the language script/character set.  Based on the actual Distribution Ratios obtained, we can calculate the Confidence level for each set of input data as described below.

4.6.1. Simplified Chinese (GB2312):


GB2312 encoding contains two levels of Chinese characters. Level 1 contains 3755 characters, and Level 2, 3008 characters. Level 1 characters are more frequently used than Level 2 ones, and it is no surprise to see that all 512 characters on the most frequently used character list for GB 2312 are within Level 1. Because Level 1 characters are sorted based on pronunciation, those 512 characters are evenly scattered in 3755 code points. These characters occupies 13.64% of all coding points in Level 1, but it covers 79.135% of the character occurrences in a typical Chinese text. In an ideal situation, a piece of Chinese text that contains enough characters should return us something like:

 Distribution Ratio =  0.79135/(1-0.79135) =3.79

And for a randomly generated text using the same encoding scheme, the ratio should be around 512 / (3755-512)=0.157 if no level 2 character is used.

If we include Level 2 characters into consideration, we can assume that the average probability of each Level 1 character is p1, and that of Level 2 is p2.  The calculation then would be:

512*p1 / (3755*p1 + 3008*p2 – 512*p1) = 512/(3755 + 3008*p2/p1-512)

Obviously, this value is even smaller. In a later analysis, we just use the worst case for comparison.
 

4.6.2. Big 5:


Big5 and EUC-TW (i.e. CNS Character Set) encodings have a very similar story.  Big5 also encodes Chinese characters in 2 levels. The most frequently used 512 characters are evenly scattered in 5401 Level 1 characters. The ideal ratio we can get from a big5-encoded text is:

Distribution Ratio = 0.74851/(1-0.74851) =2.98

And for a randomly generated text should have a ration near

512/(5401-512)=0.105

Since Big5 Level 1 characters are nearly identical to CNS plane 1 characters, the same analysis applies to EUC-TW.

4.6.3. Japanese Shift_JIS & EUC-JP:


For the Japanese Language, Hiragana and Katakana are usually more frequently used than Kanji. Because Shift-JIS and EUC-JP encode Hiragana and Katakana in different coding ranges, we are still able to use this method to distinguish among the two encodings.
Those Kanji characters that are among the most 512 frequently used characters are also scattered evenly among 2965 JIS Level 1 Kanji set.  The same Analysis leads to the following distribution ratio:

Distribution Ratio = 0.92635 / (1-0.92635) = 12.58

For randomly generated Japanese text data, the ratio should be at least

512 / (2965+63+83+86-512) = 0.191.

The calculation includes Hankaku Katakana (63), Hiragana (83), and Katakana (86).

4.6.4. Korean EUC-KR:


In EUC-KR encoding, the number of Hanja (Chinese) characters actually used in a typical Korean text is insignificant. The 2350 Hangul characters coded in this encoding are arranged by their pronunciation.  In the frequency table we got through analyzing a large amount of Korean text data, most frequently used characters are evenly distributed in these 2350 code points. Using the same analysis, in an ideal situation, we get:

Distribution Ratio = 0.98653 / (1-0.98653) = 73.24

For randomly generated Korean text, it should be:

512 / (2350-512) = 0.279.

4.6.5. Calculating Confidence Level:


From the foregoing discussions for each language script, we can define the Confidence level for each data set as follows:


Confidence Detecting(InputText)
{
  for each multi-byte character in InputText
  {
      TotalCharacterCount++;
      if the character is among 512 most frequent ones
          FrequentCharacterCount++;
  }

   Ratio = FrequentCharacterCount
                / (TotalCharacterCount-FreqentCharacterCount);
   Confidence = Ratio / CHARSET_RATIO;
   Return Confidence;
}


The Confidence level for a given set data is defined as the Distribution Ratio of the input data divided by the ideal Distribution Ratio obtained by the analyses in the preceding sections.

4.7.  Two-Char Sequence Distribution Method:

 
In languages that only use a small number of characters, we need to go further than counting the occurrences of each single character. Combination of characters reveals more language-characteristic information. We define a 2-Char Sequence as 2 characters appearing immediately one after another in input text, and the order is significant in this case. Just as not all characters are used equally frequently in a language, 2-Char Sequence distribution also turns out to be extremely language/encoding dependent. This characteristic can be used in language detection. This leads to better confidence in detecting a character encoding, and is very useful in detecting single byte languages.

Let’s use Russian language as an example. We downloaded around 20MB of Russian plain text, and wrote a program to analyze the text. The program found 21,199,528 2-Char sequence occurrences in total. Among the sequences we found, some of them are irrelevant for our consideration, e.g. space-space combination. These sequences are considered as noises, and their occurrences are not included in the analysis . In the data we used to detect the Russian language encodings, this left 20,134, 122 2-Char sequence occurrences.  That covers about 95% of all the sequence occurrences found in the data.  The sequences used in building our language model can be classified into 4096 different sequences, and 1961 of them appear fewer than 3 times in our 20,134,122 samples. We call these 1961 sequences as Negative Sequence Set of this language.

4.7.1. Algorithm for determining Confidence Level


For single-byte languages, we define the Confidence Level as follows:

Confidence Detecting(InputText)
{
  for each character in InputText
  {
      If character is not a symbol or punctuation character
          TotalCharacters++;
    Find its frequency order in frequency table;
      If (Frequency order < SampleSize)
      {
        FrequentCharCount++;
        If we do not have lastChar
        {
           lastChar = thisChar;
           continue;
        }
        if both lastChar and thisChar are within our sample range
        {
         TotalSequence++;
         If Sequence(lastChar, thisChar) belongs to NegativeSequenceSet
           NetgativeSequenceCount++;
        }
      }
   }
   Confidence = (TotalSequence – NegativeSequenceCount)/TotalSequence
                * FrequentCharCount / TotalCharacters;
   return Confidence;          
}  
 

There are several things in the algorithm that need to be explained.

First, this sequence analysis is not done to all characters. We can build a 256 by 256 matrix to cover all those sequences, but many of those are irrelevant to language/encoding analysis and thus unnecessary.  Since most single-byte languages use fewer then 64 letters, the most frequently used 64 characters seem to cover almost all the language specific characters.  This way, the matrix can be reduced to 64 by 64, which is much smaller.  So we are using 64 as our SampleSize in this work. The 64 characters we choose to build our model are mostly based on the frequency statistics with some adjustment allowed. Some characters, such as 0x0d and 0x0a, play roles very similar to the space character (0x20) in our perspective, and thus have been eliminated from the sampling.

Second, for all the sequences covered by this 64 by 64 model, some sequences are also irrelevant to detecting language/encoding.  Almost all single-byte language encodings include ASCII as a subset, it is very common to see a lot of English words in data from other languages, especially on web sites. It is also obvious that the space-space sequence has no connection with any language encoding. Those are considered as “noise” in our detection and are removed by filtering.
 
Third, in calculating confidence, we need to also count the number of characters that fall into our sample range and those that do not. If most of the characters in a small sample data do not fall into our sampling range, the sequence distribution itself may return us a high value since very few negative sequences might be found in such a case.  After filtering, most of those characters that have been fed to the detector should fall into the sampling range if the text is in the desired encoding. So the confidence obtained from counting negative sequences needs to be adjusted by this number.

To summarize the foregoing:

  • Only a subset of all the characters are used for character set identification. This keeps our model small. We also improved detection accuracy by reducing noise.
  • Each language model is generated by a script/tool.
  • Handling of Latin Alphabet characters:
  • If the language does not use Latin Alphabet letters, Alphabet -letter to Alphabet -letter sequences are removed as noise for detection. (e.g. English words frequently appear in web pages of other languages.)
  • If the language does use Latin Alphabet letters, those sequences are kept for analysis.
  • The number of characters that fall into our sample range and those that do not are counted so that they can be used in calculating the Confidence Level.

 

5. Comparison of the 3 methods:

 

5.1. Code scheme:


For many single-byte encodings, all code points are used fairly evenly. And even for those encodings that do contain some unused code points, those unused code points are seldom used in other encodings and are thus unsuitable for encoding detection.

For some multi-byte encodings, this method leads to a very good result and is very efficient. However, because some multi-byte encodings such as EUC-CN and EUC-KR share almost identical coding points, it is very hard to distinguish among such encodings with this method. Considering the fact that a browser normally does not have a large amount of text, we must resort to other methods to decide on an encoding.  

For 7-bit multi-bye encodings like ISO-2022-xx and HZ, which use easily recognizable escape or shift sequences, this method produces satisfactory results. Summarizing, the Code Scheme method,

  • is very good for 7-bit multi-byte encodings like ISO-2022-xx and HZ.
  • is good for some multi-byte encoding like Shift_JIS and EUC-JP, but not for others like EUC-CN and EUC-KR.
  • is not very useful for single-byte encodings.
  • can apply to any kind of text.
  • is fast and efficient.


5. 2. Character Distribution:


For multi-byte encodings, and especially those that can not be handled reliably by the Code Scheme method, Character Distribution offers strong help without digging into complicated context analysis. For single-byte encodings, because the input data size is usually small, and there are so many possible encodings, it is unlikely to produce good results except under some special situations. Since the 2-Char Sequence Distribution method leads to a very good detection result in such a case, we have not gone further with this method on single-byte encodings. Summarizing these points, the Character Distribution Method

  • is very good for multi-byte encodings.
  • only applies to typical text.
  • is fast and efficient.


5.3.  2-Char Sequence Distribution:


In the 2-Char Sequence Distribution method, we can use more information data in detecting language/encodings. That leads to good results even with a very small data sample. But because sequences are used instead of words (separated by a space), the matrix will be very big if it was to apply to multi-byte languages. Thus this method:
 

  • is very good for single-byte encodings.
  • is not efficient for multi-byte encodings.
  • can lead to good results with even small sample size.
  • only applies to typical text.

 

6. A composite Approach:

 

6.1. Combining the 3 methods:


Languages/encodings we want to cover with our charset auto-detector includes a number of multi-byte and single-byte encodings.  Given the deficiencies of each method, none of the 3 methods alone can produce truly satisfactory results.  We propose, therefore, a composite approach which can deal with both types of encodings.

The 2-Char Sequence Distribution method is used for all single-byte encoding detections.
The Code Scheme method is used for UTF-8, ISO-2022-xx and HZ detection. In UTF-8 detection, a small modification has been made to the existing state machine. The UTF-8 detector declares its success after several multi-byte sequences have been identified.  (See Martin Duerst’s (1977) detail). Both the Code Scheme and Character Distribution methods are used for major East Asian character encodings such as GB2312, Big5, EUC-TW, EUC-KR, Shift_JIS, and EUC-JP.

For Japanese encodings like Shift_JIS and EUC-JP, the 2-Char Sequence Distribution method can also be used  because they contain a significant number of Hiragana syallbary characters, which work like letters in single-byte languages.  The 2-Char Sequence Distribution method can achieve an accurate result with less text material.

We tried both approaches -- one with the 2-Char Distribution Method and the other without.  Both led to quite satisfactory results. There are some web sites which contain a lot of Kanji and Katakana characters but only a few Hiragana characters. To achieve the best possible result, we use both the Character Distribution and 2-CharDistribution methods  for Japanese encoding detection.

Here then is one example of how these 3 detection methods are used together.  The upper most control module (for auto-detectors) has an algorithm like the following:


Charset AutoDetection (InputText)
{
   if (all characters in InputText are ASCII)
   {
       if InputText contains ESC or “~{“
       {
          call ISO-2022 and HZ detector with InputText;
          if one of them succeed, return that charset, otherwise return ASCII;
       }
       else
          return ASCII;
   }
   else if (InputText start with BOM)
  {
      return UCS2;
  }
  else
  {
      Call all multi-byte detectors and single-byte detectors;
      Return the one with best confidence;
  }
}



Summarizing the sequences in the code fragment above,

  • Most web pages are still encoded in ASCII. This top-level control algorithm begins with an ASCII verifier. If all characters are ASCII, there is no need to launch other detectors except ISO-2022-xx and HZ ones.
  • ISO-2022-xx and HZ detectors are launched only after encountering ESC or “~{“, and they are abandoned immediately when a 8-bit byte is met.
  • BOM is being searched to identify UCS2. We found that some web sites send 0x00 inside http stream, and using this byte for identifying UCS2 proved to be unreliable.
  • If any one of the active detectors received enough data and reaches a high level of confidence, the entire auto-detecting process will be terminated and that charset will be returned as the result. This is called shortcut.

 

6.2.  Test Results:


As a test for the approach advocated in this paper, we applied our detector(s) to the home pages of 100 popular international web sites without document-based or server-sent HTTP charset.  For all the encodings covered by our detector(s) we were able to achieve 100% accuracy rate.

For example, when visiting a web site that provides no charset information (e.g. the web site at http://www.yahoo.co.jp before its server started sending the charset info), our charset detector(s) generates output like the following:

[UTF8] is inactive
[SJIS] is inactive
[EUCJP] detector has confidence 0.950000
[GB2312] detector has confidence 0.150852
[EUCKR] is inactive
[Big5] detector has confidence 0.129412
[EUCTW] is inactive
[Windows-1251 ] detector has confidence 0.010000
[KOI8-R] detector has confidence 0.010000
[ISO-8859-5] detector has confidence 0.010000
[x-mac-cyrillic] detector has confidence 0.010000
[IBM866] detector has confidence 0.010000
[IBM855] detector has confidence 0.010000

This then leads to the determination that EUC-JP is the most likely encoding for this site.

7. Conclusion:


The composite approach that utilizes Code Scheme, Character Distribution and 2-Char Sequence Distribution methods to identify language/encodings has been proven to be very effective and efficient in our environment. We covered Unicode encodings, multi-byte encodings and single-byte encodings. These are representative encodings in our current digital text on the Internet. It is reasonable to believe that this method can be extended to cover the rest of the encodings not covered in this paper.

Though only encodings information is desired in our detection results at this time, language is also identified in most cases. In fact, both Character Distribution and 2-Char Distribution methods rely on characteristic distributional patterns of different language characters. Only in the case of UTF16 and UTF8, encoding is detected but the language remains unknown. But even in such cases, this work can still be easily extended to cover language detection in future.

The 3 methods outlined here have been implemented in Netscape 6.1 PR1 and later versions as the “Detect All” option. We expect our work in auto-detection to free our users further from having to deal with cumbersome manipulations of the Character Coding menu.  The Character Coding menu (or Encoding menu for others) is different from other UI items in the Internet client in that it exposes part of the i18n backend to general users. Its existence itself is a mirror of how messy today’s web pages are when it comes to language/encoding.

We hope that offering good encoding default and universal auto-detection will help alleviate most of the encoding problems our users encounter in surfing the net. Web standards are shifting toward Unicode, particularly, toward UTF-8, as the default encoding. We expect gradual increase of its use on the web. Such shifts need not be overt as more and more users are freed from confronting issues related to encoding while browsing or reading/sending messages, thanks in part to auto-detection.  This is why we advocate good auto-detection and good default encoding settings for Internet clients.

8. Future Work:


Our auto-detection identifies a language. The encoding determination is a byproduct of that determination. For the current work, we only covered Russian as an example of single-byte implementation.  Since it identifies a language and only then which encoding it uses, the more language data models there are, the better the quality of encoding detection.

To add other single-byte languages/encodings, we need a large amount of text sample data for each language and certain degree of language knowledge/analysis.  We currently use a script to generate a language model for all the encodings for that language.

This work is at present not in the Mozilla source but we hope to make it public in the near future. When we do, we hope people with the above qualification will contribute in this area. Because we have not yet tested many single-byte encodings, it is likely that the model we propose here needs to be fine-tuned, modified or possibly even re-designed when applying to other languages/encodings.

 9. References:

Duerst, Martin. 1977. The Properties and Promizes of UTF-8.  11th Unicode Conference.
     http://www.ifi.unizh.ch/groups/mml/people/mduerst/papers/IUC11-UTF-8.pdf
Mandarin Promotion Council, Taiwan. Annual survey results of Traditional Chinese character usage.
  http://www.edu.tw/mandr/result/87news/index1.htm
Mozilla Internationalization Projects.  http://www.mozilla.org/projects/intl
Mozilla.org.  http://www.mozilla.org/
Mozilla source viewing.  http://lxr.mozilla.org/

이 글은 스프링노트에서 작성되었습니다.

16 윈도우 Network Share 함수

 원문 :  http://kkamagui.springnote.com/pages/773470

 

Network Share Management Functions

The Network Share Management functions can be grouped as follows.

NetFile Functions

NetFileClose
NetFileClose2
NetFileEnum
NetFileGetInfo

Session Functions

NetSessionDel
NetSessionEnum
NetSessionGetInfo

Network Share Functions

NetConnectionEnum
NetShareAdd
NetShareCheck
NetShareDel
NetShareEnum
NetShareGetInfo
NetShareSetInfo

Statistics Function

NetStatisticsGet

 

이 글은 스프링노트에서 작성되었습니다.

05 스프링노트(Springnote) API

원문 : http://nakada.springnote.com/pages/400945

 

들어가기 전에

 

0.시작하면서...

 파이썬(Python)에서 스프링노트에 접근하는 내용을 스크랩했다.

 

1.스크랩 내용

  • 참고한 소스 
    • 하늘모자님이 작성하신 python에서 스노피 소스 읽고 쓰기 http://doc.springnote.com/pages/313680 를 참고하여 8월 1일부터 바뀐 API 인증에 맞게 하였습니다.
    • ias 님이 루비로 작성하신 스노피 소스 읽고 쓰기 http://dev.springnote.com/pages/3364 를 참고하여 새로 바뀐 인증방식에 적용 하였습니다.
  • 변화된 사항 
    • 하늘모자님의 소스에서 바뀐 부분은 HTTPS 을 이용한 인증부분과 쉘상에서 입력받을때 \n 을 무조건 없애던것을 수정하였으며, 탭을 공백 4개로 표시하게 하였습니다.
    • ias 님의 소스에서와 같이 파일을 read 하여 data 를 작성하는것은 src=sys.stdin.read() 부분만 src = open('파일이름').read() 로 해주시면 됩니다.
  • 특이사항 
    • from xml.etree.ElementTree import XML 부분의 경우 python 2.5 이상에서만 됩니다. 굳이 필요하지 않으므로 해당 부분을 제거하고 소스에서  print XML(r).findtext('source')  부분만 그냥 print r 로 해도 되며 다른 xml 모듈을 사용해서 가공하시면 됩니다.
    • multipart/form-data 를 통한 파일 첨부는 제 능력 부족으로 구현하지 못하고 있습니다. 정보 있으시면 연락주세요
    • 아직 잘 작성하지 못해서 좋은 정보나 관련된 정보 주시면 감사하게 받겠습니다. 연락은 제 블로그나 메일로 주세요
  • 연락처 

 

  1. #!/usr/bin/python
  2. import sys
  3. from ConfigParser import SafeConfigParser
  4. import base64
  5. import urllib
  6. import httplib
  7. import cgi
  8. from xml.etree.ElementTree import XML
  9. class SpringNote:
  10.     def __init__(self):
  11.         self.config = SafeConfigParser()
  12.         self.config.read('spring.conf')
  13.         open_id = self.config.get('springnote','open_id')
  14.         user_key = self.config.get('springnote','user_key')
  15.         app_key = self.config.get('springnote','app_key')
  16.         username = urllib.quote(open_id)
  17.         passwd = urllib.quote('%s.%s' % (user_key, app_key))
  18.         self.basic_auth = 'Basic %s' % base64.b64encode('%s:%s' % (username, passwd))
  19.     def httpReq(self, method, uri, data = None):
  20.         HOSTNAME = 'api.springnote.com'
  21.         conn = httplib.HTTPSConnection(HOSTNAME)
  22.         conn.putrequest(method, uri)
  23.         conn.putheader('Authorization', self.basic_auth)
  24.         if data :
  25.             conn.putheader('Content-Type','application/xml')
  26.             conn.putheader('Content-Length', len(data))
  27.         conn.endheaders()
  28.         if data :
  29.             conn.send(data)
  30.         response = conn.getresponse()
  31.         r = response.read()
  32.         conn.close()
  33.         print XML(r).findtext('source')
  34.     def getPage(self, page_id):
  35.         self.httpReq('GET','/pages/%s.xml' % page_id)
  36.     def putPage(self, page_id):
  37.         print 'input page content:'
  38.         src = sys.stdin.read()
  39.         src_html = '<p>%s</p>' % cgi.escape(src).replace('\r', '').replace('\t','&nbsp;'*4).replace('\n', '</p>\n<p>').replace('<p></p>','<p>&nbsp;</p>')
  40.         data = "<page><source>%s</source></page>" % cgi.escape(src_html)
  41.         self.httpReq('PUT', '/pages/%s.xml' % page_id, data)
  42.     def main(self, cmd, arg):
  43.         if cmd == 'get':
  44.             self.getPage(arg)
  45.         elif cmd == 'put':
  46.             self.putPage(arg)
  47. if __name__ == "__main__":
  48.     SpringNote().main(sys.argv[1], sys.argv[2])

 

이 글은 스프링노트에서 작성되었습니다.

 지금까지 한 RSS 리더를 쓰고 있었습니다. 좌측에 RSS 목록이 표시되고 우측에 세부내용이 표시되는 형식이지요. 상당히 편리한 구조라고 생각합니다. ^^

 그런데 오늘 재미있는 글을 읽었습니다. RSS의 내용을 책처럼 표시해주면 어떨까하는 글이었는데, 원문은 http://naggingmachine.tistory.com/253 에서 보실 수 있습니다. 이 글을 보자마자 너무 아무생각없이 살고 있던게 아닌가 하는 생각이 들었습니다.

 물론 웹브라우저를 통해 RSS의 내용을 보니 웹브라우저의 인터페이스를 그대로 따르는 것이 자연스럽다고 생각되지만(스크롤하고 링크를 누르는...), 책처럼 표시되게 만드는 것도 그리 어렵지는 않을 것 같습니다. 최악의 방법은 화면을 한 화면 크기로 캡쳐해서 표시하는 방법도... ㅡ_ㅡa... (최악의 상황입니다. 최악.. ㅎㅎ)

 아니면 CSS를 어떻게 잘 편집해서 화면을 좌우로 분할한 다음 책처럼 표시해주는 방법도 있겠지요. ^^ 요즘 와이드 LCD를 많이 쓰니 분할하면 예쁘게 나올듯도 합니다.

 시간나면 한번 만들어봐야겠습니다. 뭔가 색다를듯 하군요. ^^)/~

 
 지난 번 위모트(Wii Remote)를 이용해서 멀티 터치 화이트 보드를 만드는 동영상( http://kkamagui.tistory.com/266 )을 만드신 분께서 새로운 동영상을 찍으셨습니다. 상당한 충격이었는데, 이분이 이번에는 헤드 트래킹(Head Tracking)을 이용해서 VR 디스플레이를 만드셨군요. 대단합니다. ㅜ_ㅜ=b

 이 분의 펜클럽이라도 만들어야겠습니다. 아주 그냥 신선한 아이디어가 흘러 넘치시는군요. ㅜ_ㅜ 게임 같은 것에 응용하면 상당히 괜찮겠네요. 저도 나중에 한번 시도해 봐야겠습니다. ^^;;;
 



 백업을 위해 하드디스크에 여유공간을 확보할 일이있어서 어떤 파일을 삭제할까 한참을 고민했습니다. 시디 이미지를 지울까 고민하다가, 문득 빌드 과정에서 나오는 파일의 크기가 크다는 것이 떠올랐습니다. >ㅁ<)/~!!

 처음에는 윈도우의 검색기능을 이용해서 지우기를 했었는데, 의외로 시간도 많이 걸리고 불편하더군요. 그래서 간단히 파이썬으로 코드를 짜봤습니다. ExtList에 다른 확장자를 추가하면 기타 파일도 삭제를 할 수 있습니다.

 파이썬의 저력을 다시 한번 느꼈습니다. 아주 금방되더군요. ^^;;; 이걸 C 언어로 짰어도 이렇게 빨리 끝났을까요? 한 10분정도 걸렸는데... ㅡ_ㅡa...

 아래는 지워주는 코드입니다.


 파이썬 만세~~!! >ㅁ<)/~~!!!

ps) OS에 대한 내용은 http://docs.python.org/lib/os-file-dir.html 를 참고하세요. ^^


03 위모트(Wii Remote) 자료

닌텐도 위모트(Wii Remote)를 이용해서 PC용 프로그램을 작성하는 것에 관한 내용을 모아 놓았다.

 

유용한 링크

 

정보

  • 위모트에서 송신되는 데이터는 IR LED를 2개까지 인식함

    • 위모트 개발 라이브러리의 HID Report 데이터를 참고

이 글은 스프링노트에서 작성되었습니다.

 멀티 터치 화이트 보드를 만드는 동영상(http://kkamagui.tistory.com/266)을 보고 뽐뿌를 이기지 못해 질러버렸습니다. ㅜ_ㅜ... 아아 정말 이번 것은 굉장히 강력하더군요.

 PSP의 뽐뿌를 물리치고 바로 지르게 만드는 위모트... 개발 욕구가 불타서 이건 뭐.... 어쩔 수 없었습니다. 흑흑... 오늘 질렀으니 수요일이나 목요일쯤 되면 택배가 오겠네요. 나중에 CRT 모니터에 터치스크린을 구축할껀데, 잘되면 동영상이라도 하나 올리겠습니다.

 재미있는 장난감이 많아서 큰일났습니다. ㅜ_ㅜ... 살려주세요... ㅜ_ㅜ...
 유튜브에서 굉장한 동영상을 발견했습니다. 닌텐도 위(Wii)에서 사용할 수 있는 조정기인 위 리모트(일명 위모트)를 이용해서 애플 아이터치나 아이폰에서나 가능한 멀티터치 화이트 보드를 만들었습니다.
 
 아래의 동영상을 보시면 아시겠지만, 싼 볼펜을 개조해서 만든 LED 펜으로 화이트보드를 클릭하면 마우스가 따라 움직입니다. 더 놀라운 것은 2개의 팬으로 클릭하면 멀티 터치가 되는군요. ^^;;;


 카네기 멜론 대학에서 공부하는 학생인 것 같던데... 대단하다는 생각이 듭니다. 아래의 동영상은 다른 방식으로 위모트를 이용해서 TV를 제어하는 동영상인데, 이것 또한 아주 멋지군요. @0@)/~!!!!

 이 분의 사이트( http://www.cs.cmu.edu/~johnny/projects/wii/ )에서 더 자세한 내용을 볼 수 있습니다. ^^

 위모트를 위한 개발 툴킷도 공개되어있는 것 같던데, 위모트를 하나 사면 유용하게 사용할 수 있을 것 같습니다. 이런 것이라면 방 구석에 위모트를 연결해 놓고 누워서 재미있는 일들을 할 수 있겠군요. ^^;;;;
 
 PSP를 살까 했었는데, 위모트를 사는게 더 좋을지도 모르겠습니다. 개발자에게 불을 당기는 이런 동영상을 봐버리다니... ㅜ_ㅜ... 다시 개발 의욕이 불타는 군요. ㅜ_ㅜ...

 마이크로 소프트웨어 3월호 원고도 써야하는데, 이런 이런.... 개발자가 천직인가 봅니다. ㅜ_ㅜ...


 블로그를 순회하다보면 가끔 포스트 하단에 각종 RSS의 구독 버튼이 달려있는 것을 쉽게 볼 수 있습니다. 어떻게 하는 것인지 궁금했는데, 오늘에서야 그 비밀을 알게 됬습니다. ^^)/~
사용자 삽입 이미지

RSS 리더 구독 권유 버튼


  "리플바" 라고하는 자바스크립트더군요. ^^ http://skin.repl.net/bookbar/index.html 에 가면 각 블로그 별로 추가할 수 있는 템플릿 코드를 생성해 줍니다. 제 블로그(kkamagui.tistory.com)을 넣어서 생성하니 아래와 같은 코드가 나오더군요.
사용자 삽입 이미지

리플바 사이트


 생성된 코드는 아래와 같습니다.

 위의 코드를 티스토리 스킨 편집에서 붙여넣으면 끝입니다. ^^ 방금 추가했는데, 아주 멋지군요. >ㅁ<)/~!!! 신나는 하루입니다. ^^;;;;

 크래커가 PC 제어를 목적으로 만든 프로그램이 내 PC에 설치되어서 내 의지와는 상관없이 광고를 클릭하던지 이상한 곳으로 메일을 보내는 등의 일을 한다는 군요. 뭐 개인 정보를 빼내가는 건 당연한 것이고 그 외의 작업들은 옵션인 듯 합니다.

 외국의 어떤 해커가 해군 시스템에 프로그램을 심어서 광고를 클릭하게 했다던데... 참 대단한 생각을 했더군요. 점검도 잘 안하고 허술하다는 것을 알고 한 것일까요? 한대만 뚫리면 근처에 비슷한 IP를 사용하고 있는 PC가 감염되는 것은 일도 아니겠습니다만은... 그래도 해군 시스템인데.... ㅡ_ㅡa...

 PC가 삶에 깊숙히 파고들어서 PC를 켜놓는 시간이 늘어나게 됬는데, 이런 점을 악용하는 군요. 안티 바이러스 프로그램은 필수가 된지 오래고, 이제는 전문 안티 봇 프로그램을 따로 깔아야 하는 것은 아닌지 걱정이됩니다. ㅜ_ㅜ...

 프로세스를 주기적으로 모니터링 해야겠네요. (프로그램을 또 하나 만들어야 하는 것인가.. ㅜ_ㅜ)


 2002년에 마이크로 소프트의 NTFS 테스트 팀에서 테스트를 해본 모양입니다. 최대 16TB까지 생성할 수 있는 파일시스템을 실제로 생성가능한지 테스트를 해봤다는 군요. ^^;;;; 원문은 http://blogs.msdn.com/oldnewthing/archive/2007/12/04/6648243.aspx 에서 보실 수 있습니다.

 16TB의 파일을 생성하는데 3일이 걸렸고 다시 읽어서 똑바로 파일이 생성됬는지 체크하는데 4일이 걸렸다는군요. 이런 테스트까지 하다니.... ㅡ_ㅡa... 그냥 입이 떡 벌어집니다.

 저 같으면 2시간 정도 돌려보고 포기했을텐데 말이지요... ㅎㅎ 덕분에 정말 16TB까지 생성되는지 확인 안해봐도 될 것 같네요 ㅎㅎ


 http://teamblog.joinc.co.kr/yundream/184 에서 글을 읽다가 깜짝 놀랄만한 것을 발견했습니다. @0@)/~!!! D 언어에 대해서 글을 읽는 중이었는데, D 언어로 만든 게임이 상당하더군요. 원문은 http://www.asahi-net.or.jp/~cs8k-cyu/windows/ttn.html 에서 보실 수 있습니다.

 아래는 게임의 스크린 샷인데, 폴리곤으로 단순하게 만들었음에도 불구하고 속도감이나 조작감이 장난이 아니더군요. ^^
사용자 삽입 이미지

게임 화면



조작 키는 아래와 같습니다.
방향키 : 아군 비행기의 이동
Control  키 : 총알 발사
Alt or Shift 키 : 적 비행기 훔치기

 적 비행기를 훔치면 아군이 되면서 같이 총알을 발사해준다는 멋진... ㅜ_ㅜ)=b 게임 모드도 Basic, Classic, Morden 이 있는데 Morden이 아주 끝내줍니다. ^^

 정말 시간때우기는 아주 좋은 게임인 듯~, 우리 모두 빠져 보아요~ >ㅁ<)/~!!

 저는 지금까지 "GPL은 공개 소스이며 무조건 소스를 공개해야하고 상용으로 판매할 수 없다"고 생각하고 있었는데 그게 아니었군요. GPL에 대한 자세한 내용은 http://teamblog.joinc.co.kr/yundream/37 에서 볼 수 있습니다.

 GPL에 대해서 간단히 요약하자면 아래와 같습니다.
1. GPL 라이센스는 배포 시에 적용되는 라이센스이기 때문에 배포하지 않는 한 소스를 공개할 필요는 없습니다.
2. GPL 라이센스라도 배포시에 소스를 같이 배포한다면 상용이라도 문제 없다.
3. GPL 라이센스 변경은 저작권자 만이 가능하며, 이미 배포된 버전에 대해서는 변경을 가할 수 없고 새로운 버전에 대해서는 변경가능하다.

 요즘 저작권에 대해서 이런 저런 말이 많은데, 시간나면 저작권에 대해서도 알아두는 것이 좋겠군요. ^^

02 CSS(Cascading Style Sheet)-Part1

 원문 : http://kkamagui.springnote.com/pages/623396

 

들어가기 전에...

 

1.CSS(Cascading Style Sheet)?

 CSS는 웹페이지의 외형을 편리하고 능률적으로 바꿀 수 있도록 해준다. 대부분의 웹 브라우져(Web Browser)는 CSS와 HTML 코드를 연동하여 웹 페이지를 표시할 수 있다. 다만 브라우져간의  약간의 차이 때문에 특정 스타일은 정상적으로 표시되지 않을 수 있으나 대부분은 잘 동작한다.

 

 CSS를 사용하여 얻는 장점은 아래와 같다.

  • HTML 코드에서 디자인에 대한 코드를 줄일 수 있음
  • CSS를 수정함으로써 일괄로 페이지의 스타일을 수정 가능 
  • HTML 코드의 크기를 줄임으로써 웹페이지의 로딩 속도를 빠르게 할 수 있음(CSS는 브라우져에 의해 캐슁될 수 있으므로 효율적으로 동작 가능) 

 

 그럼 이제부터 CSS에 대해서 알아보자.

 

2.XHTML

 HTML의 차기버전으로 HTML의 문제점을 보완한 대체 HTML이다.  XHTML의 필수적인 조건은 아래와 같다.

  • Doctype을 반드시 명세해야 함
  • 태그(Tag)는 반드시 짝을 이루어야 함. ex) <p> </p> or <p />
  • 태그는 반드시 소문자로 써야 함. 
  • Attribute는 반드시 " "로 묶어줘야 함. ex) <a href="http://kkamagui.tistory.com" > 까마구의 블로그 </a> 

 

 아래는 XHTML로 구성된 스프링노트 페이지의 한 예이다. DOCTYPE 같은 경우는 거의 고정적이므로 저장해 놨다가 붙여 넣으면 된다.

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko">
  2. <head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> 
  3. <title> kkamagui의 블로그 </title> 
  4. </head> 
  5. <body> 
  6. <p> 페이지의 내용이다. </p> 
  7. </body> 
  8. </html> 

 

3.스타일 시트(Style Sheet)의 종류

3.1 내부 스타일 시트(Internal Style Sheet)

 내부 스타일 시트는 HTML 코드 내에 스타일 시트에 대한 내용이 포함된 것을 의미한다. 일반적으로 스타일 시트 코드는 <head> 태그 안에 포함되며 아래와 같은 형식으로 사용된다.

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko">
     
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=EUC_KR" />
    <title> kkamagui의 블로그 </title>
    <!-- 스타일 코드 시작 -->
    <style type="text/css">
    h1
    {
        color : #FF7643;
        font-family : Arial;
    }
  2. p
    {
        color : red;
        font-size : 0.9em;
    }
    </style>
    </head>
  3. <body>
    <h1 /> 큰 제목입니다. ^^;;
    <p /> 내용 입니다.
    </body>
  4. </html> 

 <style type="text/css"> 태그를 이용해서 아래의 코드가 HTML이 아닌 css 임을 알려주고 해당 Element의 속성을 적어주면 된다.

 

3.2 외부 스타일 시트(External Style Sheet)

 외부 스타일 시트는 스타일 시트가 HTML 코드 외부에 있음을 나타낸다. HTML 코드에는 스타일 코드 대신에 스타일 시트의 경로가 포함된다. 아래는 XHTML의 내용이다.

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko">
     
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=EUC_KR" />
    <title> kkamagui의 블로그 </title>
    <link rel="stylesheet" type="text/css" href="test.css" />
    </head>
  2. <body>
    <h1 /> 큰 제목입니다. ^^;;
    <p /> 내용 입니다.
    </body>
  3. </html> 

 

  아래는 text.css 파일의 내용이다.

  1. h1
    {
        color : #FF7643;
        font-family : Arial;
    }
  2. p
    {
        color : red;
  3.     font-size : 0.9em;

 

 실제 HTML 코드와 스타일 시트가 분리되므로 같은 스타일을 여러 페이지에 걸쳐서 적용하기가 편리한 장점이 있다.

 

4.CSS 기본

4.1 CSS의 스타일 구성

 CSS의 스타일은 2가지로 구분된다. 첫번째는 선택자(Selector)이고 두번째는 선언구간이다. 위의 예제에서 선택자와 선언구간을 나누어 보면 아래와 같다.

  1. h1 // 선택자, 페이지 내의 h1 태그를 의미
    {  // 선언 구간. 속성을 정의
        color : #FF7643;
        font-family : Arial;

  간단히 설명하면 속성을 정의할 태그를 먼저 정의하고 그 하부 속성들을 {}로 감싸면 된다.

 

4.2 클래스 선택자(Class Selector) 및 ID

 태그중 특별한 태그만 속성을 다르게 주고 싶을 때 사용할 수 있는 방법 중에 하나이다. 태그의 클래스를 정의해서 해당 클래스를 가진 태그에만 속성을 적용할 수 있다. HTML 코드에 아래를 추가하고 CSS에 .RedH1의 속성을 추가함으로써 h1의 속성을 재정의 할 수 있다.

  1. <h1 class="RedH1" /> 큰 제목2 입니다. abcdefg ^^;;
    <p /> 내용 입니다.
    </body>

 

 아래는 RedH1 이라는 클래스를 정의한 것이다.

  1. .RedH1 
  2. color : red; 

 주의할 점은 CSS에서 클래스를 정의할때 "." 기호를 사용해야 한다는 점이다.

 

 비슷한 역할을 ID로도 할 수 있다. ID는 #으로 CSS에 표시하며 아래와 같이 사용가능하다.

  1. <h1 ID="BlueH1" /> 큰 제목3 입니다. abcdefg ^^;;
    <p /> 내용 입니다.
    </body> 

 

  1. #BlueH1
    {
        color: blue;
    }

 

4.3 하위, 그룹, 전체 선택자 속성 정의

 위에서 언급했던 방식으로 간단히 스타일 시트를 구성하면 모든 태그 또는 모든 클래스에 스타일이 적용된다. 하지만 특정 태그 하위의 태그만 속성을 다르게 하고 싶다면 어떻게 할가? 클래스를 다 정의해서 클래스를 넣어주면 될까?

 간단히 해결할 수 있는 방법은 하위 선택자를 직접 기술해서 사용하면 된다. 만약 RedP 아래에 div 태그에만 특별한 속성을 주고 싶다면 아래와 같이 입력하면 된다.

  1. .RedP div 
  2.     color : red; 

 

 또 다른 방법으로는 아래와 같이 입력할 수도 있다. 아래는 RedDiv를 클래스명으로 가지는 div에 속성을 적용하는 방법이다.

  1. div.RedDiv 
  2. {
  3.     color : red;

 

 그룹 선택자는 "," 로 구분하며 클래스, ID, 태그 모두 표현 가능하다. 아래는 그룹 선택자의 예제이다.

  1. h1, p, .RedP { color : red; } 

 

 만약 .RedP의 모든 클래스에 속성을 적용하고 싶다면 "*"를 사용하면 된다.

  1. .RedP * { font-wieght : bold; } 

 

 많이 쓰는 태그중에 링크를 빠뜨릴 수 없는데, 링크는 크게 4가지의 상태를 가진다. 각 상태별로 특별한 속성을 지정해 줄 수 있다.

  • a:link : 미방문 링크 또는 마우스가 링크 위에 있을 때의 상태
  • a:visited : 이미 방문한 링크
  • a:hover : 마우스가 링크 위를 움직일 때
  • a:active : 방문자가 링크를 클릭할 때 

 

5.각 태그별 사용가능 속성

5.1 font

 font 태그는 아래과 같은 속성들을 가지고 있다.

  • font-family : 화면에 표시할 글꼴들의 집합. 대체 글꼴을 위해 여러가지 글꼴을 나열할 수 있음

    • font-family : "Arial", "돋움체", "굴림체"; 
  • color : 글자 색을 설정

    • font : #RRGGBB; or balck;
    • font : rgb( 255, 255, 255); or rgb( 100%, 100%, 100% );
  • font-size : 글자의 크기를 변경

    • font-size : 1em; or  100% or 12px;
    • %나 em 계산법은 하위 태그에 상속되므로 주의해서 써야 함 
  • font-style : 이탤릭으로 바꾸거나 되돌림

    • font-style : italic; or normal; 
  • font-weight : 폰트를 bold로 바꾸거나 되돌림

    • font-weight : bold; or normal; 
  • font-decoration : 줄을 긋거나 지움 

    • font-decoration : underline; or overline; or line-through; or none; or underline overline; 
  • letter-spacing : 자간(단어와 단어간의 간격)을 늘리거나 줄임. 양수의 경우 기본 간격보다 넓어지고 음수의 경우 좁아짐

    • letter-spacing : -1px; or 1px; or -.1em; 
  • line-height : 줄간격 조절. 하위 태그에 상속되니 주의해야 함. 단 아무 단위도 없는 숫자는 배수를 의미하므로 글자의 크기에 배수가 됨(많이 씀).

    • line-height : 150%; or 1.5em; or 10px; 1.5;
  • text-align : 글자의 배치를 결정 

    • text-align : center; or left; or right; or justify; 
  • text-indent : 첫줄을 들여쓰거나 내어씀. 양수이면 들여쓰고 음수이면 내어씀

    • text-indent : 25px; or 1em; 
  • margin : 단락 사이의 간격을 조절. left, right, top, bottom 이 있음

    • margin : 0; or margin-left : 0; 

 

5.2 리스트 목록 스타일(ul, ol)

  • list-style-type : 목록 앞의 첨자를 붙이는 방식 정의. square, disk, circle, none, decimal, decimal-leading-zero, upper-alpha, lower-alpha, upper-roman, lower-roman 중에서 선택 가능

    • list-style-type : square; or none; 

 

5.3 테두리(Border)

 테두리는 크게 아래의 3가지 속성을 가진다.

  • color : 테두리의 색깔
  • width : 테두리의 넓이

    • thin, medium, thick와 같은 키워드 사용가능 
    • px 값 사용 가능 
  • style : 테두리의 모양

    • solid, dotted, dashed, double, groove, ridge, inset, outset, none, hidden 사용 가능 

 

 속성을 설정하는 방법은 아래와 같다.

  • border 4px solid red; or border-left : 2px solid black;
  • border-width : 2px; 
  • border-style : double; 
  • border-color : red; 

 

5.4 배경색 및 너비/높이 그리고 오버 플로우(overflow) 처리

  • background-color : 배경색을 정의

    • background-color : red; 
  • height : 높이를 정의

    • height : 20px; or 2em; or 30%;
  • width :  너비를 정의

    • width :  20px; or 2em; or 30%;
  • overflow : content가 영역을 넘어갈 때 표시할 방법

    • overflow : visible; : 아무런 처리를 안함 
    • overflow : scroll; : 무조건 스크롤바 생성 
    • overflow : auto; : 넘어가면 스크롤바 생성. 안 넘어가면 아무 처리 안함
    • overflow : hidden; : 넘어가는 영역 표시 안함 

 

5.5 float and clear

 float는 간단하게 말하면 element를 좌측이나 우측으로 옮겨서 사이드 바와 같은 형태로 만들어 주는 것을 말한다.

  • float : 해당 element를 좌측 or 우측 으로 이동하거나 원래대로 되돌려 놓음

    • float : left; or right; or none; 
  • clear : float element가 여러개가 있을 때 표시 방식을 표시. left, right, both, none 속성을 가짐. 주위의 float element가 아래로 내려가도록 함

    • clear : left; or right; both; none;

 

 아래는 float을 테스트하기위한 간단한 코드이다.

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko">
     
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=EUC_KR" />
    <title> kkamagui의 블로그 </title>
    <link rel="stylesheet" type="text/css" href="test.css" />
    </head>
  2. <body>
    <h1> 큰 제목1 입니다. abcdefg ^^;; </h1>
  3. <div class="subnote">아무것도 없는 허허벌판(??)에서 윈도우 라이브러리를 사용하기가 쉽지 않은데, 그래서 템플릿으로 사용할 수 있는 프로젝트를 올려놓았다. 26 윈도우 라이브러리(Window Library) 사용을 위한 프로젝트(Project) 만들기에서 프로젝트 파일을 찾을 수 있다.</div>
  4. <div class="subnote">아무것도 없는 허허벌판(??)에서 윈도우 라이브러리를 사용하기가 쉽지 않은데, 그래서 템플릿으로 사용할 수 있는 프로젝트를 올려놓았다. 26 윈도우 라이브러리(Window Library) 사용을 위한 프로젝트(Project) 만들기에서 프로젝트 파일을 찾을 수 있다.</div>
  5. <p> NDS에 윈도우 라이브러리가 구현되어있으므로(물론 내가 만들었다. 자세한 내용은 02 NDS 윈도우 시스템(Windows System)을 참고하자) 위에서 설명한 알고리즘 테스트 프로그램의 소스를 크게 수정없이 사용할 수 있다. 차이라면 개인적인 취향 때문에 함수 몇개가 덜 구현되거나 스타일이 조금 다르다는 정도...?</p>
  6. <p> 포팅에 대한 내용은 크게 다루지 않을 것이며 궁금한 사람은 Diff 프로그램으로 위의 테스트 프로그램과 NDS로 포팅된 소스의 내용을 비교해 보면 알 수 있을 것이다. 메인 소스는 거의 바뀌지 않았음을 알 수 있다. 이 얼마나 행복한 일인가... ㅜ_ㅜ </p> 
  7. </body> 
  8. </html> 

 

  1. body *
    {
        font-family : "돋움";
        zoom : 1;
    }
  2. h1
    {
        color : #FFFFFF;
        font-family : "굴림";
        font-size : 1.5em;
        background-color : #000000;
        margin : 20px 0px;
        padding : 10px;
        overflow : hidden;
    }
  3. p
    {
        margin : 5px 20px 5px 20px;
        padding : 0px 0px 0px 0px;
        font-size : 1em;
        color : black;
        line-height : 1.5em;
    }
  4. .subnote
    {
        border : 3px dashed #777777;
        margin : 5px 20px 5px 20px;
        padding : 5px;
        line-height : 1.5em;

 위를 익스플로러로 보면 아래와 같이 표시된다.

float1.PNG

<float 설정 이전>

 

 이제 float 속성을 넣어보자. subnote의 속성을 아래와 같이 float와 width를 추가한 뒤 확인하자.

  1. .subnote
    {
        border : 3px dashed #777777;
        margin : 5px 20px 5px 20px;
        padding : 5px;
        line-height : 1.5em;
        float : right;
        width : 200px;

 

 웹페이지를 확인하면 아래와 같이 div가 좌측으로 이동하고 글이 주위를 감싸는 형태로 표시된다.

float2.PNG

<float 후>

 

 이제 두개의 float element가 같이 나열되는 것이 아니라 순서대로 아래에 위치하도록 해보자. clear: both; 속성을 .subnote에 추가하면 끝이다.

  1. .subnote
    {
        border : 3px dashed #777777;
        margin : 5px 20px 5px 20px;
        padding : 5px;
        line-height : 1.5em;
        float : right;
        width : 200px;
        clear : both;

 화면을 표시해보면 아래와 같이 나온다.

float3.PNG

<clear 사용 후>

 

 float element의 경우 다른 속성들을 위에 표시되기 때문에 뒤에 있는 element가 그대로 표시되어 보기 싫게 되는 경우가 있다. 그런 경우 float element에의해 가려지는 element의 속성에 overflow : hidden; 속성을 추가해주면 된다. 익스플로러 6 이전 버전의 경우 그래도 잘 되지 않는 경우가 있는데 이때는 zoom: 1; 속성을 body에 추가해 주면 된다.

  1. body *
    {
        font-family : "돋움";
        zoom : 1;
    }

  2. h1
    {
        color : #FFFFFF;
        font-family : "굴림";
        font-size : 1.5em;
        background-color : #000000;
        margin : 20px 0px;
        padding : 10px;
        overflow : hidden;

 

 

6.참고

6.1 margin, border, padding 간의 관계

 간단히 설명하면 margin은 객체의 경계선 즉 border와 외부 객체 간의 여유공간을 설정하는 것이고 padding은 border 내부와 내부에 포함되는 Contents 간의 공간을 표시하는 것이다. left, right, top, bottom이 있으며 이것을 그림으로 표현하면 아래와 같이 나타낼 수 있다.

margin,padding,border.gif

<margin, border, content 간의 관계>

 

 

 

이 글은 스프링노트에서 작성되었습니다.

 좋은 이름을 지어야 하는 이유에 대한 글을 읽었습니다. 원문은 http://www.dancingmango.com/blog/2007/11/29/whats-in-a-name/ 에서 보실 수 있습니다. ^^;;;

 대충 내용을 읽어보니 구글 검색 기능 중에 "advanced search" 즉 "고급 검색" 기능을 전체 이용자의 1% 정도가 이용한다고 되어있는데, 이것을 "easy search" 또는 "better search"로 했으면 더 많은 사람들이 이용했을 것이고 더 나은 검색 결과를 얻었을 거라고 하는 군요.

 아래가 구글의 고급검색 버튼인데... 저도 한번도 써본적이 없습니다. ㅜ_ㅜ....
사용자 삽입 이미지

 실제로 어떻게 나오나 싶어서 클릭해 봤더니 약간 복잡한 화면이 나왔는데, 조금 신경써서 읽어보니 괜찮은 옵션들이 있습니다. or and 옵션들을 분리해서 항목으로 만들어놨네요. ^^
사용자 삽입 이미지

 저도 프로그램을 만들때 IT 용어 쪽으로 많이 쓰는 편인데, 일반 유저들을 생각한다면 잘못됬던 것 같습니다. 앞으로 이름을 지을 때 주의를 해야겠습니다. ^^

 양치질 하다가 문득 아이디어가 떠올라서 테스트 코드를 작성해 봤는데, 괜찮게 동작해서 팁으로 올립니다. ^^ (양치질 하다가 떠오르다니... 약간 문제가 있다고 생각되네요.. ㅡ_ㅡa.. 코딩을 좀 쉬어야 할지도...)

 아이디어는 간단합니다. 스프링노트에서 보낸 코드는 OL 태그와 함께 class 속성으로 code를 담고 있습니다. 즉 아래와 같이 되어있다는 것이지요. ^^

    <ol name=code>
    코드....
    </ol>


 이것을 자바 스크립트를 이용해서 class 속성은 cpp와 같은 언어 타입으로 바꿔 넣어주고, name 속성을 추가해주면 나머지는 Syntax Highlighter가 알아서 해줍니다. 물론 ol 태크가 먹도록 수정된 Syntax Highlighter가 있어야 한다는 전제가 있습니다. ^^;;;; 

shCore.js 파일을 수정하면 되는데 수정할 부분은 아래와 같습니다.
    FindTagsByName(elements,name,'pre'); FindTagsByName(elements,name,'textarea'); FindTagsByName(elements,name,'ol'); // 추가

    //highlighter.Highlight(element[propertyName])); highlighter.Highlight(element[propertyName].replace( /
    /gi, '\n').replace(/<\/?[^>]+>/gi, '')); // 이렇게 수정
(첨부 파일로도 올려놨습니다. ^^;;;)

    <!-- kkamagui 추가 Syntax Highliter -->
    <script class="javascript">
    <!-- kkamagui 추가 Stringnote 지원 -->
    var tags = document.getElementsByTagName( 'ol' )
    for( var i = 0 ; i < tags.length; i++ )
    {
        if( tags[ i ].attributes['class'].value == 'code' )
        {
            // cpp로 일단 고정함
             tags[ i ].attributes['class'].value = 'cpp';
            tags[ i ].setAttribute( 'name', 'code' )
        }
    }
    </script>
     
 위 코드를 "관리자"->"스킨편집"->"HTML/CSS 편집"으로 가셔서 <script class="javascript" src="./images/shCore.js"> 앞에 붙여넣으시면 됩니다.
 
 스프링노트와 티스토리를 연동하는게 점점 편리해 지는군요. ^^ 티스토리 만세~!!!





 압축된 자바스크립트 소스를 예쁘게 복원시켜주는 사이트가 있네요. ^^ 안그래도 자바스크립트를 분석할일이 있었는데, 이것이 압축되어있어서 알아보기가 굉장히 힘들었습니다. ㅜ_ㅜ...


 위 사이트로 이동하면 아래와 같은 화면이 나옵니다. 위쪽의 에디트박스에 예쁘게 볼 소스코드를 붙여넣고 아래쪽의 "Beautify" 버튼을 누르면 코드가 예쁘게 변환되서 나옵니다.
사용자 삽입 이미지

압축된 자바스크립트 소스


사용자 삽입 이미지

예쁘게 수정된 자바스크립트 소스


 자바스크립트 소스 분석할때 아주 유용하게 쓸 수 있겠군요. ^^;;; 멋집니다. ^^)/~

 학교 과제때문에 DICOM에 대해서 공부하다가 찾은 링크입니다. 의료 정보쪽이라서 앞으로 다시 볼까 의심이 들지만 혹시나 해서 올립니다.


 정말 깔끔하게 잘 정리되어있군요. ^^)/~

얼마전부터 구글 문법 하일라이터(Syntax Highlighter)를 티스토리에 적용해서 사용하고 있습니다. Syntax Highlighter에 대한 내용은 http://kkamagui.tistory.com/notice/28 에서 볼 수 있습니다. 이것을 사용하면 코드가 예쁘게 나오는 것은 물론이고 붙여넣기 및 출력도 지원하기때문에 상당히 편리한데, 문제가 하나 있습니다.

티스토리만 사용한다면 큰 문제가 안되겠지만 저같이 스프링노트와 티스토리를 같이 사용하는 사람에게는 거의 무용지물입니다. 개발하면서 주로 로그를 남기고 코드를 붙여넣는 것은 티스토리가 아니라 스프링노트쪽이고, 티스토리는 개발이 완료되었을 때 스프링노트의 보내기 기능을 써서 포스팅합니다.

이렇게 되면 스프링노트가 코드를 보낼 때 아래와 같이 OL 태그를 써서 보내게 되는데, 그 안에는 각종 HTML 태그들과 함께 인코딩된 형태로 코드가 뒤섞여있습니다.

<OL class=code>  
<LI>&lt;textarea name="code" class="cpp" cols="60" rows="10"&gt;<br />... some code here ...<br />&lt;/textarea&gt;<br /></LI></OL>

Syntax Highlighter를 사용하려면 TEXTAREA 태그나 PRE 태그를 사용해야하는데, OL 태그를 단순히 TEXTAREA 또는 PRE 태그로 교체하면 HTML 코드와 실제 내용이 어우러지는 아주 아름다운 코드를 보게 됩니다. ㅡ_ㅡ;;;;;;

그래서 어제부터 Syntax Highlighter의 소스를 고쳐보려고 자바스크립트를 공부하기 시작했는데, 너무 코드가 어려워서 포기했다가 강규영 님의 도움을 받아 해결했습니다(강규영님께 감사드립니다. ^^).

수정할 부분은 크게 두가지인데, 한가지는 shCore.js 파일을 수정하는 것입니다. shCore.js 파일의 내용중에 아래 부분을 간단히 수정한 뒤, "관리"의 "HTML/CSS 소스보기"로 가서 수정된 shCore.js 파일을 올리기만 하면 됩니다.

 ... 생략 ...

 // 기존 코드
 FindTagsByName(elements, name, 'pre');
 FindTagsByName(elements, name, 'textarea');

 // kkamagui 추가, 아래 부분을 추가해 줍니다.
 FindTagsByName(elements, name, 'ol');

 ... 생략 ...

 // 기존 코드
 //highlighter.Highlight(element\[propertyName\]);
 // 수정된 코드
 highlighter.Highlight(element\[propertyName\].replace( /<br>/gi, '\\n').replace(/<\\/?\[^>\]+>/gi, ''));
 ... 생략 ...

위의 코드가 나오는 부분은 한군데 밖에 없으니 원본 파일은 백업하시고 과감히 수정하시면 됩니다.
이제 남은 것은 스프링노트에서 보낸 글을 약간 손보는 것입니다. 스프링노트에서 보낸 글을 선택하여 수정모드로 갑니다. 수정모드에서 아래에서 보는 것과 같이 좌측 상단에 있는 "EDIT" 버튼을 눌러서 HTML 편집 모드로 변경합니다.

사용자 삽입 이미지
HTML 수정 모드로 변경

그후 "OL class=code" 를 찾아서 "OL name=code class=cpp" 와 같은 형식으로 수정합니다.

사용자 삽입 이미지
수정 전
사용자 삽입 이미지
수정 후

그리고 저장 버튼을 누른 후 해당 페이지로 이동해서 Control + F5를 눌러 캐쉬된 내용과 관계없이 화면을 갱신하면 아래와 같이 Syntax Highlight가 적용된 코드를 볼 수 있습니다. ^^

사용자 삽입 이미지
적용된 화면

수정한 shCore.js 파일을 첨부해 놓았으니 필요하신 분은 다운 받아서 바로 적용하시면 됩니다. 문제를 해결할 수 있게 도움을 주신 강규영 님께 거듭 감사드립니다. ^ㅡ^)/~

ps) 아래는 shCore.js 파일입니다.

 파이썬을 공부하고 싶으시다면 http://www.diveintopython.org/ 사이트를 한번 들려보세요. 책 Dive Into Python 의 내용을 PDF 및 각가지 포맷으로 무료 제공하고 있으며, 소스코드까지 주는군요. ^ㅡ^)/~

 후배가 발견한 사이트인데, 어디서 이런 사이트를 찾는지 모르겠군요(그놈 참 능력 좋네~ ㅎㅎ). 세컨트 프로그래밍 언어로 파이썬을 쓰시는 분이 많을꺼라 생각하는데, 특히 C/C++을 쓰시는 분들이라면 더욱 그럴꺼라 생각합니다.
 
 제 개인적인 소견으로 무척이나 C/C++에 가깝더군요. 그러면서도 유연하고 C의 라이브러리를 그대로 당겨쓸 수 있는 것이 아주 매력적인 언어였습니다. 물론 GUI 프로그래밍에는 좀 많이 약했지만... ^^;;; 텍스트 처리에는 굉장한 능력을 가진듯 보였습니다.

 한참 파이썬 프로그래밍을 하다, 새로운 NDS 홈브루를 개발하다보니 다시 C/C++로 돌아왔네요. 어느정도 정리되고나면 파이썬 공부를 다시 해야겠습니다. ^^
 제 블로그는 http://code.google.com/p/syntaxhighlighter/ 에서 제공하는 Syntax Highlighter를 사용하고 있습니다. 페이지 로딩 속도가 조금 느리다는 단점이 있지만 코드를 예쁘게 보여줄 수 있다는 장점때문에 사용하고 있는데요, 한가지 아쉬운 점은 스프링노트에서 보낸 코드가 적용이 안된다는 점입니다.

 이참에 한번 적용해보고 싶어서 자바 스크립트 책을 한권 옆에 끼고, 차근 차근 분석을 시작했는데 쉽지 않더군요. 일단 스프링노트에서 보낸 코드를 티스토리로 보내서 소스보기를 하니 아래와 같이 코드가 나왔습니다.

<OL class=code>
<LI>&lt;textarea name="code" class="cpp" cols="60" rows="10"&gt;<br />... some code here ...<br />&lt;/textarea&gt;<br /></LI></OL>


일단 < 기호와 > 기호가 인코딩 되어있고 OL 태그로 둘러싸져있더군요. 갑자기 든 생각이 자바스크립트를 이용해서 위 태그를 Syntax Highlighter에서 인식할 수 있는 <textarea> 태그로 바꿔주면 간단히 해결할 수 있을 듯 싶어서 살짝 바꿔봤더니 뒤에 <br/>가 그대로 출력되더군요. ㅜ_ㅜ..

 결국 하려면 인코딩된 태그를 다 살려주고 <br/> 같은 것은 개행문자로 바꿔주고 등등의 일을 해야할 듯한데... 자바 스크립트는 오늘부터 본지라 중도 포기... ㅜ_ㅜ...

 스프링노트에 플러그인이 나올때까지 기다리던가 해야겠군요. ㅜ_ㅜ... 흑흑... 역시 프로그래밍은 쉽지 않은 것 같습니다.
 인터넷을 뒤지다가 상당히 재미있는 글을 발견했습니다. 제목은 완벽한 콘솔 폰트였는데, 보니 자기가 쓰고있는 폰트가 콘솔에 아주 좋다는 내용이더군요. http://duncandavidson.com/archives/654 에서 원문을 보실 수 있습니다.

 무슨 폰트인가 봤더니 Bitstream Vera 폰트라고 하더군요. 폰트는 http://www.gnome.org/fonts/ 에서 다운 받으실 수 있고 폰트 파일을 받아서 압축을 풀면 ttf 폰트들이 생깁니다. 이 파일들을 제어판을 열어서 글꼴을 클릭하시고 글꼴 목록이 나오면 다 붙여 넣으시면 설치가 끝납니다.

 제가 주로쓰는 폰트는 Lucida console 폰트인데, 글자가 멋지게 보입니다. ^^ 아래를 한번 보시죠.
사용자 삽입 이미지

lucida console 폰트

 
 소문자 L과 대문자 I의 구분이 쉽고 늘씬해 보여서 주로 쓰는 폰트입니다. 그런데 여기에 도전장을 던지는 폰트가 나왔으니 Bitstream Vera Sans Mono Bold 폰트가 그것입니다. ^^ 아래가 그 폰트를 적용한 코드인데, Lucida와 한번 비교해보시면 비슷하게 늘씬하면서도 문자들의 구분이 쉬운걸 알 수 있습니다.
사용자 삽입 이미지

Bitstream Vera Sans Mono Bold


 멋지지 않습니까? 단점이라면 약간 굵어 보인다는 것인데, 적응하면 괜찮을 듯 합니다. ^^ 앞으로 폰트는 이걸로 다 바꿔야겠습니다.

 멋진 폰트를 발견하게 되서 아주 행복하군요. (프로그래머에겐 더할 나위 없이 좋은 폰트인 것 같습니다. ^ㅡ^)
 ACM 대회 준비를 위해 4문제 정도를 골라 풀었습니다만, 테스트를 위해 올렸을 때 Accept는 하나밖에 못받았습니다. ㅜ_ㅜ.. 뭐가 문제가 있던 것인지.... 대회는 끝났지만 그래도 푼 김에 소스를 한번 올려봅니다. 하드에 썩히기에는 왠지 아까워서 ^^;;;
 
 그렇다고 풀이가 상당이 완성도가 높거나 멋지거나 하진 않습니다. Accept가 안된걸 보면 무슨 문제가 있거나 오답인 것이겠지요 ^^;;;그러고 보니 올리기가 좀 부끄럽군요. (* ㅡ_ㅡ*)

 ACM 문제 데이터베이스는 http://icpcres.ecs.baylor.edu/onlinejudge/index.php 사이트에서 보실 수 있습니다. 그럼 아래에 코드 나갑니다. ^^;;;;

* 100번 문제에 대한 코드 보기
* 121번 문제에 대한 코드 보기
*151번 문제에 대한 코드 보기
* 821번 문제에 대한 코드 보기

+ Recent posts