Jump to Navigation

Coding

Excel 2007 & 2010 addin: Export selection to .CSV & .ARFF

Excel 2007/2010 CSV and WEKA ARFF export addin

Yesterday I needed to export data from Excel 2010 (or 2007) to WEKA datamining software, and found out that Excel's CSV export is pretty much broken. Hey, MS developers, ever heard about the first word of CSV acronym? Yes, it's COMMA, not SEMICOLON.

Also, WEKA does want strings enclosed in "'s, and on my czech locale, Excel exports decimal numbers with comma instead of dot (that's probably the source of semicolon messup).

Therefore, I wrote the addin that exports active selection as a proper CSV, or WEKA's preferred ARFF format (numeric and discrete attributes are supported by simple key: first row is headers, if all other rows are numbers, it's numeric, otherwise it is a set of discrete values).

You can easily add support for another file formats by inheriting from ITextFileFormat, adding instance of it to list in exportButton_Click, and recompiling.

*) Works on my PC, no further guarrantees :)
**) If you modify/improve it, drop me a note, and I'll be happy to re-release with your changes

StyleSnooper - useful utility for WPF developers and designers, fixed

I found Lester's and Arbel's StyleSnooper - a wonderful tool for getting WPF template of any visual control and I loved it.

However, the layout was wasting screen space, there was a bug in indenting algorithm, and I was missing the options to customize indentations, so I fixed the aforementioned, and am releasing the fixed version here:

Download StyleSnooper

Twitter backup script with url decoding

I appended excelent dgx's twitter backup script with decoding of minified urls, because I hate being dependent on volatile third parties, and url shorteners are an excelent example of such.

The xml is similar to the twitter xml response, but each status has additional element text_decoded, which contains tweet's text with url's replaced by their original versions.

Usage:

Edit your username and password in source, run from the commandline (php twitter-backup.php).

Known limitations:

Unshorten::Decode does not distinguish url shorteners, it just uses any target of redirection it gets (so if tweet author included full url, and that is now redirected to another site, you will get that another site in the output).

Download:

See the bottom of the article.

Enterprise service bus - přednáška

Má přednáška o ESB podle knížky Davida Chappella

MIX 2009 – lectures I watched

My tips for interesting lectures from Microsoft MIX 2009 conference:

Advance Your Design with UX Design Patterns
boring lecture, equivalent to reading Infragistics Quince design patterns list, but at a slow pace - skipped most of it
Ten Ways to Ensure RIA Failure
my recommendation to project managers - great one, fast, all the good points
The Way of the Whiteboard - Persuading with Pictures
could be summarized in 10 minutes, but the last third is great (6 kinds of questions -> 6 kinds of diagrams to answer them) and the rest it at least infotainment
Escaping Flatland in Application Design - Rich User Experiences
good in the beginning, second half is boring WPF ad, and WPF is dead/killed by MS anyway - skipped it
File|New -> Company: Creating NerdDinner.com with Microsoft ASP.NET Model View Controller (MVC)
great introduction to ASP.NET MVC by ScottGu
Off topic: Design Principles for Windows 7
on todo list :)

Apple a ARM tablet?

Ad: Netbooky, ARM a opakující se historie od Swarma:

Já Apple moc nemám rád, ale tady mě hned napadlo že Apple by na to měl - už párkrát ukázali že umí udělat malé a úsporné zařízení (viz porovnání minuty na internetu/kapacita baterie na Anandtechu, kde windows notebooky mají mezi 1,5-3 m/Wh, zatímco macbooky jsou mezi 5-6,5 (!!!)), mají jádro MacOS portované na ARM (iPhone), a mají sílu protlačit své řešení masám a přimět vývojáře k psaní SW na svou platformu.

A kdyby to mělo 10″ displej, pod 0.8 kg, výdrž přes 10h, volitelně touchscreen (s překlápěcím displejem ala tablet), netbooky by byly mrtvé do dvou let.

Odpověď pro soczmrda, tentokráte z Lupy.cz

Ad www.lupa.cz/clanky/skript-nereaguje:

Sorry ale nevyplatí se mi se o vás starat...

