Ne v kontakte Asocial programmer's blog

Facets of simplicity

Feature image

Simplicity is complicated. In the Golang community, this statement is most often attributed to Rob Pike but it turns out a lot of people said something like that. A couple of weeks ago I encountered this yet again in a debate with a colleague (someone with lots of experience and whose opinion I respect a lot). Both of us considered ourselves advocates for simplicity, yet we were leaning towards radically different technical approaches. Both, of course, were sure that our own solution is much simpler than the other, and even had a good set of technical arguments to support that.

Without going into too many details, we needed a bunch of small business logic snippets executed ever so often against a certain dataset. The whole thing was supposed to be pretty small and simple (no high-load, out of the critical path, latency insensitive, etc.), so the main concern was to minimize maintenance and debugging effort. In this particular case, the language was Go, but frankly, this can be applied to any language.

FSEconomy noob: most profitable assignments?

Feature image

Not so long ago I've discovered FSEconomy, an economy meta-gate for flightsim fans. Despite of somewhat simplistic core mechanics and unfancy look, it has a very active community and a lot of depth to it. I've spent last couple of weeks reading the manual, watching community forums and doing some assignments in the game itself. And the more I was learning the more questions I was having: where to fly? Which aircraft? Rent, buy or lease? What about FBOs? How to find the best assignments? The manual and community forums have some advices, but I want more definite answers.

I mean, staying net positive is not so difficult, but being efficient is a whole another story. And I want to be as efficient as I can. Luckily, FSE offers a treasure trove of data to support decision-making in a form of data feeds. So I armed myself with Python and spend a few evenings getting some answers.

Since I'm still quite a noob in this game, my high-level plan is this:

  1. Find the most efficient way to build up initial capital without owning any assets.
  2. Find out which assets (FBOs or aircraft, which ones) would provide the most significant cost reduction.
  3. Invest and explore less involved methods of gaining revenue: rent/lease business, FBOs and all other fun.

Comment branching in C++

Feature image

Recently I've stumbled upon a code snippet in my C++ code, which I'd call “comment branching”. For example, you are experimenting with two implementations of the same functionality represented by a relatively small pieces of code and you need to switch between them back and forth until you decide which one will end up in final version.

Consider following snippet:

long number = 1024;
std::string number_str = std::to_string(number);
std::string number_str = boost::lexical_cast<std::string>(number);

If you simply remove first slash from the second line, it turns into this:

long number = 1024;
std::string number_str = std::to_string(number);
std::string number_str = boost::lexical_cast<std::string>(number);

Your first implementation became switched off, while code remained completely valid.

It's pretty obvious, what's going on there. //* is “commented-out” beginning of multi-line comment which becomes uncommented in second case. If might be considered as a kind in if equivalent. /*/ is a universal token which either starts or ends multi-line comment, depending on preceding context, something like else. Finally, /**/ works as endif token, which terminates comment is case was opened before, or does nothing otherwise. It might also be //*/, but visually I like /**/ more.

Be warned!

This technique has some disadvantages, which must be taken into account:

  • It's a very obscure way of code management for anyone except you and even for you few months later. Don't commit this ever, it's just a time-saver during playing with code.
  • If code block a large, it's hard to find these boundaries visually, especially taking into account that they most likely won't be indented.
  • It doesn't work at all if code between this special comments contains multi-line comments.

Hosted by GitHub

Feature image

Finally, I've completed transition of this blog to GitHub pages, planned over two years ago. I did the first step — migration to a static site engine (specifically, Acrylamid) — back in March 2014. And since than I've been saying to myself “one day I must move it to a GitHub as it's a best free hosting for a static site”.

I couldn't tell for how long I'd continue slacking like this, but now I had to do this. This site was hosted at free hosting service provided by since it's very beginning and recently I've received a notification, that EOMY shuts down it's shared hosting, completely focusing on VDS. It's a bit sad news, as EOMY managed to provide fantastically stable and reliable hosting for all this years, so great thank you for them and good luck with VDS business!

By the way, I have plans on implementing an automated process of site generation and deployment using TravisCI the way it's done for GCB-JS. If i do this, I'd be able to blog right from GitHub interface, which would be pretty cool :-)

Rogue Ninja support in CLion

Feature image

In a past few years I've been using C++ as my main programming language and during this time I've been in constant search for better IDE for it which would run on Linux. I was very happy when Jetbrains released CLion IDE and immediately gave it a try. Though there is a lot to improve yet, I'd say that it has best autocompletion and modern C++ support among C++ IDEs on Linux. The only problem I had with it was a build toolchain which it uses.

Currently CLion supports only CMake projects (with is totally fine for me) with GNU Make generator (which is sad). When using CMake, I always preferred Ninja build system, especially for large projects like one I work on as my main job. For some reason Make does not a very good job at incremental builds. For example, even if there is nothing to rebuild, it spends 5 seconds to only verify this fact, which is pretty annoying. On other hand, Ninja does this in like 200 ms.

