Tag Archives: code-dumping

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

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

ssh_mp32ogg.sh

‘cos those MP3 wont convert by themselves.


#!/bin/sh

# -----------------------------------------------------------------------------
# It is a simple script to convert mp3 files (one at a time) to ogg on my 
# other computer, because that's where the LAME codec is installed.
# Last edit: 5 June 2009
#
# It requires sox (with LAME installed) on the other computer.
#
# Usage: ssh_mp32ogg.sh [-s SERVER] [-u USERNAME] [-r BITRATE] infile outfile
# -----------------------------------------------------------------------------

mp3_fn=;
out_fn=;
server="CHIKUZA.KRYIE";	# default server
server_usr="ariel"	# default user @ server, must be exists
out_rate=4	# output bitrate to ~ 128

for cur_arg in "$@" ; do 
  if [ -z "$mp3_fn" ] && [ -f "$cur_arg" ] ; then
    mp3_fn="$cur_arg";
    echo "Input file is $mp3_fn";
  elif [ -z "$out_fn" ] && [ ! -z "$mp3_fn" ] ; then
    out_fn="$cur_arg";
    echo "Output file is $out_fn";
  fi
done

while getopts s:u:r: OPTION; do
  case "$OPTION" in
	s)	shift `echo "$OPTIND -1" | bc`;
		server="$OPTARG";
		;;
	u)	shift `echo "$OPTIND -1" | bc`;
		server_usr="$OPTARG";
		;;
	r)	shift `echo "$OPTIND -1" | bc`;
		out_rate=`echo "$OPTARG / 32" | bc`;
		;;
  esac
done

# do the format conversion
cat "$1" | ssh $server_usr@$server "sox -S -t mp3 - -C $out_rate -t ogg -" > "$2"

Leave a comment

Filed under Ilmu, Orang bego punya kegiatan

kidsxp_ico2png.py

Because I got ICO files and I want them in PNG.


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

import os, glob

# location of the files
sourceDir = "/media/yamazaki/Work/Pictures/Icons/KidsXP/"
# output directory
targetDir = "/tmp/kidsxp_png/"
# the real processor of this script: imagemagick 
convertCmd = "convert %s[9] -resize %s %s"
# which categories to process? all of 'em?
processDirs = ("actions", "apps", "devices", "filesystems", "mimetypes")
# extract it and move into known usable sizes 
knownSizes = ('16x16', '22x22', '32x32', '48x48', '64x64', '96x96', '128x128')

def processDir(path, thissize):
  print "Processing source path : %s" % path
  dummy, category = os.path.split(path)

  for item in glob.glob(path + '/*.ico'):
    dummy, itemName = os.path.split(item)
    tgtDir = os.path.join(targetDir, thissize, category, '')
    tgtName = itemName[:-3] + 'png' # "xyz.ico" filename to "xyz.png"
    
    print "Writing %20s -> %s" % (itemName, tgtDir + tgtName)
    if not os.path.exists(tgtDir):
      os.makedirs(tgtDir)
    
    cmd = convertCmd % (item, thissize, tgtDir + tgtName)
    
    # execute
    os.system(cmd)  # ooh! the horror!!
  ##
  print
##

for item in processDirs:
  s = sourceDir + item
  if os.path.isdir(s):
    for size in knownSizes:
      processDir(s, size)
  else:
    print "Skipping %s" % (s)
##

Leave a comment

Filed under Ilmu

wxPrintPreview HTML on my own frame (w/o wxPreviewFrame)

I’m in the mood to dump a few code. Here’s a small code to use user’s frame, for some reason, to preview a printout.

import wx
import wx.html

sHTML = \
"""
    <h1>Hello world!</h1>
"""

class PrintPreviewFrame (wx.Frame):

  def __init__(self, *args, **kwds):
    global sHTML
    wx.Frame.__init__(self, *args, **kwds)

    self.PO = wx.html.HtmlPrintout()
    self.PO.SetStandardFonts()
    self.PO.SetMargins()

    self.PPreview = wx.PyPrintPreview(self.PO, self.PO)
    self.PreviewC = wx.PreviewCanvas(self.PPreview, self)

    self.PO.SetHtmlText(sHTML)
    self.PPreview.AdjustScrollbars(self.PreviewC)
    self.PPreview.SetCanvas(self.PreviewC)
  ####
####


app = wx.PySimpleApp()
frm = PrintPreviewFrame(None)
frm.Show()
app.MainLoop()

*shiver*

Leave a comment

Filed under Ilmu