Právo sledovat starým prohlížečem veškerý obsah internetu není nikde kodifikováno, proč si myslíte že ho máte?

Chcete-li donutit tvůrce stránek aby s vámi počítal, připravíte ho tím o čas který by mohl věnovat starání se o 99% ostatních uživatelů (a každý rozumný tvůrce to tak udělá protože se mu to vyplatí). Ve výsledku ztratí společnost hodnotu, tak jako je tomu vždycky když si pár socialistických duší začne myslet že jejich potřeby jsou nadřazeny potřebám ostatních.

PS: není nic jednoduššího než najít zmíněný skript a adblockem zakázat - i majitelé aut veteránů mají s jejich provozem větší náklady a nereptají.

Update: Teď mě napadlo lepší přirovnání: Představte si, že vám pár čtenářů napíše, že články na Lupě jsou povrchní, triviální a většinou za nic nestojí, pak:

a) seženete výborné autory, dobře je zaplatíte a zlepšíte kvalitu tohoto serveru aby bylo spokojené i poslední procento uživatelů

b) s*** na ně, stejně neklikají na bannery a nepřináší koruny, a i kdyby klikali, nárust kvality stojí víc než přinese nárust počtu čtenářů

Tohle už by mělo jít pochopit :)

Google Code Jam: o kousek...

Tak jsem se přihlásil do GCJ, a pak s překvapením zjistil že mám posledních 35 minut do deadlinu :). Takže jsem se vrhnul k Eclipsu a začal kódit úlohu A - universe. No, hotovo bylo 4 minuty před deadlinem, ale oiga - výstup neakceptován...

Oprava bugu spočívala v umazání jednoho sčítance, ale bohužel, nezadařilo se do termínu :). Tak aspoň dirty kód pro potěchu:

function rln() {
        static $fpointer = 0;
        global $file_in;
        $line = $file_in[$fpointer++];
        return ereg_replace("\r\n","",$line);   
}

function arr_write(array $arr) {
        $out = "";
        foreach ($arr as $a) {
                $out .= $a . "\r\n";
        }
        echo $out;
        return $out;
}

function max_first_occurence(array $needles, array $haystack, $start = 0) {
        $max = count($haystack)+1;
        $haystack = array_slice($haystack, $start, count($haystack) - $start, true );
        $pos = array()
        foreach($needles as $index=>$needle) {
                $pos[$index] = array_search($needle, $haystack);
                if ($pos[$index]===FALSE) {
                        $pos[$index]=$max;
                }
        }
        asort($pos);
        $keys = array_keys($pos);
        return array( "index" => end($keys), "pos"=> $pos[end($keys)] );
}

$argc = $_SERVER['argc'];
$argv = $_SERVER['argv'];

if ($argc<1) {
        echo 'zadej soubor';
        exit(1);
}

$filename_in = $argv[1];
$file_in = file($filename_in);

$cases = rln();
 
for ($case = 0; $case<$cases; $case++) {
        $engines = rln();
        $engine = array();
        for ($i=0; $i<$engines; $i++) {
                $engine[] = rln();
        }
        $queries = rln();
        $query = array();
        for ($i=0; $i<$queries; $i++) {
                $query[] = rln();
        }
       
        //algorithm
        //echo "----------".($case+1)."----------\n";
       
        $changes = -1;
        $done = false;
        $pos = 0;
        while (!$done) {
                $res = max_first_occurence($engine, $query, $pos);
               
                $ppos = $pos;
                $se = $res["index"];
                $pos = $res["pos"];
                //echo(" ".($ppos+1)." - $pos : {$engine[$se]} \n");
               
                if ($pos>count($query)) {$done = true;}
               
                $changes++;
        }
        //echo "-------\n";
        echo "Case #". ($case+1) .": ".$changes."\n";
       
       
}

Vista (windows generally) suffers from not having a powerful GUI toolkit

One powerful GUI toolkit available from early version would save Windows' GUI consistency and work of all platform developers.

I like Vista, but things like this really bring the user experience down, because of inconsistency.

