Tag Archives: programming

Oh Noes, I Wrote A Program

Long time no update, sorry but in the mean time I managed to get busy with life, ha! What? You think I write blogs all day long?

It’s an image viewer folks.

Yes, I can hear the collective cry of “great, yet another image viewer that the world needs” and you might disappointed that I haven’t yet complete my zillion dollars super fast kernel that will eclipse Linux and BSD alike and shock the entire IT world. Well, in my defense I would if I manage to start that project.. but in the mean time I hope you would forgive my insolence of NOT fulfilling your high standard o’ reader of my blog. I’m sure being a blog reader gives you the authority over some guy over the internet to do your bidding.

In case your sense of humor is out of wack, please read the last paragraph as a joke. Thank you.

Anyway, this is what it looks like:

Oh noes, a screenshot!

Oh noes, a screenshot!

If you wince hard enough you’ll see Gwenview, well IT IS one of the main reason I wrote this damn program. For now, its name is “Lihat” which depending if you care or not to try to pronounce it but really from my side, I don’t care if you can pronounce it at all. We’re both random dudes on the internet, you can call it whatever you want.

Why you say? Well because a) I can, b) it was started with “how hard could it be?”, and c) IrfanView looks like someone from east europe wrote a program in the 90’s and still haven’t bothered to update the interface of (maybe) the most used image viewer program for Windows.

Behold!

the program I mean, not Napoleon, mind you

Oh my god, its so seggssy!

For people who cares, fret not, I intend to release the code as open source. Besides, who makes millions from just an image viewer?

What is this? I don't even ..

What’s this? I don’t even ..

As you can see, I manage to put a useless feature here.

As you can see, I manage to put a useless feature here.

Please stay tuned, I’m working on it.. I’ll release it soon enough. If I haven’t upload it somewhere after a while, please bother me on the comment, or not.. I don’t care.

Advertisements

Leave a comment

Filed under Orang bego punya kegiatan

Fixing PySide UI Code-Generator Error

Today while coding a program I’m working on I got this ImportError exception. It says it cannot find a module. It is one of those modules that supposed to be created automatically every time I hit the magic make button.

So this shift my curiosity to the build process: what went wrong in the building process?

This is the message that got my attention:

An unexpected error occurred.make[1]: *** [../../sekolah/app/qt/inputasalpendidikandlg_ui.py] Error 1
make: *** [qtappres] Error 2

This message must be the clue to the ImportError exception thrown by Python interpreter. So basically Python can’t import it because the build unable to create it in the first place.

Clues

The next logical thing is to try creating the UI module by hand, with debug message, so:

$ pyside-uic -d resources/qt/ui/inputasalpendidikandlg.ui

gave me:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'resources/qt/ui/inputasalpendidikandlg.ui'
#
# Created: Tue Jan 14 23:33:06 2011
#      by: PySide uic UI code generator
#
# WARNING! All changes made in this file will be lost!

Traceback (most recent call last):
  File "/usr/bin/pyside-uic", line 75, in main
    options.indent)
  File "/usr/bin/pyside-uic", line 39, in generateUi
    pysideuic.compileUi(uifname, pyfile, execute, indent)
  File "/usr/lib/pymodules/python2.6/pysideuic/__init__.py", line 73, in compileUi
    winfo = compiler.UICompiler().compileUi(uifile, pyfile)
  File "/usr/lib/pymodules/python2.6/pysideuic/Compiler/compiler.py", line 37, in __init__
    CompilerCreatorPolicy())
  File "/usr/lib/pymodules/python2.6/pysideuic/uiparser.py", line 104, in __init__
    self.factory = QObjectCreator(creatorPolicy)
  File "/usr/lib/pymodules/python2.6/pysideuic/objcreator.py", line 79, in __init__
    raise WidgetPluginError, "%s: %s" % (e.__class__, str(e))
WidgetPluginError: : 'pluginType'

Hmm.. this is far more complicated than I thought. It seems, the faulty went straight to the PySide code. Because when I tried the same ui file with PyQt4’s pyuic4 it generate the module just fine.

Solving It

After reading the code on /usr/lib/pymodules/python2.6/pysideuic/objcreator.py and comparing it to PyQt4’s I found, semantically, they are doing the same thing. So the code is good, unless I missed something, which is hardly possible because both code are written nicely.

Now I know that this thing load plug-ins, by means of reading Python modules in a certain path. Putting some default variables and taking it back from the plug-in and basically do something against that. Nothing uncanny here, so what’s the big deal?

So I browse to the directory where it load its plug-ins: /usr/lib/pymodules/python2.6/pysideuic/widget-plugins/.

This is what I found:

$ ls
__init__.py	__init__.pyc	qtwebkit.py	qtwebkit.pyc

Aha! The __init__.py module being nothing more than a empty module (with its “compiled” __init__.pyc) is the culprit here. The objcreator.py executes __init__.py causing exception because the loader code expect variable pluginType to be defined by the plug-in, which in this case is an empty file.

