Code Snippets Content Syndicate content

  • A collection of snippets in different programming languages which might be useful to one or the other.
    Languages span from PHP over JavaScript to Bash and HMTL/CSS.

  • » Shell helper: running KDE unit tests (ctests) the easy way

    Thu, 03/26/2009 - 03:09

    Unit tests are in my eyes a very important part of programming. KDE uses them, KDevelop does - the PHP plugin I help writing does as well. cmake comes with a ctest program which does quite well to give you a quick glance on which test suite you just broke with your new fance feature :)

    But I am very dissatisfied with it. Right now I usually do the following

    1. # lets assume I'm in the source directory
    2. cb && ctest
    3. # look for failed test suites
    4. cd $failed_test_suite_path
    5. ./$failed_test_suite.shell | less
    6. # search for FAIL
    7. cs
    8. cd $to_whereever_I_was_before

    That’s pretty much for just running a test. Especially all that cding and lessing became very tedious. Tedious is good, because I eventually fix it:

    introducing kdetest

    I wrote a bash function (with autocompletion!!!) called kdetest. Calling it without any parameter will run all test suites and gives a nice report of failed functions at the end. Here’s an example (run via cs php && kdetest).

    1. kdetest
    2. # ... lots of test output
    3.  
    4. --- ALL PASSED TESTS ---
    5. ...
    6. PASS : Php::TestCompletion::implementMethods()
    7. PASS : Php::TestCompletion::inArray()
    8. PASS : Php::TestCompletion::cleanupTestCase()
    9.  
    10. 143 passed tests in total
    11.  
    12. --- ALL FAILED TESTS ---
    13. FAIL! : Php::TestCompletion::newExtends() Compared values are not the same
    14. FAIL! : Php::TestCompletion::updateExtends() '! forbiddenIdentifiers.contains(item->declaration()->identifier().toString())' returned FALSE. ()
    15. FAIL! : Php::TestCompletion::updateExtends() '! forbiddenIdentifiers.contains(item->declaration()->identifier().toString())' returned FALSE. ()
    16. FAIL! : Php::TestCompletion::updateExtends() Compared values are not the same
    17. FAIL! : Php::TestCompletion::newImplements() Compared values are not the same
    18. FAIL! : Php::TestCompletion::updateImplements() Compared values are not the same
    19.  
    20. 6 failed tests in total
    usage
    • kdetest, i.e. without any arguments runs all tests in this directory and below
    • kdetest path/to/test.shell ... runs that test suite only, ... can by any argument the test suite accepts.
    autocompletion

    kdetest comes with full support for autocompletion of tests and functions, for example:

    1. milian@odin:~/projects/kde4/php$ kdetest TABTAB
    2. completion/tests/completiontest.shell duchain/tests/expressionparsertest.shell parser/test/lexertest.shell
    3. duchain/tests/duchaintest.shell duchain/tests/usestest.shell
    4. milian@odin:~/projects/kde4/php$ kdetest duchain/tests/usestest.shell TABTAB
    5. classAndConstWithSameName classSelf interfaceExtendsMultiple staticMemberFunctionCall
    6. classAndFunctionWithSameName constAndVariableWithSameName memberFunctionCall staticMemberVariable
    7. classConstant constant memberFunctionInString variable
    8. classExtends constantInClassMember memberVariable variableTwoDeclarations
    9. classImplements functionAndClassWithSameName memberVarInString variableTwoDeclarationsInFunction
    10. classImplementsMultiple functionCall newObject varInString
    11. classParent interfaceExtends objectWithClassName
    the code

    You can find the code below, or you can obtain the most up-to-date version on github. Just head over to my shell-helpers repo and peek into the bash_setup_kde4_programming file.

  • » Attack of the shell helpers

    Mon, 03/02/2009 - 02:46

    Everyone who uses the command line regularly has a bunch of (at least for him) useful helper scripts. I now took the liberty to put mine on github for general consumption.

    You can find them at: http://github.com/milianw/shell-helpers/tree/master

    Some of these might be more useful than others, you decide :) Personally, I can’t live without the following:

    apupgrade
    a shortcut to update your Debian system with one command - no questions asked
    openurl
    opens a given URL in an already opened browser instance or starts a new browser session. Not only one browser is checked. I use it because firefox is slow to start and konqueror is blazingly fast to start. But when firefox is already open I want to use that.
    xerr
    shortcut for fast error checking in your Xorg log
    clipboard
    makes KDE4 Klipper contents available on the CLI (read and write access!)
    debug

    shortcut to start a GDB session: debug APP APP_ARGS is all you have to do. Its basically the same as doing:

    1. $ gdb APP
    2. > run APP_ARGS
  • » Take 2: Download script for springerlink.com Ebooks

    Tue, 02/24/2009 - 22:58

    Seems like quite some people are interested in my bash script for downloading ebooks from http://springerlink.com.

    That script has some quirks, the greatest of all that it was written in bash which makes it kind of hard to implement new features. And one which was requested was support for books which span multiple pages on SpringerLink.

    So here I present springer_download.py - a Python rewrite which should handle all the old links and some more. This is the very first program I’ve written in Python. And since it has to run on the Zedat servers it’s limited to Python 2.4.x without any fancy shmancy additions (a pity, since I’d love to use urlgrabber or pycurl).

    the script

    You can find the sources on GitHub: http://milianw.github.com/springer_download/

    I plan to put all my future code snippets in public repositories on GitHub. That way you can easily track changes and stay up to date. GitHub also has a nice “download” feature which you can use to get the current version. You can find my profile and my repositories at http://github.com/milianw

    Note: This script is intended to be run under Linux or other *nix’es which fulfill the requirements (Python 2.4.x, iconv and pdftk). Windows is not supported.

    TODO
    • introduce multithreading for faster / simultaneous downloads
    • add speed to progressbar
    • use progressbar in source-downloader
    • use one git-repo per project (makes links work properly)
  • » Download script for springerlink.com Ebooks

    Sat, 11/08/2008 - 17:28

    After a long period of silence I present you the following bash script for downloading books from http://springerlink.com. This is not a way to circumvent their login mechanisms, you will need proper rights to download books. But many students in Germany get free access to those ebooks via their universities. I for example study at the FU Berlin and put the script in my Zedat home folder and start the download process via SSH from home. Afterwards I download the tarball to my home system.

    Read on for the script.

  • » Access klipper clipboard on CLI under KDE4

    Wed, 08/13/2008 - 23:12

    Here’s a little script you can save in your path and do things like

    1. # paste current clipboard into file
    2. clipboard > "some_file"
    3. # copy some file into clipboard
    4. cat "some_file" | clipboard

    Actually I find it rather useful so I thought I will have to share it.

    Since KDE4 D-BUS is used throughout KDE and thus in Klipper as well. IMO they should really rework the output of dbus-send or add some more flags (what about --quiet). Well that’s the reason why the script below is somewhat long. But nothing a little bit of bash+awk magic couldn’t cope with:

    1. #!/bin/bash
    2.  
    3. # check for stdin
    4. # since we don't want to wait endlessly we set a timeout
    5. # a pity `read` only supports seconds and no fractions...
    6. read -t 1 stdin
    7. if [[ "$stdin" != "" ]]; then
    8. # get the rest of stdin
    9. stdin=$stdin$(cat)
    10. # oh, nice - user input! we set that as current
    11. # clipboard content
    12. dbus-send --type=method_call --dest=org.kde.klipper \
    13. /klipper org.kde.klipper.klipper.setClipboardContents \
    14. string:"$stdin"
    15. exit
    16. fi
    17.  
    18. # if we reach this point no user input was given and we
    19. # print out the current contents of the clipboard
    20. # note: I hate the output of dbus, dcop was much easier in that regard!
    21. dbus-send --print-reply --dest=org.kde.klipper /klipper \
    22. org.kde.klipper.klipper.getClipboardContents | awk '
    23. BEGIN { output = ""; }
    24. {
    25. if ( NR > 1 ) {
    26. output = output $0 "\n";
    27. }
    28. }
    29. END {
    30. print substr(output, 12, length(output) - 13);
    31. }'

    As usually, save the file (attached below) in your $PATH and make it executable.

    PS: Thanks to Martin Vidner for his article on D-BUS btw. - it gave me the proper dbus commands.

  • » profile.class.php

    Tue, 06/24/2008 - 18:29

    Every now and then I want to profile a given part of PHP code. For example I want to quickly check wether my current changeset to GeSHi works faster or is horribly slower. For a big change I’ll stick to Xdebug and KCachegrind. But for a quick overview? Overkill in my eyes.

    Say hello to profile.class.php, a simple timer class for PHP5 which you can use to get an overview about where how much time is spent. This is in no way a scientific method nor should you take the results of a single run as a basis for you decisions.

    I’ve set an emphasize on an easy API so you don’t have to pollute your code with arbitrary hoops and whistles.

    UPDATE: You can find the current updated source in the SVN repo of GeSHi.

  • » mp3dump take two - better audio quality

    Sat, 03/29/2008 - 16:29

    So just yesterday I’ve published a bash script which rips the audio stream of Flash Videos (*.flv) to mp3 format. It’s nice, fast and imo all-purpose. But I didn’t like the audio quality. Thus below you can find a second version of the script which is using mplayer and lame instead of ffmpeg. Usage and behaviour should be pretty much the same. Only the audio quality should be better on cost of a bit more computing.

    Since it relies on the fact that the input *.flv video already uses MP3 encoding for its audio stream this might not work for every flash file! Youtube works just fine though. You can find the script after the break, it’s also attached below. For usage / installation / more information read the old article.

    If you wonder why I reencode the audiodump with lame: The dumped mp3 file is considered by most (all?) audio players to be ~10x the length. A five minute video gets a 45 minute audio dumpfile. It plays fine but seeking is a mess. Reencoding fixes this. If you know an alternative which does not require reencoding or is generally faster - please drop a comment!

  • » Patching Kirocker Music Display for volume control via mouse scrolling

    Fri, 03/28/2008 - 16:32

    Kirocker is such a great application, it’s a pity the developer Sébastien Laoût has given up on it and is using Windows now!

    Usually I only use the kicker applet, the full screen window is nice for parties though. But I didn’t like the way the applet handles scroll events: It seeks (if possible). Since I rarely seek when listening to music I’d rather have the behaviour of the Amarok tray icon: volume control!

    I had a look inside the sources and found this part in src/coverdisplay.cpp:

    1. void CoverDisplay::wheelEvent(QWheelEvent *event)
    2. {
    3. if (areControlsShown()) {
    4. if (event->orientation() == Qt::Vertical) {
    5. PlayerInformation *infos = PlayerInformation::instance();
    6. if (infos->canSeek()) {
    7. int deltaSeconds = 10 * (event->delta() > 0 ? 1 : -1);
    8. m_infos->seekRelative(deltaSeconds);
    9. }
    10. } else {
    11. if (event->delta() > 0)
    12. AmarokApi::volumeUp();
    13. else
    14. AmarokApi::volumeDown();
    15. }
    16. }
    17. }

    As you can see it already supports volume control via scrolling! The thing is I’ve disable four-way scrolling for my MX1000. Thus I’ve simply swapped the if statements and now I’m really happy with Kirocker. Here’s the updated snippet:

    1. void CoverDisplay::wheelEvent(QWheelEvent *event)
    2. {
    3. if (areControlsShown()) {
    4. if (event->orientation() == Qt::Vertical) {
    5. if (event->delta() > 0)
    6. AmarokApi::volumeUp();
    7. else
    8. AmarokApi::volumeDown();
    9. } else {
    10. PlayerInformation *infos = PlayerInformation::instance();
    11. if (infos->canSeek()) {
    12. int deltaSeconds = 10 * (event->delta() > 0 ? 1 : -1);
    13. m_infos->seekRelative(deltaSeconds);
    14. }
    15. }
    16. }
    17. }

    Replace the old code, compile Kirocker, install it. Then restart kicker (killall kicker; sleep 1; kicker;) and Kirocker should accept scroll events in the way the Amarok tray icon does!

  • » mp3dump: Rip the audio stream of a Flash video to MP3

    Fri, 03/28/2008 - 00:03

    UPDATE: Also check out mp3dump part 2

    On some undefined occasion you might want to dump the audio stream of a flash file. This is how you do it:

    1. Get the *.flv, e.g. visit youtube with Konqueror and check /tmp for a file like FlashV5SQLt - this is your FLV.
    2. Install some dependencies: ffmpeg is required, mp3info and ecasound are optional but strongly recommended.
    3. Download the script below (it’s attached!) and save it inside your $PATH, remember how you’ve called it!
    4. I’ve saved the script inside ~/.bin which is inside my $PATH so all I have to do now is running it:

      mp3dump FlashV5SQLt "Foo Bar" "All Your Base Are Belong To Us"

      This would rip the audio stream of FlashV5SQLt to a file named Foo Bar - All Your Base Are Belong To Us.mp3 - with emulated stereo sound and basic MP3 tags (artist and title). Coolio!

  • » Reinstall Nvidia Driver

    Sat, 02/09/2008 - 03:41

    For those of you, who use the original NVIDIA display driver and have to reinstall it with every kernel update: Here is a little bashscript for your convenience.

    1. #!/bin/bash
    2. sudo /etc/init.d/kdm stop
    3. sudo chvt 1
    4. sudo sh ~/Downloads/NVIDIA-Linux-x86-*.run --ui='none' -aNq
    5. sudo /etc/init.d/kdm start
    6. sudo chvt 7

    Save it e.g. as ~/.bin/nv_reinst.sh, make it executable (chmod +x ~/.bin/nv_reinst.sh). Then put your NVIDIA driver (only the newest version please) into ~/Downloads/ (or change the path above). Now run your script.

    Attention: Save all your work, since kdm will be stopped! You’ll lose all unsaved work!