I noticed, that on Linux, it is mostly solved by having universal GUI toolkits (GTK and QT), and that way, application's look and feel is always consistent, and it is possible to update the look of an app simply by replacing toolkit's files in a system.

On the windows platform, however, apps are directly acessing windows API and implementing their menus and other GUI parts, and without an intermediate layer of GUI framework, they need to be rewritten to be updated to a new look.

And that is the problem of Vista leading to a sites like Long Zheng's UX Taskforce - apparently, there is a lot of programming teams in MS, and each one has a bit different opinion as to how interface should look. This is nothing unexpected - try to synchronize aesthetical feelings of several thousand developers - but it is unnecessary, and it shows that more is less. If there was only one way to do menu, abstracted from look, things would be easier on both sides - look, windows, here is a hierarchical structure with menu items, shortcuts, icons and callbacks, and now draw it as you like, in a manner consistent with a platform.

Another thing - layout: QT and GTK have a nice layout support, so it is possible to just stack some layout placeholders, and have everything resized automatically, even when window size/dpi/font height/ammount of text changes. In pure windows API, this needs to be coded by hand, and if everyone does it on his own, everyone will do it differently (and everyone will forget some edge case when things will get broken).

OK, there appeared some GUI frameworks that solve this, but still, each one of them do things differently, so it is still much worse, compared to situation when windows would have a powerful GUI tookit from the beginning.
So, sorry MS, but you are the cause of inconsistencies, which bring you laughter from both apple and linux fanboys (and cost you millions on maintenance costs with every new version of windows), and being a Vista fan, I must agree with them - sadly, though.

On the other side - making the platform developers sprinkle their code with unportable windows API constructions is maybe the best way to ensure that code won't get ported to competing platform. But if there was an evil mastermind behind it, it caused a huge pain to every windows developer. How sad :/.

PS: Of course, now with .NET System.Forms and WPF, things are much better, and easily maintainable, but so far, 99% of applications in Vista installation are native, written in C++ and Windows API.

The future user interface

K vizím o ovládání počítače řečí, a Hlavenkově článku o tom, proč je to špatně:

Nevím na co jsou potřeba tyhle velké exklamace, snad na udržení pozornosti médií, ale svět se mění pomalu, evolucí, a tak to zůstane. A vůbec to není špatně.

Co třeba takový mobilní telefon? před 20 lety scifi, před 10 ti jedna krabička z mnoha, a dnes se pomalu stává všemi těmi scifi 'wearable computers' - jen menší a chytřejší - zavolá, přehraje hudbu, video, brzo i po síti (až klesnou ceny za data), najde odjezd autobusu, natočí oslavu narozenin (VGA, 30fps, na HD video si zas tak dlouho nepočkáme), odpoví na otázky (google, wikipedia, celý web v kapse), najde nás, ukáže cestu... jen to není s žádnou revolucí a nikdo se nad tím nepozastaví.

A vůbec, změny nás čekají, opravdu v rozhraní, ale proč se omezovat na silně omezené médium hlasu? Kolik informací přenese za stejný čas jeden člověk druhému řečí, textem, videem? Když nepočítáme city a mimoverbální komunikaci, což od počítačů nechceme?

Jak moje máma pozná kdy má kliknout jednou a kdy dvakrát? Proč se má učit že když chce nahrát fotky na flashku, tak má hledat v jakýchsi abstraktních hierarchických strukturách, hlídat si zda kopíruje či přenáší, otvírat jakýsi explorer aby v něm našla možná flashku, bez jakékoliv spojitosti s fyzickým objektem flashky...

Co kdyby se při zapojení flashky do moniotoru objevil přesně u ní výřez obrazovky kde budou soubory z flashky (co, soubory - prostě fotky, texty, videa rotřízené do hromádek tak jak to má člověk i v hlavě, fotky podle gps tagů, času pořízení, lidí co na nich jsou - 'týdenní akce se třídou na chatě' - takový titulek může počítač hromádce vymyslet i sám, má-li dost metadat, ví že minulé fotky ze stejného místa jsme označili 'na chatě', stejní lidé se objevili na všech fotkách označených jako 'třída' a že jsou souvisle z týdenního intervalu - keyword: semantic web, semantic technology).

