Skip to main content

CodeHighlighter plugin test page.

This post is for testing CodeHighlighter plugin which uses GeSHi as a fontifier engine. ((Those code blocks are acquired from Google Code Search.)) ((For more supported languages, go CodeHighlighter plugin or GeSHi homepage.))



  1. C++ (<pre lang="cpp" lineno="1">)

    class nsScannerBufferList
    {
    public:
    /**
    * Buffer objects are directly followed by a data segment. The start
    * of the data segment is determined by increment the |this| pointer
    * by 1 unit.
    */
    class Buffer : public PRCList
    {
    public:
    Buffer() {
    ++index_;
    }



  2. PHP (<pre lang="php" lineno="4">)

    for ($i = 0; $i < strlen( $utf8_string ); $i++ ) {

    $value = ord( $utf8_string[ $i ] );

    if ( $value < 128 ) {
    // ASCII
    $unicode .= chr($value);
    } else {
    if ( count( $values ) == 0 ) {
    $num_octets = ( $value < 224 ) ? 2 : 3;
    }
    $values[] = $value;



  3. Lisp (<pre lang="lisp">)

    ;;; Assignment
    (define-caller-pattern setq ((:star var form)) :lisp)
    (define-caller-pattern psetq ((:star var form)) :lisp)



  4. Python (<pre lang="python">)

    def Print(file):
    """Print a file thru the finder. Specify file by name or fsspec"""
    finder = _getfinder()
    fss = Carbon.File.FSSpec(file)
    return finder._print(fss)



  5. Ruby (<pre lang="ruby">)

    class AbstructNotifier
    def initialize(prefix, base_notifier)
    @prefix = prefix
    @base_notifier = base_notifier
    end

    attr_reader :prefix

    def notify?
    true
    end



  6. Perl (<pre lang="perl">)

    my ($class, $mail, $orig) = @_;
    my $new_list = $class->_detect($orig) or return;
    $new_list->add_to_posts({mail => $mail->id})
    unless Email::Store::List::Post->search( mail => $mail->id,
    list => $new_list->id
    );



  7. Java (<pre lang="java">)

    /**
    * Creates a new model list that is a member of some enclosing list.
    * @param binary_operator An operator with that this list is connected
    * with other members of the enclosing list.
    * @param unary_operator The unary operator for this list.
    * @param a_nodes The nodes inside this list.
    */
    public list(char binary_operator, char unary_operator, node[] a_nodes)
    {
    super(binary_operator, unary_operator, a_nodes);
    nodes = a_nodes;
    }



  8. Diff (<pre lang="diff">)

    5,6c5,7
    < AC_INIT(FULL-PACKAGE-NAME, VERSION, BUG-REPORT-ADDRESS)
    < AC_CONFIG_SRCDIR([include/hello.h])
    ---
    > AC_INIT(hello, [1.0], [your@email.com])
    > AC_CONFIG_SRCDIR([src/hello.cpp])
    > AC_CONFIG_AUX_DIR(config)
    8a10,11
    > AM_INIT_AUTOMAKE(hello, [1.0])
    >



  9. HTML (<pre lang="html4strict">)








    Memory Carrier






    pre tag test.
    < /pre>



  10. CSS (<pre lang="css" lineno="4">)

    pre {
    border: 1px solid #ccc; padding: 0em 0.5em;

    /* Browser specific (not valid) styles to make preformatted text wrap */
    white-space: pre-wrap; /* css-3 */
    white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
    white-space: -pre-wrap; /* Opera 4-6 */
    white-space: -o-pre-wrap; /* Opera 7 */
    word-wrap: break-word; /* Internet Explorer 5.5+ */
    }

    .strike {
    text-decoration: line-through;
    }



  11. Bash (<pre lang="bash">)

    echo << EOF
    echo << EOF



Comments

  1. thanks for the great plugin :p. it works like a charm.
    it's very helpfull for a newbie like me.

    ReplyDelete
  2. Thank you for using this plugin. :-)

    ReplyDelete
  3. I have a problem with code font on my blog. It is very small. How do I fix this problem?

    ReplyDelete
  4. This plugin don't support pretty configuration page for styles, now. :-| So if you want to change the styles of your code, you have to add some lines to codehighlighter.php by yourself.

    For example, if you want to change the style of one line comment to italic font, you can do this with the following line. The line should be located before the 'return $geshi->parse_code();'.

    $geshi->set_comments_style(1, 'font-style: italic;', true);

    You can find more information about these in the http://qbnz.com/highlighter/geshi-doc.html#changing-styles. I'm sorry for your inconvenience.

    ReplyDelete
  5. 안녕하세요.
    본 플러그인을 설치 후 테스트를 해 보았는데..

    php나 c 코드의 경우 lineno를 입력해도 좌측에 숫자가 안보이는데 혹시 제 방법이 잘못된 것인지요...

    ReplyDelete
  6. 이 페이지에 보이는 예제들이 같은 플러그인을 사용중이라 일단 제 환경에선 제대로 동작하고 있는 것 같습니다. 물론 설치하고 Activate는 하셨겠죠? :-) lineno 뒤에 반드시 첫번째 라인 번호가 쌍 따옴표 안에 들어 있어야 합니다. 위의 예제처럼요. 그리고 이 플러그인은 댓글에선 동작하지 않도록 되어 있습니다.

    위의 경우가 모두 아니라면 다른 플러그인과 충돌이 나는 상황일지도 모르겠습니다. 그런데 아직 한번도 다른 플러그인과 충돌난다는 문제는 없었기 때문에 정확하진 않습니다. 좀 더 자세한 정보를 주시면 도움이 되겠습니다. (해당 화면의 소스를 메일로 보내주시거나, 사용중이신 플러그인들을 알려주세요.)

    참, 해당 코드안에 pre 태그가 있는 경우 닫는 pre 태그의 <와 /pre 사이에 공백을 하나 넣어주셔야 합니다.

    ReplyDelete
  7. [pre lang="css" lineno="4"]
    pre {
    margin: .5em 0 2.1em 0;
    padding: 1em;
    }
    pre:hover {
    background-color: #c9c7bc;
    }
    .strike {
    text-decoration: line-through;
    }
    [/pre]

    출력되지 않기에. 수정해봅니다.

    ReplyDelete
  8. pre:hover {
    background-color: #c9c7bc;
    }
    .strike {
    text-decoration: line-through;
    }



    이런식으로 해봤는데 컬러 코드는 출력이 되나 좌측부분의 숫자가 나오지 않습니다.
    물론 플러그인을 다 꺼보기도 했구요..

    ReplyDelete
  9. 흠... 위 예제의 마지막에 똑같이 넣어 봤는데 잘 되네요.
    하나 의심스러운게 있는데요, 혹시 사용하고 계신 테마에서 ol - li 태그의 스타일이 무엇인지 확인해 주세요. 이 문제인지 쉽게 확인하시려면 기본 테마로 바꾸고 줄번호가 보이는지 보시면 됩니다.

    그럼 확인 부탁드릴께요. :-)

    ReplyDelete
  10. ol, li의 문제였습니다. 현재 테마에서는 수정불가능 할 것 같고..
    플러그인에 id를 추가하면 될듯합니다.

    답변 감사드리고, 좋은하루되세요 (__

    ReplyDelete
  11. Im having a problem with css highlighting. See the url http://br19.dialhost.com.br/~alexandr/blog/ and note that code of javascript works fine, but the css mess the layout and float to right.

    Here ther is the code put at the post that makes the problem:



    #body {

    background-color: red;
    color: black;
    border: 1px solid green;

    }

    Whats wrong?????

    ReplyDelete
  12. Alexandre, it seems to be OK. Did you fix the problem by yourself?

    ReplyDelete
  13. Thanks iwongu, I fix the problem. This problem happen because Wordpress change de location of the attribute lineno to before the attribute lang. This way, the plugin doesnt work. Each save of post the WP make this, I don´t know why, but all the time I have to put the attributes in the right location...

    Great plugin, I tested a lot and this is the best. My blog its about Jquery, so I have to post all the time some code, like CSS, HMTL and Javascript, and with this plugin, this job its so much easer..

    Did you think about put the support for Jquery, I can help you if you wish...

    ReplyDelete
  14. Hm... I had no such problem. I think WP did not change the location of attributes of <pre> tag. Anyway thank you for using this plugin well and your future help. :-)

    ReplyDelete
  15. Works like a charm but one doubt, I am assuming nothing can be done about lines crossing the box but can I reduce the size of the font ? for example check http://www.thecredence.com/programming-with-wxwidgets/ - The size of code font is too big. How to reduce it ?

    ReplyDelete
  16. Your page looks good. I think you found the solution. You can change font size with css's <pre> tag.

    One solution of line crossing problem is showd in CSS section of this page. (only in <pre> tag part) But this is not perfect one. :-|

    ReplyDelete
  17. Hi...

    Somehow I am not able to get this to work...
    I just did basic install of WP and intalled this plugin, activated it and I have no idea why it is not working...

    http://blog.flashvacuum.com/?p=3

    I am using my script blah blah to test that page...

    Can you help me figure this out???

    Thanks...

    Jason

    ReplyDelete
  18. Oopes... I guess the pre tag has gotten zapped...

    I am using it like this...

    [pre language="actionscript" lineno="1"]
    #include "hello.as"

    for (var i:Number = 0 ; i

    ReplyDelete
  19. Use "lang" instead of "language." I added your ActionScript code to the this test page. :-)

    ReplyDelete
  20. Ah... That was really dumb... My bad... Appreciate your help... :)

    Jason

    ReplyDelete
  21. Hi... :)

    I see some oddities with copy & paste...

    For example, copy the code from the CSS example up there... Try that in FF and IE...
    FF adds # in the line break, but IE loses the line breaks which makes it one liner...

    Do you know if there is any way to fix this???

    Thanks... :)

    Jason

    ReplyDelete
  22. If we use "lineno" feature, it uses <ol> tag in <pre> tag to display line numbers. But the behavior of FF is different from IE's in "copying" text from html. And both are not good for copying source code. :-(

    If you have to supply your source code, it's better to make a link to download your source code, I think.

    ReplyDelete
  23. #include
    #include

    int main()
    {
    return 0;
    }

    ReplyDelete
  24. I use the plugin, but I find that the will be convert to < and >.
    How to change it?
    You can find it here:
    http://www.livebaby.net/exp/?p=17

    ReplyDelete
  25. Hi, mantou.

    I think that the problem is caused by one of your plugins. To see the '&lt;', the html have to have '&amp;lt;'. And it means, before CodeHighlighter handles your code, the one of other plugins already changes '<' to '&lt;'.

    Deactivate your post-formatting related plugins one by one, and see the codes in your post. If you have any question or problem, let me know. Thanks for using this plugin. :-)

    ReplyDelete
  26. Hi, iwongu.

    I use 4 plugins: Akismet, All in One SEO Pack, WP-PageNavi and CodeHighlighter.
    I deactivated the other 3 plugins, but there is no change.
    My wp version is 2.2.2.

    ReplyDelete
  27. I updated the upper PHP example with your codes. As you can see, there is no problem to display <.

    Lastly, If you write your post with the visual editor, the characters can be converted by it and saved to DB. Please try to use raw editor and see the result.

    (My WordPress version is 2.3, now. But there was no problem even when I used 2.2.x versions.)

    ReplyDelete
  28. I change the source:
    $x = $geshi->parse_code();
    to
    $x = $geshi->parse_code();
    $x = preg_replace(array('#&lt;#si', '#&gt;#si'), array('<', '>'), $x);
    return $x;

    It work well.SO faint.

    ReplyDelete
  29. [...] CodeHighlighter plugin test page Download Now [...]

    ReplyDelete
  30. Hi, anyone have the CSS code to stylize the code blocks, because my current theme is XHTML but your own CSS do the code appear like this:

    Line X
    Code of Line X
    Line Y
    Code of Line Y

    And, maybe an offtopic, anyone knows a professional free theme. Beautiful but sober o.O

    Thanks

    ReplyDelete
  31. Thanks a lot for this plugin!
    It works well on my website!

    ReplyDelete
  32. hi ;)

    thanks for this plug in :D D:

    can you up grade to 2.3.0 ? :$ $:

    ReplyDelete
  33. [...] Prettify (examples). The second plugin which looked promising was WordPress:CodeHighlighterPlugin (examples), which was a wrapper around GeSHi. Let's find out what they do, and how they do [...]

    ReplyDelete
  34. class Foob extends Object {

    }

    ReplyDelete
  35. [...] Sample Link:   http://ideathinking.com/blog-v2/?p=13 [...]

    ReplyDelete
  36. Awesome plugin! Just installed it and used it for a post on my blog. Thanks a bunch!

    ReplyDelete
  37. Hi!

    I have a problem when I want to post php code. The plug-in always creates a space between < and ? of <?php

    Any ideas how to solve this?

    ReplyDelete
  38. Hi Nick,
    I put the same code in this post as you see now. But it didn't have any problem. It can have some problem if you're using visual editor. It can modified the code before this plugin can handle it.

    ReplyDelete
  39. Hi!

    This is strange, because I'm not using the visual editor.

    ReplyDelete
  40. I modified java5.php to java6.php. The only changes I made were to the string identifier and the links to the Javadoc. Lines 53 and 54 look like this:

    $jdk='http://java.sun.com/javase/6/docs/api';
    $jdk='http://java.sun.com/j2se/1.5.0/docs/api';

    Here is a sample link (lines 848-1008):

    48 => "$jdk/java/util/concurrent/atomic/{FNAME}.html",

    Line 53 is what I really want, but the link comes out weird. I'm using line 54 right now until someone figures this problem out.

    ReplyDelete
  41. Oh, yes, the file is temporarily available at http://www.mslinn.com/java6.php.txt

    ReplyDelete
  42. Hi iwongu how are you.

    Thanks for the great plugin man, your a life saver :).

    I am having that problem as well, with the <?php tags and such. I use the 'Code' view of the editor and yet it still converts it using htmlentities.

    I know the problem is becuase the editor changes the content before the plugin actually gets the chance to use it but I was wondering. What file is the WP editor located in? I'd like to change this, I'm pretty new to WordPress so I'm still learning its code base :).

    -Thanks again.

    P.S: Your site template is hot :)

    ReplyDelete
  43. Hi Navid,

    To avoid the character converting problems, I put two lines into my plugin code.

    62 remove_filter('the_content', 'wptexturize');
    63 remove_filter('the_content', 'convert_chars');

    But for your case, it seemed not working. I think that there can be other plugin that add these filters again.

    Thanks for using this plugin. :)

    ReplyDelete
  44. some actionscript 3 highlight has already been made by someone or should i make it myself?

    ReplyDelete
  45. Hi Valentino,

    GeSHi already support actionscript language. Is there any big syntax difference between versions? If not, you can use lang="actionscript" in your pre tag.

    ReplyDelete
  46. Hey, any plans to support Groovy? Nice plugin!

    ReplyDelete
  47. Hi Mark,
    I have just upgraded the GeSHi version that this plugin is using. Now, it supports Groovy!!

    Thanks for using this plugin. :)

    ReplyDelete
  48. If you could get it to work in comments, that would be even better. Maybe you should try changing the tag, too, so that users don't have to alter the existing tags in their code. Good work, though.

    ReplyDelete
  49. Hi Jason,
    In fact, I thought about that. But I didn't do it because it required that users should know about the tag.

    ReplyDelete
  50. May be it's just me...but I can't seem to get it work. I am using your plugin with the current WordPress MU release, and it seems that no matter whether the visual editor is used or not, the pre-tags are -stripped- of their attributes upon saving.
    Any idea, what that might be? Have I missed something from the installation description?

    - Volkmar

    ReplyDelete
  51. Ah, I just found the solution. WPMU strips attributes off tags for security reasons. This renders plugins like codehighlighter quite unusable. I have patched my version of codehighlighter.php a bit, and now it works perfectly well with WPMU:

    I changed line 57 from
    $pattern = '/((\\n|.)*)/U';

    to

    $pattern = '/\[(\s*lang="([^"]*)")?(\s*lineno="([^"]*)")?\]((\\n|.)*)/U';

    With the result that you have to use it as follows:
    [lang="lang" lineno="1"]
    your code...


    This works perfectly well.

    -Volkmar

    ReplyDelete
  52. Hm...ok, this comment-functionality does not transform < and > as I thought it would...what I wrote before should have looked like this:

    I changed line 57 from
    $pattern =
    '/<pre(\s*lang="([^"]*)")?(\s*lineno="([^"]*)")?>((\\n|.)*)<\/pre>/U';
    to

    $pattern = ‘/<pre>\[(\s*lang=”([^”]*)”)?(\s*lineno=”([^”]*)”)?\]^gt;((\\n|.)*)<\/pre>/U’;

    With the result that you have to use it as follows:
    <pre>[lang=”lang” lineno=”1″]
    your code…
    /</pre>

    ReplyDelete
  53. Thanks for the solution. In fact I haven't used WPMU so that I couldn't test on it. Sorry~ ;)

    ReplyDelete
  54. Hey, no problem. It took me a moment or two to figure out what it the problem really was, and how to solve it. May be you can implement it for good. I will write entry with this solution into my own blog as well, so people will definitely find it, no matter if it is implemented or needs to be patched.

    As others did before me, I have to thank you for the plugin. It works really well, especially after the patch ;)

    -Volkmar

    ReplyDelete
  55. I've been tested many script of 'highlight codes', and I've a similar problem with your script, I found the same problem on CodeColorer script.

    Error/problem:

    Fatal error: Cannot redeclare class GeSHi in /home/accountname/public_html/home/wp-content/plugins/code-highlighter/geshi.php on line 158

    Is it normal?

    ReplyDelete
  56. I think that CodeColorer also uses GeSHi. Is it possible to deactivate one of them in the plugins management page?

    ReplyDelete
  57. I made a copy mods to this plug-in to allow fetching of URL to get the source. You can now also style the code container. See http://www.ryancloke.com/codehighlighter-enhancements/ for more

    ReplyDelete
  58. hello,

    I'm having a few problems, if i enter the code



    and switch to or from the HTML view or Visual view the code disappears?

    any help would be appreciated.

    chris

    ReplyDelete
  59. Hi Chris,
    You'd better use HTML view to use this plugin. I didn't test this plugin with Visual view.
    I'm sorry about that. :-(

    ReplyDelete
  60. thanks for the response, i'll stick to using the html view from now on.

    ReplyDelete
  61. [...] da automatisk fargekoding av koden slik at det er mye lettere å lese og forstå, slik som vist på denne og denne [...]

    ReplyDelete
  62. Hello again,

    While using the plugin with WordPress MU 1.3.3, I stumbled across another problem: double-converted html-entities. WPMU does this already, and since GeSHi does it, too, entities get converted where no one wants it. Again, I have written a little patch that helps disabling the conversion within GeSHi. This bears a certain risk, I admit that, but within WPMU, it should be safe, since WPMU converts the entities upon saving the text into the database, and thus long before GeSHi gets it.

    Here is the link to my blog-post describing the problem and providing the patch:
    http://blog.nifelheim.info/tech/2008/05/05/codehighlighter-for-wordpress-mu-2/

    ReplyDelete
  63. [...] C# code as well as XAML code (Windows Presentation Foundation) on the site. I found a plugin called Code Highlighter, that helps. I just found the default formatting for my theme's website lacking, so I borrowed from [...]

    ReplyDelete
  64. So odd. I can't get my line numbers to show up even when using lineno="1" in my pre tag. I'm on WP 2.6 and CH 1.8. Any ideas?

    ReplyDelete
  65. Interestingly, when I paste the html generated from my blog into the html of yours it works, so it must have something to do with the stylesheet...

    ReplyDelete
  66. Got it figured out. note that the li in the ol must have display:list-item or line numbers dont work. inline or block breaks it.

    ReplyDelete
  67. Hi,

    Please change the pattern to:

    $pattern = '/(.*?)/s';


    It's equivalent to the pattern you use, but it can handle bigger codes.

    I got some "Internal Server Errors" with the current pattern when highlighting some bigger codes. Changing to the pattern above solved the problem.

    ReplyDelete
  68. Trying to post again the pattern:

    $pattern = '/<pre(\s*lang="([^"]*)")?(\s*lineno="([^"]*)")?>(.*?)<\/pre>/s';

    ReplyDelete
  69. Looks great !

    One question. Why aren't the long code lines wrapping ? If you see your HTML ( #9 ) and CSS ( #10 ) examples, the code is spilling out of the box within which it should be wrapping ?

    Thanks

    ReplyDelete
  70. It's just because it was very difficult to find the way to make the line wrapping for all browsers. :-)
    I tried to apply some styles to the pre tag but none worked correctly for all.

    ReplyDelete
  71. Great plugin, we are using in on our intranet documentation db website (so I cannot link it). Every blogging programmer will love it!

    ReplyDelete
  72. Hi,

    We are having trouble with the plugin in that when I save my post or page, the pre tag reverts back to just pre.

    So I can enter and after saving it then becomes just

    We would really like to use this plugin as posting code is going to play a large part of our blog and I would love to get it working.

    Would you be so kind as to contact me so we can work through this?

    thank you.

    ReplyDelete
  73. This plugin doesnt work for me. Other plugin too. I wrote php codes and when i previewed my page, the list tag is converted and its floated to the right. Weird.....

    ReplyDelete
  74. Hedley and Buzzlair, I'm sorry for inconvenience. If you can give more information, it'll be helpful to help you.

    FYI, this plugin does not get along with visual editor. Please turn it off in the profile setting page if you are using it.

    ReplyDelete
  75. #
    One question. Why aren’t the long code lines wrapping ? If you see your HTML ( #9 ) and CSS ( #10 ) examples, the code is spilling out of the box within which it should be wrapping ?

    Thanks
    #

    iwongu said
    am September 9 2008 @ 8:12

    It’s just because it was very difficult to find the way to make the line wrapping for all browsers. :-)
    I tried to apply some styles to the pre tag but none worked correctly for all.

    --

    Did you try

    pre {
    border: 1px solid #ccc;
    padding: 0em 0.5em;
    font-size: small;
    overflow:hidden;
    overflow:auto;
    overflow:scroll;
    }

    in the CSS? .-)

    ReplyDelete
  76. my highlighting is working. but my line numbers are not..
    what am i doing wrong?


    pre {
    margin: .5em 0 2.1em 0;
    padding: 1em;
    }
    pre:hover {
    background-color: #c9c7bc;
    }
    .strike {
    text-decoration: line-through;
    }

    ReplyDelete
  77. oops

    [pre lang="css" lineno="4"]
    pre {
    margin: .5em 0 2.1em 0;
    padding: 1em;
    }
    pre:hover {
    background-color: #c9c7bc;
    }
    .strike {
    text-decoration: line-through;
    }
    [/pre]

    ReplyDelete
  78. If you have a problem in displaying line numbers, you should check the style of ol tag first because the line numbers are using the tag. :)

    ReplyDelete
  79. I'm not sure if this is a problem with the CodeHighligther plugin or wordpress editor but when I type something like "echo << EOF" it automatically inserts a space between the first < and the second.
    Is there any way to fix this ?

    ReplyDelete
  80. Hi Mihai, I tried to trigger your problem by myself, but failed. I added few lines of bash code in the 11th entry of this post. I didn't know exactly what you used, so I used both < and &lt;.
    But there was no space between them. :(

    ReplyDelete
  81. Thanks for the great plugin! If you have problems with the &, symbols I just posted a solution to my blog

    http://www.sealabs.net/seadog/2009/05/codehightlighter-wordpress-plugin-and-symbols

    enjoy

    ReplyDelete
  82. Hey I found this plugin very useful, and I've made an important change to it. You can read it here, http://tomorrowevening.com/blog/uncategorized/as3-code-highlighter/

    ReplyDelete
  83. http://www.neathighlighter.com is a very nice code highlighter which highlights code in standard colors and has the ability to highlight code which is mixture of different languages

    ReplyDelete
  84. #include
    using namespace std;

    int main ()
    {
    cout << "Hello World!";
    return 0;
    }

    ReplyDelete
  85. Are there any plans for adding Clojure support? Would it be something that could be added to "the List"?

    ReplyDelete
  86. Is there a way to stop Wordpress from removing the lineno="1" tag from Lineo when you jump back to and forth from Style/HTML view?

    ReplyDelete
  87. i am using wp2.3.3 and the plugin 1.7 or 1.8 does not display \n properly

    ReplyDelete

Post a Comment

Popular posts from this blog

1의 개수 세기 - 해답

벌써 어제 말한 내일이 되었는데 답을 주신 분이 아무도 없어서 좀 뻘쭘하네요. :-P 그리고 어제 문제에 O(1)이라고 적었는데 엄밀히 얘기하자면 O(log 10 n)이라고 적었어야 했네요. 죄송합니다. ... 문제를 잠시 생각해보면 1~n까지의 수들 중 1의 개수를 얻기 위해서는 해당 숫자 n의 각 자리의 1의 개수가 모두 몇개나 될지를 구해서 더하면 된다는 사실을 알 수 있습니다. 예를 들어 13이라는 수를 생각해 보면 1~13까지의 수에서 1의 자리에는 1이 모두 몇개나 되는지와 10의 자리에는 모두 몇개나 되는지를 구해 이 값을 더하면 됩니다. 먼저 1의 자리를 생각해 보면 1, 11의 두 개가 있으며 10의 자리의 경우, 10, 11, 12, 13의 네 개가 있습니다. 따라서 2+4=6이라는 값을 구할 수 있습니다. 이번엔 234라는 수에서 10의 자리를 예로 들어 살펴 보겠습니다. 1~234라는 수들 중 10의 자리에 1이 들어가는 수는 10, 11, ..., 19, 110, 111, ... 119, 210, 211, ..., 219들로 모두 30개가 있음을 알 수 있습니다. 이 규칙들을 보면 해당 자리수의 1의 개수를 구하는 공식을 만들 수 있습니다. 234의 10의 자리에 해당하는 1의 개수는 ((234/100)+1)*10이 됩니다. 여기서 +1은 해당 자리수의 수가 0이 아닌 경우에만 더해집니다. 예를 들어 204라면 ((204/100)+0)*10으로 30개가 아닌 20개가 됩니다. 이런 방식으로 234의 각 자리수의 1의 개수를 구하면 1의 자리에 해당하는 1의 개수는 ((234/10)+1)*1=24개가 되고 100의 자리에 해당하는 개수는 ((234/1000)+1)*100=100이 됩니다. 이들 세 수를 모두 합하면 24+30+100=154개가 됩니다. 한가지 추가로 생각해야 할 점은 제일 큰 자리의 수가 1인 경우 위의 공식이 아닌 다른 공식이 필요하다는 점입니다. 예를 들어 123에서 100의 자리에 해당하는 1의 개수는 ((123/1

std::map에 insert하기

얼마전 회사 동료가 refactoring한 코드를 열심히 revert하고 있어서 물어보니 다음과 같은 문제였습니다. 원래 코드와 refactoring한 코드는 다음과 같더군요. nvp[name] = value; // original code nvp.insert(make_pair(name, value)); // refactored 아시겠지만 위의 두 라인은 전혀 다른 기능을 하죠. C++03에 보면 각각 다음과 같이 설명되어 있습니다. 23.1.2/7 Associative containers a_uniq.insert(t): pair<iterator, bool> inserts t if and only if there is no element in the container with key equivalent to the key of t. The bool component of the returned pair indicates whether the insertion takes place and the iterator component of the pair points to the element with key equivalent to the key of t. 23.3.1.2/1 map element access [lib.map.access] T& operator[](const key_type& x); Returns: (*((insert(make_pair(x, T()))).first)).second. 원래 코드는 매번 새 값으로 이전 값을 overwrite했지만 새 코드는 이전에 키가 존재하면 새값으로 overwrite하지 않습니다. 따라서 원래 기능이 제대로 동작하지 않게 된것이죠. 그래서 물어봤죠. "왜 이렇게 했어?" "insert가 성능이 더 좋다 그래서 했지." :-? 사실 Fowler 아저씨는 Refactoring 책에서 refactoring은 성능을 optimizing하기 위한 것이 아니다라

C++ of the Day #9 - Boost.Python 사용하기 #1

Python 은 가장 인기있는 interpret 언어중의 하나입니다. Python의 장점 중 하나는 C/C++ 모듈과 쉽게 연동할 수 있다는 점입니다. 물론 손으로 일일히 wrapper를 만드는 것은 손이 많이 가고 에러를 만들수 있는 작업이나 SWIG 등과 같은 도구를 사용하면 쉽게 python 모듈을 만들 수 있습니다. Boost.Python 은 이런 SWIG와 같이 python 모듈을 쉽게 만들 수 있도록 도와주는 라이브러리로 순수 C++만을 사용한다는 점이 SWIG와 다른 점입니다. 그리고 개인적으로는 Boost 라이브러리에 포함되어 있는 것들이 왠지 좀 더 믿음직스러워서... :-) 이번 글에서는 Boost.Python 문서에 나와 있는 예제 를 가지고 간단하게 python 모듈을 만드는 방법에 대해서 알아보겠습니다. Requirements 리눅스 이 글에서는 리눅스 환경에서의 사용 방법을 설명한다. Boost.Python 라이브러리 (1.33.1) Boost 라이브러리를 다운로드받아 아래와 유사한 명령으로 라이브러리를 빌드한다. bjam -sTOOLS=gcc -with-python install bjam의 --prefix 옵션으로 라이브러리가 설치될 위치를 변경할 수 있다. Python 라이브러리 (2.4.3) Python을 다운로드 받아 빌드하여 설치한다. 위의 경우와 유사하게 configure의 --prefix 옵션으로 설치될 위치를 변경할 수 있다. Write C++ Code 다음과 같이 코드를 작성한다. // greet.cpp #include <stdexcept> char const* greet(unsigned x) { static char const* const msgs[] = { "hello", "Boost.Python", "world!" }; if (x > 2) throw std::range_error("