Unfortunately, CLion developers currently have no plans on supporting Ninja (I realize that they have many things to do way more important than Ninja support), so I decided to solve this problem by myself.

CMake-Ninja wrapper for CLion

I've found a kind of solution for my problem on internet but it had two very critical drawbacks:

  1. You meed to edit manually CMake cache for each project you work on.
  2. You have to run cmake -G Ninja manually eash time you add or remove files from your project.

After messing around CMake and ~/.clion11 directory for a while I've came up with a simple python script which wrapped around CMake binary used by CLion, replacing -G "Unix Makefiles" command line option with -G Ninja. It did work in terms of making CLion using Ninja for building a project and didn't require any additional actions from me unlike previous solution. Unfortunatelly, it absolutely broke autocompletion support in the IDE, since it relied upon some artifacts, which Unix Makefiles generator was producing.

After some trial and errors I modified my script to act according following rules:

  1. Whenever it's called outside of CLion's private directory (~/.clionXX) or there is no -G option in command line, it simply passes control over to CMake.

  2. If there is -G option, it does some black magic to make me, CMake and CLion happy:

    1. First, it calls real CMake with original arguments, producing Makefiles required by CLion.
    2. Then it alters CMakeCache.txt to make CMake think that previous generator used was Ninja, not Unix Makefiles.
    3. Finally, replace “Unix Makefiles” occurrance in generator name with “Ninja” and call CMake again.

You may grab the script on GitHub. I've tested it on Linux and Python 2.7 but I suppose it should work on Windows and Mac too, maybe with minor modifications. Please, let me know in comments if it worked for you :-)

Finally, this script has several imperfections, which I'll fix in future. One of the most important is that it currently mizes stderr and stdout of CMake which seems to confuse CLion a little bit when dealing with invalid CMakeList.txt file.

В День Победы

Feature image

В виде исключения этот пост будет на русском, поскольку он касается в первую очередь русскоязычной аудитории.

9 мая, День Победы — один из самых главных праздников в странах бывшего СССР. По массовости празднования он может соперничать разве что с Новым Годом. Однако, мне кажется, с течением лет акцент этого праздника становится все более и более неправильным. Он превращается в символ военной доблести, военной мощи, величия. Бесспорно, все это было, и это сыграло важнейшую роль для победы как таковой. Честь и память всем, кто сражался за свободу наших родин, и тех, кто трудился в тылу и в оккупации.

Но вот чем этот праздник так и не стал — это символом Большой Ошибки. Победа может быть только тогда, когда есть война. Чтобы была победа должны погибнуть люди — неважно, кто именно победил, кто агрессор и кто больше виноват. Погибнут люди с обеих сторон. Большая Ошибка — это начинать войну. Да, если враг ступил на нашу землю, то он должен быть изгнан. Если в его руках оружие, оно должно быть и в наших руках. Но, начав войну, мы, как человечество, делаем ошибку, за которую будем дорого платить.

Боюсь, что в современном мире у нас нет права на еще одну такую же ошибку, ибо мы не сможем выплатить ее цену. Поэтому я хочу пожелать всем, независимо от национальности и убеждений, одно: помните уже совершенные Ошибки и не дайте совершить еще одну.

P.S. Специально берег эту песню для сегодняшнего поста.

Crowd funding EaxCast podcast

Feature image

I've never really mentioned this on the Internet, but I'm podcast-addicted kind of person. At the moment I have about 20 different podcasts in my subscription list and I enjoy them very much. Actually, it turned out that listening to podcasts does two important things:

  1. You don't fall completely bored while doing some monotonic work like house cleaning or dish washing.
  2. It delivers you most of the important news, keeping you up-to-date at no time cost. You know, you have to wash dishes at some point…

In my list there are two categories of podcasts: general tech news and hardcore-geeky-programming stuff. And actually I love latter the most. This kind of discussions make me thinking, directs me while exploring new technologies, teaches about things far beyond of my scope and so on. Unfortunately, there are not so many shows of this kind.

One of the young and promising podcasts is EaxCast and at this time they are raising funds for second season of the show. I'm not a kickstarter kind of person, but what makes these campaign special, is that collected money would be spent on creating text transcripts of the show. Actually, I know only about two tech podcasts, which make these transcripts. First is Security Now and the second is EaxCast.

Why text transcripts rule? Fucking obvious: it make 1 hour show searchable. When you heard something interesting in the middle of you way to work, you don't have to scroll through all audio file to find it again. You just open a transcript, hit Ctrl+F and here you are.

Why am I writing this? There are only 4 days left and ~6k rubles to go. It's 8%, they almost did it. So, if you are a programming geek, if you like what guys doing, than go donate them some money. If you don't like it, go listen the first season of the podcast, like it and go donate.

Motivational song included.

Google Cache Browser 3.0: The Late Announcement

Feature image

Today I'm going to announce a pet project, which I've been working on for a last few month. It happened so that it's live for more than two years and it's the third major release, but I never announced it on my blog. Now I have to fix this.