A vůbec, jaké složky a disky, je to prostě všechno 'v počítači', a když ten nerozumí tomu co po něm chceme, tak se doptá na detaily... (to je asi idea WinFS, plochá struktura se spoustou metadat, chytrým UI které jim rozumí, a kdo chce adresáře, ten si je udělá nějakými tagy, zatímco underlying objekt existuje jen jednou - tohle je podle mě vizionářská myšlenka pro jednadvacáté století).

IT je dneska jako automobilový průmysl za Henryho Forda (Billa Gatese): Každý má auto, firmy vědí, že se sebelepším koněm autu konkurovat nemohou, ale zároveň každý řidič, každý táta rodiny musí vědět, jak je převodovka udělaná aby ji nezadřel, jak opravit libovolnou část uprostřed cesty, jak pracuje motor... dneska stačí vědět že volantem doleva doprava, plyn zrychlí, brzda zpomalí, a když je něco špatně, rozsvítí se kontrolka a pán v servisu to opraví.

A tahle kultivace čeká i počítačový průmysl, jen nesmíme zapomenout, že tomu automobilovému to trvalo přes osmdesát let a ještě není u konce.

PS: A že je dneska rozhraní moc? Ba ne, bude jich potřeba řádově víc, co třeba poslání mailu -> poslání textové zprávičky, poslání delšího textu, poslání fotky, poslání písničky, poslání kusu písničky, poslání videa, poslání kousku videa, poslání pozvánky ke spolupráci... Kopírování souboru -> kopírování fotky (mají stejný název ale je na nich něco jiného, mám je přejmenovat?), kopírování videa (nevejde se tam, počkáš si na překódování?) - možná to jsou špatné příklady, ale chtěl jsem ukázat že abstrakce souboru nemá vždy všechny vlastnosti všech skutečných objektů, se kterými chce uživatel zacházet, a to zatím uživatele mate.

Počet rozhraní bude explozivně růst, začátkem jsou dnešní webové aplikace (aplikace jako specializované rozhraní k to-do listu, jiná aplikace jako specializované rozhraní k nejoblíbenějším písničkám...)

Set your mouse precision correctly (and don't rely on windows setting)!

I have a wonderful Razer Pro|Click mouse, but since I started using it with Razer's drivers, I suspected that the precision isn't as it used to be.

And I was right: While setting high sensitivity in Razer's control panel interpolates mouse movement correctly, Windows Pointer Speed setting "cheats" - when you set it on high, it just moves cursor by more than one pixel, when a message from mouse driver arrives - thereby reducing your hi-tech mouse to a normal office peripherial.

The result? Unability to click on certain pixel when you need it (cursor just jumps around, no matter how hard you try)..

Solution: Leave windows 'pointer speed' setting on one half (anything more will make Windows cheat), and instead, increase mouse precision in Razer's control panel (I don't have experience with Logitech or Microsoft mice, but I think it would be similar).

For testing of mouse precision, I prepared an applet in Processing, that shows (and magnifies) the movement of your mouse. Run it and tweak :).

See the Mouse Precision Test (click for more):

Browser plugin idea: Personal blacklist

Inspired by post on Lupa.cz

Plugin for blacklisting posts from certain authors/users:
Consists of

  1. Server, with a database of URLs (wildcarded), and regexps/xpath queries/JQuery commands to identify a part of page authored by certain user and name of author of that part.
  2. Client plugin, which would filter all content pages, and could remove content from banned users.

    It would also enable users to mark certain author as blacklisted (for example by right-clicking author's name and choosing blacklist). After blacklisting, user would never see any content submitted by that author anywhere on the internet (because after browser arrives at url, it asks server whether there is a known way of assigning authors to page parts, and then uses that info to filter out that content - assigning display:none, or deleting from DOM).

    Last thing client could do, would be enabling user to create a content filter for a website which isn't yet in main server's database. Something like Opera's block content would be nice - hover over the page until the div with post highlights, then find the element containing author's name, third - define urls that have same structure.

So, if I for example decide that I don't want to see a thing written by 'Krakonos', I would mark him as my blacklisted author, and when I later arrive at news server, which employs this guy as author, I wouldn't see his articles on a homepage, I wouldn't see his posts in discussions, etc...

Sounds good? If not, blacklist me :)

