All articles, tagged with “linux”

Об уважении

Назвал человек админов красноглазыми, а они возьми и обидься. И посоветуй ему в sources.list вставить ссылки на Debian experimental.

Будет плакать и жалеть, что никто не предупредил. А будет поздно.

Update: говорил же, что будет плакать

Converting scanned pages from PDF to DJVU

Last week I got PDF file with jpeg images for pages. As images were quite large (2095x2995) my lBook V3 had some trouble flipping them (15 second a page).

After some considerations I decided to transform PDF to DJVU format.

What can be easier?

  1. Extract JPEG pages from PDF
  2. Transform JPEG to PBM
  3. Transform PBM to DJVU
  4. Compile individual DJVU files in one book

The JPEGs were extracted without problem.

pdfimages -j source.pdf output

which gives a set of output-nnn.jpg files in a current directory.

And here comes the trouble.

Each JPEG contained a scanned color (RGB) or grayscale bookpage and had resolution like 2100x3000. Each image contained not only the front of the page but the back too as sheets of paper were quite thin and transparent on a scanner. It looked like this:

Original image

Once I tried to scan a paper book to read it on my lBook reader. That time I just told XSane to scan in “black&white mode” so there will be only letters on the front of the page and clean white background without contents from the back of the page.

After several minutes of search I found a name of the function to reduce colors of image — Posterize.

I checked the function in the GIMP and was quite pleased with the result. As there were hundreds of images to convert I needed more automagic solution. “What can be easier?” I asked myself again and run man convert (convert is a part of the ImageMagick suite). Quick search of the manual revealed -posterize function and all JPEGs were quickly converted by a shell for loop.

Alas the result was quite different from the one produced by GIMP.

Image By GIMP:
Image by GIMP

Image By Convert:
Image By convert

convert utility reduced the number of colors but emulated underlying images with dithering (to add insult to injury cjb2 utility from djvulibre suite wasn’t able to tell the difference between letters and background — result was a mess).

I must admit that I can’t cook utilities from the ImageMagick suite properly.

So I tried to make GIMP convert images automagically. That cost me several hours of debugging and cursing.

Beware of the snakes there.