So the easiest solution is to remove __init__.py and __init__.pyc from widget-plugins directory. At first I move the two to /tmp/ just in case something break badly I can put it back in, but after seeing make working as intended I delete them immediately.

Another alternative is to modify objcreator.py to remove __init__.py from “plugins” after enumerating files from the widget-plugins directory.

Leave a comment

Filed under Ilmu, Orang bego punya kegiatan

Multiple Items Existence Check in Python

This is new for me, sometimes I want to do this:

aList = [1, 2, 3, 5, 7];

if (2, 3) in aList:   # I want to check whether 2 and 3 is in aList
    doSomethingCool( );

that code right there is a logical error, I thought the interpreter will search aList for items inside the tuple while the truth is that it will look for the existence of a tuple with 2 and 3 in it inside aList.

Thanks to some guy’s code which I happened to stumble upon, now I know that I can use all( ) function to do that. A leaner solution than the tedious enumeration of all items and checking it one by one. Here’s a demonstration:

# instead of this ..
allFound = True;
for num in (2, 3):
    if not (num in aList):
        allFound = False;
        break;
if allFound:
    doSomethingCool( );

# now I can use this ...
if all(num in aList for num in (2, 3)):
    doSomethingCool( );

wow, look at that! It makes perfect sense because most of the gist in that sample is a list comprehension and all( ) made up the invisible AND between the list items. Another similar function to all( ) is the appropriately-named any( ) which having the effect of OR instead of AND.

Leave a comment

Filed under Ilmu

Pascal, Python, C

A quick question: How many days you can go writing code alternately in three different programming language without accidentally mixing them?

My answer is 3 days. I caught writing def, return on Pascal file, := on C and Python files, and … for .. in in C. So it is true, sometimes you can type faster than your brain remembering minor detail called syntax.

Leave a comment

Filed under Orang bego punya kegiatan, Pendapat gak penting

Analytic Hierarchy Processs (AHP) in Python

One day I have to implement AHP in Python, so this is what I came up with: a decision.py and a test unit called decision_test.py to demonstrate its usage.

Due to this WordPress.com account limitation I have to upload as ODT files, but you can rename them by replacing “-py.odt” into “.py” in the filename. Sorry for the inconvenience.

1 Comment

Filed under Ilmu

Bahasa Pemrograman “Go” dari Google

Holy crap! A new programming language from Google!

http://golang.org/

Busyet, gw mesti lihat yang satu ini. Dari contoh program yang diberikan nampaknya Python-ish dengan rasa C. Saya bersemangat dengan prospek bahasa ini, bukan karena nama besar Google dibelakangnya tapi karena sederet feature yang masih “katanya” (soalnya belum coba sendiri :D). Baguslah, saya sedang tunggu-tunggu yang seperti ini: fleksibilitas Python dengan power dan workflow C.

Yang paling penting menurut gw, ini bukan interpreted language! Kalau memang betul bisa kompilasi dengan cepat, seperti Object Pascal, maka asik juga bisa menyaingi Python yang (IMHO) bagus tapi sayangnya interpreted. Artinya Go, dari kesan yang gw dapat setelah membaca sekilas, memiliki kecepatan kompilasi seperti Object Pascal, menghasilkan native object bukan intermediate yang dijalankan oleh VM seperti Python atau Java, tapi dengan sifat ekspresif seperti Python.

Hmm.. very interesting. Pertanyaannya sekarang, apakah bahasa ini akan “sukses”?

Leave a comment

Filed under Uncategorized

updateln.py

A Python script to update links under a path to use new prefix.


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, sys, getopt;
options = {'start': None, 'oprefix': None, 'nprefix': None, 'simulate': True};

class PathError (Exception):
  pass;

def ShowUsage():
  progname = os.path.split(sys.argv[0])[1];
  print progname;
  print '-'*len(progname)
  print " Usage: %s [-w] [-s startpath] -o oldprefix -n newprefix\n" % progname;
  print " Parameters: "
  print " -w, --write       Dont run the program run in simulation mode.\n";
  print " -s, --start-path  Use custom starting directory.\n";
  print " -o, --old-prefix  Find link(s) with prefix as specified by this parameter.\n";
  print " -n, --new-prefix  New prefix for the offending link(s) to use.\n";
####  
  
def GetOptions():
  global options;
  ret = 0;
  
  arguments = sys.argv[1:];
  
  try:
    wnt, dummy = getopt.getopt(arguments, "o:n:s:w", ["old-prefix=",
                    "new-prefix=", "start-path=", "write"]);
    for name, val in wnt:
      if name in ('-o', '--old-prefix'):
        options['oprefix'] = val;
      elif name in ('-n', '--new-prefix'):
        options['nprefix'] = val;
      elif name in ('-s', '--start-path'):
        options['start'] = val;
      elif name in ('-w', '--write'):
        options['simulate'] = False;
    ##
        
    if options['start'] == None:
      options['start'] = os.getcwd();
  except getopt.GetoptError:
    ret = -1;
  ##
  
  if (options['oprefix'] == None) or (options['nprefix'] == None): ret = -1;  
  if ret != -1:
    print "Start      : %s" % options['start'];
    print "Old prefix : %s" % options['oprefix'];
    print "New prefix : %s" % options['nprefix'];
    if options['simulate'] == False:  print "WARNING    : This program may change links.";
    print;
  ##
  
  return ret;