Meet: Google Cache Browser.

The idea behind this project is pretty simple: when viewing Google's search cache, click on any link on the cached page is going to send you back to live site, not to cache, and there are many situations when this is not what you want. For example, when you site of interest is under maintenance and you need to find something there, all internal links would be broken, leading you to “Temporary unavailable” page.

This is where Google Cache Browser comes in. It would inject himself into cached page, catch all click on links and redirect you to cached versions of paged they point to. The most beautiful thing is that you don't have to install any kind of browser extensions: GCB is a pure JavaScript running is your browser.

There are two ways to use GCB:

  1. Open, put in URL of a page and hit “Go”.
  2. Use GCB bookmarklet. It's designed to take you to the cached version of page you're currently viewing, plus adding all nice GCB features.

Переход блога на английский

Feature image

Месяц назад я всерьез задумался о переходе на английский для ведения этого блога. Проведенный опрос показал, что большая часть моих читателей не выступает против этого шага, так что этот пост будет последним на русском языке.

Еще раз перечислю причины перехода:

  1. Я пишу в основном на технические темы, часто — довольно узкие. На английском мои посты будут найдены и прочтены большим количеством людей.
  2. Писать на технические темы по-английски часто даже проще, чем на русском.
  3. Подтянуть свой письменный и разговорный английский. Такая практика не бывает лишней.

Тем не менее, я решил, что наиболее важные и интересные посты я буду писать и на русском. Они будут публиковаться на Хабре, желающие читать их могут подписываться на мой аккаунт. Хабр, кстати, отдает RSS, так что все желающие читать меня, но не желающие заводить аккаунт на Хабре, могут воспользоваться любимой читалкой.

Я теперь о “последней соломинке”, которая заставила меня принят решение о смене языка. Обычно я стараюсь избегать политических тем, что здесь, что в твиттере, но это не лезет ни в какие рамки. Я говорю об очередном идиотском законе, принятом народными избранниками. Вкратце: если у вас есть страничка в интернете с посещаемостью более 3000 человек в сутки — добро пожаловать в море геморроя реестр, считайте себя СМИ. И хоть у меня посетителей гораздо меньше, я хочу быть подальше от этого маразма.

Напоследок, мое мнение обо всех “цензурных” законах последнего времени:

Перенос комментариев из Drupal в Disqus

Feature image

Пришло время завершить цикл постов о переезде этого блога на статический движок. Я уже успел рассказать о переносе самих постов и о манипуляциях со структурой адресов. Последняя оставшаяся не освещенной тема — перенос комментариев. За 6 лет существования блога их накопилось немало, и было бы обидно от них отказаться.

Так как Acrylamid — полностью статический движок, его средств недостаточно для обеспечения комментирования на блоге, и у меня возник выбор: либо использовать сторонние сервисы, либо поднять на своем сервере собственное решение (например, ISSO от того же разработчика). Взвесив все альтернативы, я понял, что совершенно не хочу заморачиваться с собственным решением и, по крайней мере поначалу, воспользуюсь услугами стороннего сервиса.

Исследование показало, что хороших вариантов не так уж и много, и Disqus из них кажется самым удобным. Но, что самое важное, он позволяет импортировать и экспортировать комментарии в достаточно простом формате. Это обеспечивало мне возможность в любой момент сменить его на любой аналог, лишь поколдовав над конвертацией дампа комментариев.

Впрочем, есть и негативные моменты, которые скорее всего вынудят меня однажды пойти искать другую платформу. Первый среди них — тяжеловесность клиентского JS даже в сжатом виде — около 700 КБ. Это гораздо больше, чем мне хотелось бы.

Теперь дело было за малым — сгенерировать дамп для импорта в Disqus. Конечно, для Drupal существует модуль, позволяющий импортировать все комментарии в Disqus, но он не мог ничего знать про новую структуру адресов постов, и, стало быть, после смены движка снова стал бы бесполезен. Так что я пошел по уже проторенному пути, и стал писать свой экспорт комментариев из Drupal. К счастью, Disqus умеет импортировать комменты в формате WXR (родной формат экспорта Wordpress), который представляет собой достаточно простой XML.

Достать комментарии из базы Drupal было проще простого:

SELECT cid, pid, nid, comment, hostname, timestamp, name, mail, homepage
        FROM drupal_comments
        WHERE status = 0

Сохранить его в нужном формате почти так же просто, если использовать модуль питона lxml. Единственная тонкость — указывая ссылку на пост, по которой Disqus потом определит принадлежность комментариев, нужно указывать новый адрес поста, консультируясь с картой перенаправлений, полученной на [предыдущем этапе](/2014/Changing URL structure for Acrylamid.html).

Дальнейшие шаги хорошо документированы на справочном сайте Disqus:

  1. Добавление сайта в систему.
  2. Импорт файла с комментариями (обычно занимает минут 5).
  3. Установка кода на сам блог.

На этом, пожалуй, все, что касается переезда. Надеюсь, кому-то это пригодится :-)