Prezentace Drupal CMS

Dělal jsem do školy prezentaci o Drupalu, a říkal jsem si, že by byla škoda ji dál nezveřejnit, takže tady je :).

Text k prezentaci (ve spolupráci s Igorem Kulmanem) najdete zde.

Move between WiFi networks with one simple script

I am using my laptop at different places, and I always disliked the difficulty of moving between a WiFi network with static IP addresses and public WiFi with automatic configuration.

However, after a long time, I found out that you can assign IP addresses, gateways and DNS servers from the command line, and it is realy easy:

  1. (optional) Name your Wireless network connection with some distinct name - I use WiFi
  2. Change to static IP
    staticip.bat

    REM set up static IP - change indicated addresses to your own
    netsh interface ipv4 set address name="WiFi" source=static address=192.168.1.1 mask=255.255.255.0 gateway=192.168.1.255 store=persistent
    REM add a default DNS server - I use OpenDNS
    netsh interface ipv4 set dnsserver name="WiFi" source=static address=208.67.222.222
    REM add a backup DNS server
    netsh interface ipv4 add dnsserver name="WiFi" address=208.67.220.220 index=2

  3. Change to automatic configuration
    dynamicip.bat

    REM set dynamic ip address
    netsh interface ipv4 set address "WiFi" dhcp store=persistent
    netsh interface ipv4 set dnsserver name="WiFi" source=dhcp
    REM ipconfig /renew WiFi doesn't do anything in my case, I have no idea why
    ipconfig /renew Wi*

It seems weird to me that widows have really nice and easy UI for switching WiFI networks, but everyone at Microsoft assumes that every wireless network uses autoconfiguration.

Drupal Bugfix: Content from anonymous users disappears

I found a case where Drupal installation can be broken by depending on undefined behaviour of MySQL server with MyISAM tables - see bugreport at http://drupal.org/node/243423 and longer story at http://drupal.org/node/239150.

If you are wondering why anonymous comments aren't displayed / doesn't show in Drupal, you have found the reason. It also explains why Drupal won't display anonymous posted content. (that should be enough to lure googling miserables :))

Uff, 5 hours of my life lost, I hope I will be the last victim of the bug :).

Update: I made a custom module to check for user with uid = 0, if it doesn't exist, module will find it in database and assign uid = 0 back, and tell the admin on a report page. Download for Drupal 6.x

Big ORM frameworks are elegant? Hardly, I say!

I was looking at todays state-of-the-art ORM frameworks for PHP, particularly at Propel.

I wanted to see, what is that good, object and elegant way of doing things. And I was quite amused:

Consider a task as simple as building a query. Wait, a query is... just a query, you write it on a line and it exists. Well, not quite so in Propel:

$criteria = new Criteria;

$criteria->add(
  AuthorPeer::FIRST_NAME,
  'Sebastian'
);

$criteria->add(
  AuthorPeer::LAST_NAME,
  'Nohn',
  Criteria::NOT_EQUAL
);

$authors = AuthorPeer::doSelect($criteria);

OMG, it's full of objects! What do we want to accomplish here? Propel have just defined its language for making queries, ignoring te existence of a old, standardized, widespread language called SQL, which is here... for making queries.

How the equivalent criterion in SQL looks like?

WHERE first_name = 'Sebastian' AND last_name <> 'Nohn'

So, Propel have just said 'fuck off' to millions of developers speaking SQL. Your language isn't good enough, come learn my new language. It is adds 800% more Lines Of Code, it makes things harder to understand, because you read the definition of criterion about three times longer than you need for understanding what it does, and best of all, it is 100% equivalent to SQL - which mean that learning this DSL will not give you any new abilities, or won't make it easier to express more. Compared to Brawndo, it sucks.