####

def ProcessPath(curPath, recursive):
  proccount = 0;
  files = os.listdir(curPath);
  
  if len(files) > 0:
    print "Examining %s" % curPath;

  for entry in files:
    curFile = os.path.join(curPath, entry);
    
    if os.path.islink(curFile):
      linkPath = os.readlink(curFile);
      if linkPath.find(options['oprefix']) == 0:
        # we need to update this one
        newLinkPath = linkPath.replace(options['oprefix'], options['nprefix'], 
                                      1);
        print "Fixing %s\n   Old path: %s\n   New path: %s" % (curFile, 
          linkPath, newLinkPath);
        
        if options['simulate'] == False:         
          # these two lines will modify/regenerate the symbolic link        
          os.unlink(curFile);
          os.symlink(newLinkPath, curFile);
          proccount += 1;
        ##
      else:
        # good link, skip it
        pass;
    elif os.path.isdir( curFile ) and recursive:
      proccount += ProcessPath(curFile, recursive);
  ##    
  
  return proccount;
####

def main():   
    if GetOptions() == 0:
      i = ProcessPath(options['start'], True);
      print;
      print ["Nothing processed by this program", \
             "There are %s link(s) processed" % i][i > 0] + '.';
    else:
      ShowUsage();
####

if __name__ == '__main__':
    main();
##

Leave a comment

Filed under Ilmu

Firebird’s UNION use for multipe SELECT result

I would like to post this one just in case I’ll need it someday in the future.

UNION can be used to ‘append’ multiple SELECT result into one stream of rows. This is not a JOIN. There are few situations where a UNION should be used to get a certain result. Here’s one:

I’ve got a table, a view to be exact, like this :


V_EMPLOYEERELATION
+------------+-------------+----------+
|  EMPLOYEE  |  EMPLOYEE_2 | RELATION |
+------------+-------------+----------+
|  101       |  203        | 45       |
+------------+-------------+----------+
|  104       |  108        | 40       |
+------------+-------------+----------+
|  102       |  79         | 45       |
+------------+-------------+----------+

As you can see this is a table that stores relationship between employees. The task is to get all employee entries having a certain Relation ID.

Right, now here’s the query:


SELECT EMPLOYEE AS "ID" FROM V_EMPLOYEERELATION WHERE RELATION = %d
UNION
SELECT EMPLOYEE_2 AS "ID" FROM V_EMPLOYEERELATION WHERE RELATION = %d';

This query will return rows of employee ID satisfying a relation ID. If you know Python or Delphi, you might know the formatting string there. For people who don’t know, the %d is a replacement for an integer value. In this example I’m using integer as foreign key to a RELATION table.

One can use this SQL query like this:


const
  SQUERY_GETEMP = 
  'SELECT EMPLOYEE AS "ID" FROM V_EMPLOYEERELATION WHERE RELATION = %d ' +
  'UNION ' +
  'SELECT EMPLOYEE_2 AS "ID" FROM V_EMPLOYEERELATION WHERE RELATION = %d';

...
// RunQuery is a function that takes string SQL query and a dataset, returning an integer
if ( RunQuery(Format(SQUERY_GETEMP, [iRelationID, iRelationID]), Table1) = 0 ) then
begin
  while (not Table1.EOF) do
   ...

Please note that UNIONs requires each ‘source-stream’ (a.k.a SELECT statements) to have the same fields number, type and size.

Leave a comment

Filed under Ilmu

Back to C++, in Engrish

cee.pngI’m back to C++, at least for now. I’m in a process re-writing some of my (personal) apps to C using MFC (or wxWidgets). I’m doing this because I’m looking forward to code in C++ a lot more in the future. I’m quite satisfied with my current knowledge of Delphi, and frankly understanding Delphi’s (Object Pascal) programming helps my (re)transition to C++.

I worked my way through C++ basic (again) for a few hours, and some other quirks in C and how to do basic things done in C++. I’m using my free copy of VS.NET express, but that’ll (probably) change soon as I’m downloading wxDev C++. From the words I’ve heard about it, it sounds like ‘okay’ and might stand a chance as a good alternative for someone like me –someone coming from GUI-based IDE.

From my experience (so far) I realized that Delphi really has it’s own good points, and I did struggle with C++ to ‘do things’ like the way I used to in Delphi. As it turns out although not actually the same, now I know how to ‘do things’ C++ way. And these C++ ways of ‘doing things’ makes me really appreciate Delphi.

I guess it’s true then, you’ll appreciate the things you don’t have even more than the ones you have.

Nah, I guess that’ll change too. I’ll see where this fascinating world of C will take me.

Leave a comment

Filed under Orang bego punya kegiatan