вторник, 19 марта 2013 г.

grep support for \d

A long time ago, when every PC had own OS, it was easy to remember, which RegEx are from POSIX standart, and which appeared only in Perl-style. Now it’s almost forgotten, and C# regexp classes don’t support POSIX character classes (like [:digit:]).

That’s why the debugging of a simple bash script is so difficult. grep is older then a lot of his users, he remembers all of these times and needs -P for Perl mode and ‘\d’ for digits support.

That’s how

ls | grep -e "[0-9][0-9].[0-9][0-9].md"

becames:

ls | grep -Pe "\d{2}.\d{2}.md"

Free and open-source software licenses

There’re plenty of free and open-source software licenses and not all of them are as simple as Do What the Fuck You Want to Public License. And even if you collected all 4 freedoms and 650 pokemons, it isn’t enough.

The main thing a developer has to know about free and open-source licenses – some of them let the code be linked from code in another language, and some of them don’t.

For example, if you use something licensed as GNU GPL. your project has to be under GNU GPL too. In other hand, if you use BSD license, you can sell it to Apple to make OS X from it.

Please, check the license before using something from GitHub or Google Code.

Google Code allows only OSI-Approved licenses. You have to remember this table to be safe using projects from it:

LicenseLink with code using a different licenseRelease changes under another license
Apache License++
Artistic License+!
Eclipse Public+-
GNU GPL 3--
GNU GPL 2--
GNU Lesser+-
Mozilla Public+!
New BSD++
Microsoft Public License*+-
+ – allowed
- – not allowed
! – limited
* Microsoft Public License isn’t included in official list on Google Code, but is approved by OSI too and is very popular on Codeplex.


Git: How to rename a GitHub repo

GitHub allows to rename your repos. I really like this solution.

Install curl if you haven’t and use terminal (or cygwin under windows):

user=MyUserName
pass=MyPassword
newName='{"name": "NewNameForRepo"}'
oldName="MyRepo"
curl -u "$user:$pass" -X PATCH -d "$newName" https://api.github.com/repos/$user/$oldName

четверг, 7 марта 2013 г.

QT: error: cannot find -lQtMultimedia

The QtMultimedia library is not available in Ubuntu. If you’re trying to create in Qt a project that uses it, it will fail with following error:

error: cannot find -lQtMultimedia

To fix it, you have to install qtmobility and use multimedia items from this lib. Install qtmobility-dev and libdeclarative-multimedia. Then remove QT += multimedia from .pro file and add INCLUDEPATH to QtMobility and QtMultimediaKit directories.

воскресенье, 24 февраля 2013 г.

“Already defined” linker error

This error is very common, when you try to compile in Visual Studio a huge cross-platform C++ project.

This is because of standart C++ templates, that are released in Visual Studio libs and in additional UNIX libs too. So, you have to exclude one of them to use another.

Just add one of them, go to Project Properties / Linker / Input / Ignore Specific Default Libraries and add the standard lib that produces conflict. For me it was enough to add LIBCMT.LIB.

LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt

LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt

It's a common error when you compile C++-projects with Visual Studio 2010. Ift happens when 2 version of Visual Studio are installed on same PC (like 2010 and 2012) and cause conflict between two versions of cvtres.exe.

To fix it, go to the bin directory of Visual Studio 2010 (c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\ or something like this) and rename cvtres.exe to cvtres0.exe.

Don't worry, it willn’t break linker of 2010,

суббота, 8 декабря 2012 г.

WordCount в Sublime

Sublime чудесен. Можно сказать, что проблема отсутствия под linux-ом Notepad++ успешно решена.

Правда был вопрос – насколько можно его использовать для написания всяких текстов. А чтобы в программе писали тексты, она должна уметь подсчитывать символы.

Соответствующий плагин нашёлся сразу, но он не умел посчитывать количество символов. Решил допилить, а заодно разобраться, что у этих плагинчиков внутри.

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

Обновлённый код успешно merged и залит в основную ветку.

А удивил меня сам алгоритм подсчёта. Их там целых два, причём первый закомментирован:
#=====1
# wrdRx = Pref.wrdRx
# """counts by counting all the start-of-word characters"""
# # regex to find word characters
# matchingWrd = False
# words = 0
# for ch in content:
# # # test if this char is a word char
# isWrd = wrdRx(ch)
# if isWrd and not matchingWrd:
# words = words + 1
# matchingWrd = True
# if not isWrd:
# matchingWrd = False


#=====2
wrdRx = Pref.wrdRx
words = len([x for x in content.replace('\n', ' ').split(' ') if False == x.isdigit() and wrdRx(x)])
На первый вгляд, алгоритм 1 должен работать лучше и экономней. Фактически, перед нами нечто наподобие state machine, и его сложность не больше o(n). В то время как второй алгоритм создаёт кучу новых элементов только для того, чтобы их пересчитать.

На самом деле алгоритм 2 отрабатывает намного быстрее, чем 1. Например, чтобы подсчитать количество слов в “Петербургских трущобах” Крестовского, 2-ому нужно порядка 1 сек., а первому – 2.

Вот вам и оптимизация.