Where does object oriented approach help? Well, we now know sure that $criteria->add( AuthorPeer::LAST_NAME, 'Nohn', Criteria::NOT_EQUAL); expresses inequality, after all, we spent 19 keystrokes writing it (as opposed to two with'<>'). Also, we have explixitly specified that LAST_NAME belongs to author. Good, but SQL knows it without mentioning. And if we wanted to specify it, we cas express it as well, only in a shorter way: author_peer.first_name.

Also, why do we have two criterions? It just says so, in 11 lines, that theres AND relation between them, unfortunately, this has never been said explicitly (Saving keystrokes now, Propel? I say throwing away the semantics and pissing against the wind).

So, if a good, compact query language exists, why reinvent the wheel, poorly?

I think we should keep using good old SQL, and frameworks should be there to make it safe and comfy with the minimum of programmer's additional keystrokes:

$authors = AR::Find('AuthorPeer', AR::Prepare('firstname=%s AND lastname <> %s','Sebastian', 'Nohn'));

Database schemas rant

Another thing I find weird is how ORM frameworks like to generate database from XML files. Well, there is already a language for defining database tables... but you know the drill :).
So, what does XML bring to the table?

  • It isn't very human readable - meaning it will make things harder for you, developer, and waste your time every time you use it.
  • It can be machine processed easily - so the guys who wrote the framework once did save some time - but you are not interested about how long they spent implementing it.
  • There are no tools that can edit tables visually and aid you with tedious details, once you save the table in XML.
  • On the other side, you loose all the support of tools, of educated public on the internets, of textbooks you bought, of your databases 101 course...
  • And we shouldn't forget all the synchronization problems when you change the XML, but have to change the tables manually, otherwise you loose all the data, and the pleasure of running update script and waiting for all tables to be rebuilt after every change...

So, I say, kick the XML definition back to trash, the real, actual, tables are our model, and our framework should respect that and learn from them!

Český webhosting zdarma - ztráta času

Tato stránka je varováním!

Potřeboval jsem najít webové útočiště pro svou Bc. práci, a jelikož mám na svém hostingu u webdum.com jen jednu databázi, šel jsem hledat freehosting. A jak to dopadlo? Akorát jsem se nas***:

  • php5.cz - mimořádně pomalé (asi 30s na homepage). Děkuji, nechci.
  • pipni.cz - stačilo najít náhodné fórum zabývající se hostingem a je vvidno že TCN (Tudy cesta nevede)
  • banan.cz - serioznost se pozná tak, že lidi od banánu (nebo člověk? vypadá to na one dumb man show) obíhají český internet a všude pod náhodnými přezdívkami vychvalují banán. Všichni ostatní mluví pravdu - raději do hlavy ránu, nežli hosting od banánu.
  • webzdarma.cz - zřídil jsem si účet, nahrál stránky, nahrál databázi, spustil a co nevidím, parse errory na každé stránce. To snad ne - wz.cz v roce 2008 má stále zastaralé php 4.3 bez podpory objektů :O. KTHXBYE.
  • ic.cz - to už vypadalo lépe, php5 + mysql5, dobré podmínky. Nahrál jsem prezentaci, synchronizoval databázi a ... fuck - u poloviny tabulek přidání záznamu způsobí chybu tabulky, takže ta se potom musí opravit, přičemž přidané záznamy smaže. Tomu říkám mysql funkčnost. Fuckoff, bye.

To je vážně český internet plný neumětelů a sígrů?

Takže nakonec jsem si zřídil za stovku/rok další databázi u webdomu, a jedu... uff.

Český freehosting - ztráta času.

PS: Webdům opět ukázal jak vypadá kvalita, během tří let se mi nestalo, že bych dostal odpověď na mail za více než 4 hodiny. Thanks:).

Vítací (a testovací) blogový příspěvek

Testovací text, ale hlavně vyzkoušíme kód:

#ifndef IRCLI_H
#define IRCLI_H

#include <QtGui/QMainWindow>
#include <QString>
#include "ui_ircli.h"

class IRCli : public QMainWindow
{
Q_OBJECT

public:
        IRCli(QWidget *parent = 0);
        ~IRCli();

private:
        Ui::IRCliClass ui;

private slots:
        void on_pushButton_clicked();

};

#endif // IRCLI_H

Vypadá to dobře? :)