Note to the brave: don’t always trust the tutorials and reference. Functions that return TRUE or FALSE by the reference in fact return (1) or (0) — a list containing one element — both are considered TRUE. Hence the (if (= 1 (car (function ...))) syntax.

First run GIMP in batch mode:

$ gimp -b —

Paste the script there:

(define (batch-jpeg-pbm filemask)
  (let* ((filelist (cadr (file-glob filemask 1))))
    (while (not (null? filelist))
      (let* ((filename (car filelist))
             (image (car (gimp-file-load RUN-NONINTERACTIVE
                                         filename filename)))
             (drawable (car (gimp-image-get-active-layer image))))
        (if (= 1 (car (gimp-drawable-is-rgb drawable))) 
          (gimp-image-convert-grayscale image))
        (gimp-posterize drawable 2)
        (plug-in-autocrop RUN-NONINTERACTIVE image drawable)
        (let ((newfilename (string-append (substring filename 0
                            (- (string-length filename) 4)) ".pbm")))
          (file-pgm-save RUN-NONINTERACTIVE image drawable
                         newfilename newfilename 1))
        (gimp-image-delete image))
      (set! filelist (cdr filelist)))))

And run it like this:

> (batch-jpeg-pbm "/path/to/your/images/*.jpg")

After several minutes for each JPEG there will be a .pbm bitonal file which can be converted to DJVU by cjb2 utility like this:

$ for i in *.pbm; do cjb2 $i $i.djvu; done

Next command will compile all DJVU files into one book:

$ djvm -c book.djvu *.djvu

Read more about Script-Fu

Microsoft Ukraine CEO about open source and free software

Recently Ukraine government made another move toward an open source software. As anyone would expect Microsoft has something to say and something to offer.

I can’t help but translate some FUD by Microsoft Ukraine CEO Dmitry Shimkiv

Can you elaborate on Microsoft’s position on using open source software in state institutions?

No doubt a government should consider an open source software as one of the possibilities. We always support this as it helps to raise an intellectual potential of Ukraine and facilitates exchange of code between local and foreign developers. But there are many questions. For example, lets consider rewards for time spent on generating ideas and implementing them. Ukrainian laws have provisions about rewarding author for his work. When there is a community around open source software everyone will do his part. This means emerging product will be non-commercial because if you implement your ideas and someone make billions on them sooner or later you’ll be asking “Can I have my $5k?”. And those questions will be asked constantly. As Ukraine laws protect the author I can sue and win the case if the open source software contains some lines of code written by me. If I can’t sue here in Ukraine I’ll do it abroad and still win. Somehow these questions are left without discussion. Few understand what open source means. It’s like open society. Everyone talks about it but hardly someone understands.

Suppose the company A wins a tender. Suppose they hire ukrainian developers and build a Linux distribution signing all necessary papers to have a right to distribute product.

This won’t be an open source anymore. Just this company’s product.

But what if they use open source software to build it. For example, base it on distributions like Ubuntu or RedHat?

Okay, but let’s consider possibilities. Tomorrow there will emerge a boy from Israel, Germany or USA and he will sue Ukraine for using his intellectual property. Do you understand inherent risks? Bomb is planted and primed. You’re going to take code intended only for non-commercial use and start to sell it.

But we can sign papers to transfer rights with every developer and pay a reward for it. Let’s say we pay $100 and there will be no further claims.

I can’t see a clear business model in this. Okay we gave them money. But what are you going to do if something work not as intended?

But there will be a company to carry all such requests.

Their reply will most likely be “We didn’t do those modifications” as this is open source. There were situations like this before. Let’s don’t forget other companies. Like Sun who can call and tell you “We are sorry but there are lines of code in your product we own or have a patent covering them. And we want money”. What will you do? Are you going to cut parts of product code base?

But Brasil or China have managed to avoid these problems before.

So what? There are no countries at the moment where governments are using an open source software exclusively.

Don’t you think this move was intended to soften Microsoft position? This is not a first time this happens. Five years ago Microsoft had offered better deal in response to an open source wave.

Government had some arrangements but done nothing. As ukrainian I’m very sorry for them if cooperation with Microsoft will stay as it is now. Also suppose government will finance development of a national open source operating system. By some guesses it will take at least four years. And all these years Ukraine is going to use pirated software. We have right to demand to cease such practice. What will you do then?

Что делать, если на клетке написано ”слон”?

Файл управляющего сценария с расширением .php содержит внутри такую конструкцию:

#!/bin/sh
echo [$0] ... > /dev/console

<?
код PHP
?>

Хочу понимать эту логику, пусть меня научат.

Выбор ноутбука

Рассматривая каталог ноутбуков заметил название eMachines. Сначала подумал, что какая-то новая китайчатина. Начал искать и обнаружил, что полное название выглядит как Acer eMachines. Помня, что хорошую вещь азером не назовут, производитель решил чуть-чуть внести изменения в схему именования. :)

А теперь о серьезном — посоветуйте ноутбук до $500, поддерживаемый последними Ubuntu (я буду ставить Debian). Предполагаемые задачи: самообразование (emacs, firefox, haskell, python), развлечения (фильмы).

Adobe Alchemy и главный вопрос

Недавно Adobe опубликовала проект Alchemy позволяющий компилировать код на C/C++ в байткод виртуальной машины ActionScript.

Первым наглядным результатом можно считать портирование на Flash игры Doom.

Но это не главное. Главное можно описать двумя вопросами:

  • Можно ли на Adobe Alchemy запустить Linux?
  • Если да, то можно ли из нескольких экземпляров создать кластер Beowulf?

Random password generation

Don’t crush your keyboard with your fists if you need to generate large volume of random user passwords.

You can base your password generator on /dev/random but those passwords would be difficult to remember.

Instead use apg.

This post is based on actual events.

А вот и послевкусие…

Некоторое время назад я написал о принудительном переводе на Linux. Тогда было сделано предположение, что через некоторое время будет сказано о “неудобности” и “неприменимости” Linux.

Вот и ответ на наши ожидания.

В ответе есть два очень интересных момента.

 

Этот день мы приближали как могли… но у победы может оказаться странный вкус

Вот тут разработчик жалуется, что контора его принудительно пересаживает на Linux. Сказано — сделано. Быстро поставили Ubuntu и вроде бы миграция закончилась.

Теперь о странном вкусе. Через некоторое время я жду возмущенных криков “а почему в Linux нет аналогов уродских инструментов разработки под Windows?”.

Следим за журналом мигрирующего и делаем ставки в каментах?