Thursday, August 20, 2009

Thursday, August 13, 2009

General shape drawing application JShapeMaster (Jython & JFace example)

Links:
  • Read here how to setup environment.
  • If you need to check on SWT/JFace API here is the proper place to do so.

New things you will learn in this example: Rectangle, Path, Canvas, Concept of Abstract Base Class

Rectangle class (org.eclipse.swt.graphics.Rectangle)

Fields
int xthe x coordinate of the rectangle
int ythe y coordinate of the rectangle
int widththe width of the rectangle
int heightthe height of the rectangle
Constructors
Rectangle(int x, int y, int width, int height)Construct a new instance of this class given the x, y, width and height values.
Methods
void add(Rectangle rect)Destructively replaces the x, y, width and height values in the receiver with ones which represent the union of the rectangles specified by the receiver and the given rectangle.
boolean contains(int x, int y)Returns true if the point specified by the arguments is inside the area specified by the receiver, and false otherwise.
boolean contains(Point pt)Returns true if the given point is inside the area specified by the receiver, and false otherwise.
void intersect(Rectangle rect)Destructively replaces the x, y, width and height values in the receiver with ones which represent the intersection of the rectangles specified by the receiver and the given rectangle.
Rectangle intersection(Rectangle rect)Returns a new rectangle which represents the intersection of the receiver and the given rectangle.
boolean intersects(int x, int y, int width, int height)Returns true if the rectangle described by the arguments intersects with the receiver and false otherwise.
boolean intersects(Rectangle rect)Returns true if the given rectangle intersects with the receiver and false otherwise.
boolean isEmpty()Returns true if the receiver does not cover any area in the (x, y) coordinate plane, and false if the receiver does cover some area in the plane.
Rectangle union(Rectangle rect)Returns a new rectangle which represents the union of the receiver and the given rectangle.

Path class (org.eclipse.swt.graphics.Path)

Constructors
Path(Device device)Constructs a new empty Path.
Path(Device device, PathData data)Constructs a new Path with the specified PathData.
Path(Device device, Path path, float flatness)Constructs a new Path that is a copy of path.
Methods
void addArc(float x, float y, float width, float height, float startAngle, float arcAngle)Adds to the receiver a circular or elliptical arc that lies within the specified rectangular area.
void addPath(Path path)Adds to the receiver the path described by the parameter.
void addRectangle(float x, float y, float width, float height)Adds to the receiver the rectangle specified by x, y, width and height.
void addString(String string, float x, float y, Font font)Adds to the receiver the pattern of glyphs generated by drawing the given string using the given font starting at the point (x, y).
void close()Closes the current sub path by adding to the receiver a line from the current point of the path back to the starting point of the sub path.
boolean contains(float x, float y, GC gc, boolean outline)Returns true if the specified point is contained by the receiver and false otherwise.
void cubicTo(float cx1, float cy1, float cx2, float cy2, float x, float y)Adds to the receiver a cubic bezier curve based on the parameters.
void getBounds(float[] bounds)Replaces the first four elements in the parameter with values that describe the smallest rectangle that will completely contain the receiver (i.e. the bounding box).
void getCurrentPoint(float[] point)Replaces the first two elements in the parameter with values that describe the current point of the path.
PathData getPathData()Returns a device independent representation of the receiver.
boolean isDisposed()Returns true if the Path has been disposed, and false otherwise.
void lineTo(float x, float y)Adds to the receiver a line from the current point to the point specified by (x, y).
void moveTo(float x, float y)Sets the current point of the receiver to the point specified by (x, y).
void quadTo(float cx, float cy, float x, float y)Adds to the receiver a quadratic curve based on the parameters.

Canvas class (org.eclipse.swt.widgets.Canvas)

Constructors
Canvas(Composite parent, int style)Constructs a new instance of this class given its parent and a style value describing its behavior and appearance.
Methods
void redraw()Causes the entire bounds of the receiver to be marked as needing to be redrawn.
void redraw(int x, int y, int width, int height, boolean all)Causes the rectangular area of the receiver specified by the arguments to be marked as needing to be redrawn.

Concept of Abstract Base Class

Abstract base classes are useful in that they can be used to define and enforce a contract: a set of methods which all classes that will subclass it must support. Disallow instantiating of abstract class helps to ensure program correctness.

class AbstractBase:
    def __init__(self):
        raise NotImplementedError, "Could not instantiate abstract class (Subclass it)"
Drawing on Canvas

Canvas control is specifically designed for drawing operations. You could make use of this control in two ways: you could add listener to it or subclass it. In our example we will use a listener approach. To reducing flickering I recommend to pass SWT.DOUBLE_BUFFERED style bite into Canvas constructor.

We will start by designing abstract shape class

Well every shape has position (two coordinates x and y) and size (x – width and y -height). Shapes also have border and fill color. Every shape should be able to draw itself. Here it goes our shape class:

class AbstractShape:
    def __init__(self, x, y, width, height):
        self._path = None
        self._position = Point(x, y)
        self._size = Point(width, height)
        self._fillColor = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN)
        self._borderColor = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_BLUE)
    
    def getBounds(self):
        b = zeros(4, 'f')
        self._path.getBounds(b)
        # Thanks Frank Wierzbicki (http://stackoverflow.com/users/78599/frank-wierzbicki)
        # and Charlie Groves (http://stackoverflow.com/users/157016/charlie-groves)
        # for pointing out * 'explode operator'
        return Rectangle(*[int(round(x)) for x in b])
    
    def createShape(self):
        raise NotImplementedError, "Abstract method implement it in Subclass"

    def setPosition(self, l):
        self._position = l

    def setSize(self, s):
        self._size = s

    def draw(self, gc):
        if (self._path):
            self._path.dispose()
        
        self._path = Path(Display.getCurrent())
        self.createShape()

        gc.setAntialias(SWT.ON) 
        gc.setBackground(self._fillColor)
        gc.setForeground(self._borderColor)
        gc.fillPath(self._path)
        gc.drawPath(self._path)

Every concrete class will properly implement createShape() method. Let's look at createShape() method of RectangleShape class:

class RectangleShape(AbstractShape):
    def createShape(self):
        self._path.addRectangle(self._position.x,
                                 self._position.y,
                                 self._size.x,
                                 self._size.y)
code
"""
General shape drawing application JShapeMaster (Jython & JFace example)
GUID of this code snippet: 12aa740f-5bb5-40be-8409-2c0a01ef37cf
[ extends code snippet: None ]
Author: Darius Kucinskas (c) 2008-2009
Email: d[dot]kucinskas[eta]gmail[dot]com
Blog: http://blog-of-darius.blogspot.com/
License: GPL
"""

from org.eclipse.swt import *
from org.eclipse.swt.SWT import *
from org.eclipse.swt.widgets import *
from org.eclipse.swt.layout import *
from org.eclipse.jface.window import *
from org.eclipse.jface.action import *
from org.eclipse.jface.resource import *
from org.eclipse.swt.graphics import *
from org.eclipse.swt.events import *
from jarray import array, zeros

class AbstractShape:
    def __init__(self, x, y, width, height):
        self._path = None
        self._position = Point(x, y)
        self._size = Point(width, height)
        self._fillColor = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN)
        self._borderColor = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_BLUE)
    
    def getBounds(self):
        b = zeros(4, 'f')
        self._path.getBounds(b)
        # Thanks Frank Wierzbicki (http://stackoverflow.com/users/78599/frank-wierzbicki)
        # and Charlie Groves (http://stackoverflow.com/users/157016/charlie-groves)
        # for pointing out * 'explode operator'
        return Rectangle(*[int(round(x)) for x in b])
    
    def createShape(self):
        raise NotImplementedError, "Abstract method implement it in Subclass"

    def setPosition(self, l):
        self._position = l

    def setSize(self, s):
        self._size = s

    def draw(self, gc):
        if (self._path):
            self._path.dispose()
        
        self._path = Path(Display.getCurrent())
        self.createShape()

        gc.setAntialias(SWT.ON) 
        gc.setBackground(self._fillColor)
        gc.setForeground(self._borderColor)
        gc.fillPath(self._path)
        gc.drawPath(self._path)

class RectangleShape(AbstractShape):
    def createShape(self):
        self._path.addRectangle(self._position.x,
                                 self._position.y,
                                 self._size.x,
                                 self._size.y)

class CanvasPaintListener(Listener):
    def __init__(self, app):
        self.app = app

    def handleEvent(self, e):
        self.app.shape.draw(e.gc)

class CanvasMouseListener(MouseListener):
    def __init__(self, app):
        self.app = app

    def mouseDoubleClick(self, evt):
        pass

    def mouseDown(self, evt):
        self.app.isDraging = True
        if (self.app.shape.getBounds().contains(evt.x, evt.y) == True):
            self.app.clickOffsetX = evt.x - self.app.shape.getBounds().x
            self.app.clickOffsetY = evt.y - self.app.shape.getBounds().y

    def mouseUp(self, evt):
        self.app.isDraging = False

class CanvasMouseMoveListener(MouseMoveListener):
    def __init__(self, app):
        self.app = app

    def mouseMove(self, evt):
        if (self.app.isDraging == True and
            self.app.shape.getBounds().contains(evt.x, evt.y) == True):
        
            oldRect = self.app.shape.getBounds()
            self.app.shape.setPosition(Point(evt.x - self.app.clickOffsetX,
                                             evt.y - self.app.clickOffsetY))
            uRect = oldRect.union(self.app.shape.getBounds())
            self.app.canvas.redraw(uRect.x - 1, uRect.y - 1, uRect.width + 3, uRect.height + 3, True)

# Skip this for now
# Draw glider emblem (I use it as icon for this example)
def drawIcon(display):
    image = Image(display, 16, 16)
    gc = GC(image)

    gc.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT))
    gc.fillRectangle(0, 0, 16, 16)

    gc.setBackground(Color(display, 193, 39, 45))
    gc.fillRectangle( 1, 11, 4, 4)
    gc.fillRectangle( 6, 11, 4, 4)
    gc.fillRectangle(11, 11, 4, 4)
    gc.fillRectangle(11,  6, 4, 4)
    gc.fillRectangle( 6,  1, 4, 4)

    gc.setBackground(Color(display, 253, 185, 19))
    gc.fillRectangle( 1,  1, 4, 4)
    gc.fillRectangle( 1,  6, 4, 4)
    gc.fillRectangle(11,  1, 4, 4)

    gc.setBackground(Color(display, 0, 106, 68))
    gc.fillRectangle( 6,  6, 4, 4)

    gc.dispose()
    return image

class App(ApplicationWindow):
    """ Main class for JFace application drived from ApplicationWindow class """

    # add static image registry
    imageRegistry = None

    # add class method for image registry
    @classmethod
    def getImageRegistry(cls):
        if (not cls.imageRegistry):
            cls.imageRegistry = ImageRegistry()
            cls.imageRegistry.put("app.icon", ImageDescriptor.createFromImage(drawIcon(Display.getCurrent())))
        
        return cls.imageRegistry

    def __init__(self, shell):
        """ application constructor """
        # let parent class to do it's stuff first
        ApplicationWindow.__init__(self, shell)

        self.canvas = None
        self.shape = RectangleShape(50, 50, 100, 100)
        self.isDraging = False
        self.clickOffsetX = 0
        self.clickOffsetY = 0
    
    def dispose(self):
        """ dispose resources here """
        pass
    
    def createContents(self, parent):
        self.shell.setImage(drawIcon(Display.getCurrent()))
        self.shell.text = 'JShapeMaster (Jython & JFace example)'
        self.shell.setMinimumSize(650, 480)

        # create canvas for drawing
        self.canvas = Canvas(parent, SWT.BORDER|SWT.DOUBLE_BUFFERED|SWT.NO_REDRAW_RESIZE|SWT.NO_MERGE_PAINTS)
        self.canvas.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT))
        self.canvas.setLayoutData(GridData(SWT.FILL, SWT.FILL, True, True, 1, 1))

        # add listeners to canvas, so we could react to events
        self.canvas.addListener(SWT.Paint, CanvasPaintListener(self))
        ##self.canvas.addListener(SWT.Resize, CanvasResizeListener(self))
        self.canvas.addMouseListener(CanvasMouseListener(self))
        self.canvas.addMouseMoveListener(CanvasMouseMoveListener(self))

        return self.canvas

if __name__ == "__main__":
    """ The entry point for our application """
    display = Display()
    shell = Shell(display)

    app = App(shell)
    # Voodoo of SWT message loop
    try:
        app.setBlockOnOpen(True)
        app.open()
    finally:
        if app != None:
            app.dispose()

    display.dispose()
So you now have learned basics of animation of canvas.

Monday, August 10, 2009

How to add optional filter parameters to Stored Procedure

Sometimes you need to use optional parameters to filter results of select or other statement in stored procedure. Here it goes example I think it is self explaining...
--
-- Adding optional filter parameters to Stored Procedure
-- GUID of this code snippet: 80901808-027c-47a8-81de-472d58281392
-- [ extends code snippet: None ]
-- Author: Darius Kucinskas (c) 2008-2009
-- Email: d[dot]kucinskas[eta]gmail[dot]com
-- Blog: http://blog-of-darius.blogspot.com/
-- License: GPL
--
CREATE PROCEDURE ShapeReport
(
@min_width int = NULL,
@max_width int = NULL,
@min_height int = NULL,
@max_height int = NULL,
@type int = NULL
)
AS
SELECT type, count(*) [count] 
FROM shape 
WHERE (@min_width IS NULL OR (width >= @min_width)) 
AND (@max_width IS NULL OR (width <= @max_width)) 
AND (@min_height IS NULL OR (height >= @min_height))
AND (@max_height IS NULL OR (height <= @max_height))
AND (@type IS NULL OR (type = @type))
GROUP BY type
HAVING COUNT(*) >= 1 
ORDER BY [count] DESC

Monday, August 3, 2009

Installing Apache Tomcat on Windows

Download Apache Tomcat

Download apache-tomcat-X.Y.ZZ.zip archive from http://tomcat.apache.org/ Extract archive to selected path for example: d:\java\apache-tomcat-6.0.20

Set Java Environment

Check your java version: "java -version" My Computer -> System Properties -> Environment Variables -> set JAVA_HOME to C:\Program Files\Java\jdkX.Y.Z_ZZ and set JRE_HOME to C:\Program Files\Java\jdkX.Y.Z_ZZ\jre

Start Apache Tomcat

From start menu -> Run and enter "cmd" Navigate to you Apache Tomcat bin directory for example: "d:" "cd D:\java\apache-tomcat-6.0.20\bin" "start apach-tomcat" "startup.bat" you should see something similar to the following picture:

Open your browser

Navigate to address: http://localhost:8080 you should see result page like one in the following screen shot:

Troubleshooting Apache Tomcat install

Check if 8080 port is free run "netstat -an" and check if nothing listens to port no. 8080 if some program uses 8080 port you can check which by using Microsoft tool TCPView

Best Regards,
Darius

P.S. What ever you do try to have fun ;)

Monday, July 20, 2009

Software Engineering: Dead?

The guys and gals who show up every day eager to hone their craft, who are passionate about building stuff that matters to them, and perhaps in some small way, to the rest of the world -- those are the people and projects that will ultimately succeed. Everything else is just noise. (Jeff Atwood) Read it here.

Friday, June 19, 2009

Rapid application development with Jython and JFace (part VI - First application reviewed)

New things to learn in this part: Tree, SashForm, DirectoryDialog, TreeViewer, ITreeContentProvider, LabelProvider, ISelectionChangedListener.

Tree control

Tree control is used to display a hierarchy of items and issues notification when an item in the hierarchy is selected. We'll use this control in our application to display hierarchy of directories and files. User will be able to select image file and then we'll display selected image.

SashFrom

Divides client are into independent areas. We'll use it to divide application screen into two peaces: tree of files and image view area.

DirectoryDialog

Directory selection dialog.

TreeViewer, ITreeContentProvider, LabelProvider, ISelectionChangedListener

These classes help to customize and simplify control of tree control. TreeViewer – sits on top of tree control and provides easy control of it, less of manual control is needed. ITreeContentProvider – provides items that should be displayed in tree control. LabelProvider – controls how items should apier in tree control. ISelectionChangedListener – tels what actions should be taken on item selection in tree control.

Explanation of source code

Create SashFrom as top window and divide client area of it into two peaces: treePanel (displays tree control) and imagePanel (displays selected image). Tree will get 30% of application window and image will get 70% of application window.

mainForm = SashForm(parent, SWT.HORIZONTAL | SWT.NULL)
treePanel = Composite(mainForm, SWT.NONE)
imagePanel = Composite(mainForm, SWT.NONE)
mainForm.setWeights([30, 70])
In treePanel we should put tree control.
self.treeViewer = TreeViewer(treePanel, SWT.BORDER | SWT.VIRTUAL)
We'll add ITreeContentProvider, LabelProvider, IselectionChangedListener to it.
self.treeViewer.setContentProvider(FileTreeContentProvider())
self.treeViewer.setLabelProvider(FileTreeLabelProvider())
self.treeViewer.addSelectionChangedListener(FileTreeSelectionChangedListener(self))
We'll add canvas to imagePanel.
self.canvas = Canvas(imagePanel, SWT.BORDER | SWT.NO_BACKGROUND|SWT.NO_REDRAW_RESIZE|SWT.V_SCROLL|SWT.H_SCROLL)

Class FileTreeContentProvider implements ITreeContentProvider

We search directory for directories and files and add those to tree.

Class FileTreeLabelProvider extends LabelProvider

We display short name of directory or file in tree control. If item is directory we are displaying directory image. If item is file we are displaying picture image.

Class FileTreeSelectionChangedListener implements ISelectionChangedListener

Then user selects item which is file we will display it in canvas.

Full Code

"""
Not so dumb image displaying application JPictureMaster II (Jython & JFace example)
Part VI - First application reviewed
GUID of this code snippet: 979fa00c-3001-4c24-b04d-f41d06f1d6d2
[ extends code snippet: eef8f89a-d1d6-4211-9063-ba4c736eb620 ]
Author: Darius Kucinskas (c) 2008-2009
Email: d[dot]kucinskas[eta]gmail[dot]com
Blog: http://blog-of-darius.blogspot.com/
License: GPL
"""

from org.eclipse.swt import *
from org.eclipse.swt.SWT import *
from org.eclipse.swt.widgets import *
from org.eclipse.swt.layout import *
from org.eclipse.jface.window import *
from org.eclipse.jface.action import *
from org.eclipse.jface.resource import *
from org.eclipse.swt.graphics import *
from org.eclipse.swt.custom import SashForm
from org.eclipse.jface.viewers import TreeViewer
from org.eclipse.jface.viewers import ITreeContentProvider
from org.eclipse.jface.viewers import LabelProvider
from org.eclipse.jface.viewers import ISelectionChangedListener
from java.lang import Math
from java.io import File
import jarray

# Skip this for now
# Draw glider emblem (I use it as icon for this example)
def drawIcon(display):
    image = Image(display, 16, 16)
    gc = GC(image)

    gc.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT))
    gc.fillRectangle(0, 0, 16, 16)

    gc.setBackground(Color(display, 193, 39, 45))
    gc.fillRectangle( 1, 11, 4, 4)
    gc.fillRectangle( 6, 11, 4, 4)
    gc.fillRectangle(11, 11, 4, 4)
    gc.fillRectangle(11,  6, 4, 4)
    gc.fillRectangle( 6,  1, 4, 4)

    gc.setBackground(Color(display, 253, 185, 19))
    gc.fillRectangle( 1,  1, 4, 4)
    gc.fillRectangle( 1,  6, 4, 4)
    gc.fillRectangle(11,  1, 4, 4)

    gc.setBackground(Color(display, 0, 106, 68))
    gc.fillRectangle( 6,  6, 4, 4)

    gc.dispose()
    return image

class HBarListener(Listener):
    """ Listener for horizontal scroll events """

    def __init__(self, app):
        self.app = app

    def handleEvent(self, e):        
        selection = self.app.canvas.getHorizontalBar().getSelection()
        x = -selection - self.app.origin.x
        rect = self.app.image.getBounds()
        self.app.canvas.scroll(x, 0, 0, 0, rect.width, rect.height, False)
        self.app.origin.x = -selection

class VBarListener(HBarListener):
    """ Listener for vertical scroll events """

    def handleEvent(self, e):        
        selection = self.app.canvas.getVerticalBar().getSelection()
        y = -selection - self.app.origin.y
        rect = self.app.image.getBounds()
        self.app.canvas.scroll(0, y, 0, 0, rect.width, rect.height, False)
        self.app.origin.y = -selection

class CanvasPaintListener(HBarListener):
    """ Listener for paint events """

    def handleEvent(self, e):
        gc = e.gc
        gc.drawImage(self.app.image, self.app.origin.x, self.app.origin.y)
        rect = self.app.image.getBounds()
        client = self.app.canvas.getClientArea()
        marginW = client.width - rect.width
        if (marginW > 0):
            gc.fillRectangle(rect.width, 0, marginW, client.height)

        marginH = client.height - rect.height
        if (marginH > 0):
            gc.fillRectangle(0, rect.height, client.width, marginH)

class CanvasResizeListener(HBarListener):
    """ Listener for resize events """

    def handleEvent(self, e):
        self.app.newOrResizeImage()
        self.app.canvas.redraw()

class ExitAction(Action):
    """ This is simple quit application action.

    All action classes should inherit from Action (org.eclipse.jface.action.Action) class.
    """

    def __init__(self, app):
        """ constructor of ExitAction

        arguments:
        app - in order to do anything useful I am passing 
        object of my application.    
        """

        self.app = app
        self.text = "E&xit@Ctrl+Q"
        self.toolTipText = "Exit the application"
        self.imageDescriptor = App.getImageRegistry().getDescriptor("file.exit")

    def run(self):
        """ run() method of action. Every action class should have one.

        This time it closes application.
        """

        if self.app != None:
            self.app.close()

class OpenDirectoryAction(Action):
    """ Simple open image action """

    def __init__(self, app):
        self.app = app
        self.text = "O&pen@Ctrl+O"
        self.toolTipText = "Open directiory and scan it for images"
        self.imageDescriptor = App.getImageRegistry().getDescriptor("file.open")

    def run(self):
        # this code shows DirectoryDialog usage
        dlg = DirectoryDialog(self.app.shell, SWT.OPEN)
        dlg.filterPath = "."
        dlg.text = "Select directory to scan for images"
        dir = dlg.open()     

        if (not dir):
            return

        self.app.treeViewer.setInput(File(dir))
        self.app.treeViewer.refresh()

class MainMenuManager(MenuManager):
    """ MenuManager is responsible for constructing  menu """

    def __init__(self, app):
        """constructor of MainMenuManager

        arguments:
        app - in order to do anything useful I am passing 
        object of my application.    
        """
        # let parent class to do it's stuff first
        MenuManager.__init__(self)
        self.app = app

    def createMainMenu(self):
        """ creates menu """

        mainMenu = MenuManager("")
        fileMenu = MenuManager("&File")
        mainMenu.add(fileMenu)
        # add Exit action to file menu 
        fileMenu.add(ExitAction(self.app))
        fileMenu.add(OpenDirectoryAction(self.app))
        return mainMenu

class MainToolbarManager(ToolBarManager):
    """ """
    def __init__(self, app):
        """construcotr of MainToolbar

        arguments:
        app - in order to do anything useful I am passing 
        object of my application.    
        """
        # let parent class to do it's stuff first
        ToolBarManager.__init__(self)
        self.app = app        

    def createMainToolBar(self, style):
        """ add items to toolbar """

        mainToolBar = ToolBarManager(style)

        # add Exit action to toolbar 
        mainToolBar.add(ExitAction(self.app))
        mainToolBar.add(OpenDirectoryAction(self.app))
 return mainToolBar

class FileTreeContentProvider(ITreeContentProvider):
    def getChildren(self, element):
        if (not element):
            return None

        kids = element.listFiles()
        return kids

    def getElements(self, element):
        return self.getChildren(element)

    def hasChildren(self, element):
        if (not element):
            return False

        kids = self.getChildren(element)
        if (not kids):
            return False

        if (len(kids) < 1):
            return False

        return True

    def getParent(self, element):
        return element.getParent()

    def dispose(self):
        pass

    def inputChanged(self, viewer, old_input, new_input):
        pass

class FileTreeLabelProvider(LabelProvider):
    def getImage(self, element):
        if (element.isDirectory()):
            return App.getImageRegistry().getDescriptor("file.open").createImage()

        return App.getImageRegistry().getDescriptor("file.image").createImage()

    def getText(self, element):
        return element.getName()

class FileTreeSelectionChangedListener(ISelectionChangedListener):
    def __init__(self, app):
        self.app = app

    def selectionChanged(self, e):
        selection = e.getSelection()

        file = selection.getFirstElement()
        if (file.isDirectory()):
            return

        self.app.image = Image(Display.getCurrent(), file.getPath())
        self.app.setStatus("Open file: " + file.getPath())
        self.app.newOrResizeImage()

        gc = GC(self.app.canvas)
        rect = self.app.canvas.getClientArea()
        gc.drawImage(self.app.image, 0, 0)
        gc.dispose()

        self.app.canvas.redraw()

class App(ApplicationWindow):
    """ Main class for JFace application drived from ApplicationWindow class """

    # add static image registry
    imageRegistry = None

    # add class method for image registry
    @classmethod
    def getImageRegistry(cls):
        if (not cls.imageRegistry):
            cls.imageRegistry = ImageRegistry()
            cls.imageRegistry.put("app.icon", ImageDescriptor.createFromImage(drawIcon(Display.getCurrent())))

            # load icon image from file
            cls.imageRegistry.put("file.exit", ImageDescriptor.createFromImage(Image(Display.getCurrent(), "img/system-log-out.png")))
            cls.imageRegistry.put("file.open", ImageDescriptor.createFromImage(Image(Display.getCurrent(), "img/document-open.png")))
            cls.imageRegistry.put("file.image", ImageDescriptor.createFromImage(Image(Display.getCurrent(), "img/image-x-generic.png")))

        return cls.imageRegistry

    def __init__(self, shell):
        """ application constructor """
        # let parent class to do it's stuff first
        ApplicationWindow.__init__(self, shell)

        self.canvas = None
        self.image = None
        self.origin = Point(0, 0)

        self.treeViewer = None

        # lets add menu
        self.addMenuBar()

        # lets add toolbar
        self.addToolBar(SWT.FLAT | SWT.WRAP)

        # lets add status line
        self.addStatusLine()

    def dispose(self):
        """ dispose resources here """
        if (self.image != None):
            self.image.dispose()

    def createContents(self, parent):
        """Creates the main window's contents
        parent - the main window
        return - control
        """
        self.shell.setImage(drawIcon(Display.getCurrent())) 
        self.shell.text = 'JPictureMaster II (Jython & JFace example)'

        # create split form
        mainForm = SashForm(parent, SWT.HORIZONTAL | SWT.NULL)
        mainForm.setLayout(FillLayout())

        # create tree
        treePanel = Composite(mainForm, SWT.NONE)
        treePanel.setLayout(GridLayout(1, True))

        self.treeViewer = TreeViewer(treePanel, SWT.BORDER | SWT.VIRTUAL)
        self.treeViewer.getControl().setLayoutData(GridData(SWT.FILL, SWT.FILL, True, True, 3, 3))
        self.treeViewer.setContentProvider(FileTreeContentProvider())
        self.treeViewer.setLabelProvider(FileTreeLabelProvider())
        self.treeViewer.setInput(File("."))
        self.treeViewer.addSelectionChangedListener(FileTreeSelectionChangedListener(self))
        self.treeViewer.refresh()

        imagePanel = Composite(mainForm, SWT.NONE)
        # set layout as one column grid
        imagePanel.setLayout(GridLayout(1, True))

        # create canvas for image displaying
        self.canvas = Canvas(imagePanel, SWT.BORDER | SWT.NO_BACKGROUND|SWT.NO_REDRAW_RESIZE|SWT.V_SCROLL|SWT.H_SCROLL)
        self.canvas.setLayoutData(GridData(SWT.FILL, SWT.FILL, True, True, 1, 1))
        # add listeners to canvas, so we could react to events
        self.canvas.getHorizontalBar().addListener(SWT.Selection, HBarListener(self)) 
        self.canvas.getVerticalBar().addListener(SWT.Selection, VBarListener(self))
        self.canvas.addListener(SWT.Paint, CanvasPaintListener(self))
        self.canvas.addListener(SWT.Resize, CanvasResizeListener(self))

        mainForm.setWeights([30, 70])
        return mainForm

    def createMenuManager(self):
        """ create main menu """
        return MainMenuManager(self).createMainMenu()

    def createToolBarManager(self, style):
        """ create main toolbar """
        return MainToolbarManager(self).createMainToolBar(style)

    def getStatusLineManagerForUpdate(self):
        """ get status line manager """
        return self.getStatusLineManager()

    def newOrResizeImage(self):
        if (not self.canvas):
            return

        client = self.canvas.getClientArea()

        if (not self.image):
            self.image = Image(self.shell.getDisplay(), client.width, client.height)

            gc = GC(self.image)
            gc.fillRectangle(0, 0, client.width, client.height)
            gc.drawLine (0, 0, client.width, client.height)
            gc.drawLine (0, client.height, client.width, 0)
            gc.drawText ("No Image", 10, 10)
            gc.dispose ()

        rect = self.image.getBounds()
        self.canvas.getHorizontalBar().setMaximum(rect.width)
        self.canvas.getVerticalBar().setMaximum(rect.height)
        self.canvas.getHorizontalBar().setThumb(Math.min (rect.width, client.width))
        self.canvas.getVerticalBar().setThumb(Math.min (rect.height, client.height))

        hPage = rect.width - client.width
        vPage = rect.height - client.height
        hSelection = self.canvas.getHorizontalBar().getSelection()
        vSelection = self.canvas.getVerticalBar().getSelection()

        if (hSelection >= hPage):
            if (hPage <= 0):
                hSelection = 0
                self.origin.x = -hSelection

        if (vSelection >= vPage):
            if (vPage <= 0):
                vSelection = 0
                self.origin.y = -vSelection

if __name__ == "__main__":
    """ The entry point for our application """
    display = Display()
    shell = Shell(display)

    app = App(shell)
    # Voodoo of SWT message loop
    try:
        app.setBlockOnOpen(True)
        app.open()
    finally:
        if app != None:
            app.dispose()

    display.dispose()

Thursday, June 18, 2009

Dynamically create a type with Python

Create new type on the fly with type in Python Code:
def cat_init(self):
    self.test1 = '1'
    self.test2 = '2'

def some_method(self):
    print 'meow'

# create new class on the fly
Cat = type('Cat', (object,), {'meow': some_method, '__init__': cat_init })

# create instance of the new class
cat = Cat()

# test new instance
print cat.test2
# >>> 2
print cat.test1
# >>> 1
cat.meow()
# >>> meow

Honey, I killed the superbug

AUSTRALIAN researchers have been astonished to discover a cure-all right under their noses -- a honey sold in health food shops as a natural medicine.

Wednesday, June 17, 2009

Rapid application development with Jython and JFace (part V – First application)

Jython 2.5.0 final is out! Big congrats to the Jython team! Go and download it now! Today my friends we will glue all components together and will make our first application. This application will be dump image displaying utility. I’ll call it “JPictureMaster”. I am using some free icons from Tango Desktop Project so you’ll need to download this archive in order to be able to run application. Then done downloading copy two icons: tango-icon-theme-0.8.90\16x16\actions\system-log-out.png and tango-icon-theme-0.8.90\16x16\actions\document-open.png into "img" folder there your jython script is located. In this part I will add FileDialog and StatusLine. FileDialog This is simple single file selection dialog. By using it I’ll show basics of SWT\JFace dialog usage. StatusLine Status line is used for displaying short status information in your application. Search script code for self.app.setStatus("Open file: " + filename) and you will get idea how to use it. Code:
"""
Dump image displaying application JPictureMaster (Jython & JFace example)
Part V - First application
GUID of this code snippet: eef8f89a-d1d6-4211-9063-ba4c736eb620
Author: Darius Kucinskas (c) 2008-2009
Email: d[dot]kucinskas[eta]gmail[dot]com
Blog: http://blog-of-darius.blogspot.com/
License: GPL
"""
from org.eclipse.swt import *
from org.eclipse.swt.SWT import *
from org.eclipse.swt.widgets import *
from org.eclipse.swt.layout import *
from org.eclipse.jface.window import *
from org.eclipse.jface.action import *
from org.eclipse.jface.resource import *

from java.lang import *

# Skip this for now
# Draw glider emblem (I use it as icon for this example)
from org.eclipse.swt.graphics import *
def drawIcon(display):
    image = Image(display, 16, 16)
    gc = GC(image)

    gc.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT))
    gc.fillRectangle(0, 0, 16, 16)

    gc.setBackground(Color(display, 193, 39, 45))
    gc.fillRectangle( 1, 11, 4, 4)
    gc.fillRectangle( 6, 11, 4, 4)
    gc.fillRectangle(11, 11, 4, 4)
    gc.fillRectangle(11,  6, 4, 4)
    gc.fillRectangle( 6,  1, 4, 4)

    gc.setBackground(Color(display, 253, 185, 19))
    gc.fillRectangle( 1,  1, 4, 4)
    gc.fillRectangle( 1,  6, 4, 4)
    gc.fillRectangle(11,  1, 4, 4)

    gc.setBackground(Color(display, 0, 106, 68))
    gc.fillRectangle( 6,  6, 4, 4)

    gc.dispose()
    return image

class HBarListener(Listener):
    """ Listener for horizontal scroll events """

    def __init__(self, app):
        self.app = app
    
    def handleEvent(self, e):        
        selection = self.app.canvas.getHorizontalBar().getSelection()
        x = -selection - self.app.origin.x
        rect = self.app.image.getBounds()
        self.app.canvas.scroll(x, 0, 0, 0, rect.width, rect.height, False)
        self.app.origin.x = -selection

class VBarListener(HBarListener):
    """ Listener for vertical scroll events """

    def handleEvent(self, e):        
        selection = self.app.canvas.getVerticalBar().getSelection()
        y = -selection - self.app.origin.y
        rect = self.app.image.getBounds()
        self.app.canvas.scroll(0, y, 0, 0, rect.width, rect.height, False)
        self.app.origin.y = -selection

class CanvasPaintListener(HBarListener):
    """ Listener for paint events """

    def handleEvent(self, e):
        gc = e.gc
        gc.drawImage(self.app.image, self.app.origin.x, self.app.origin.y)
        rect = self.app.image.getBounds()
        client = self.app.canvas.getClientArea()
        marginW = client.width - rect.width
        if (marginW > 0):
            gc.fillRectangle(rect.width, 0, marginW, client.height)

        marginH = client.height - rect.height
        if (marginH > 0):
            gc.fillRectangle(0, rect.height, client.width, marginH)

class CanvasResizeListener(HBarListener):
    """ Listener for resize events """

    def handleEvent(self, e):
        rect = self.app.image.getBounds()
        client = self.app.canvas.getClientArea()
        self.app.canvas.getHorizontalBar().setMaximum(rect.width)
        self.app.canvas.getVerticalBar().setMaximum(rect.height)
        self.app.canvas.getHorizontalBar().setThumb(Math.min (rect.width, client.width))
        self.app.canvas.getVerticalBar().setThumb(Math.min (rect.height, client.height))
        hPage = rect.width - client.width
        vPage = rect.height - client.height
        hSelection = self.app.canvas.getHorizontalBar().getSelection()
 vSelection = self.app.canvas.getVerticalBar().getSelection()
 if (hSelection >= hPage):
            if (hPage <= 0):
                hSelection = 0
  self.app.origin.x = -hSelection
  
 if (vSelection >= vPage):
            if (vPage <= 0):
                vSelection = 0
                self.app.origin.y = -vSelection

        self.app.canvas.redraw()

class ExitAction(Action):
    """ This is simple quit application action.
    
    All action classes should inherit from Action (org.eclipse.jface.action.Action) class.
    """
    
    def __init__(self, app):
        """ constructor of ExitAction
        
        arguments:
        app - in order to do anything useful I am passing 
        object of my application.    
        """
        self.app = app
        self.text = "E&xit@Ctrl+Q"
        self.toolTipText = "Exit the application"
        self.imageDescriptor = App.getImageRegistry().getDescriptor("file.exit")
        
    def run(self):
        """ run() method of action. Every action class should have one.
        This time it closes application.
        """
        if self.app != None:
            self.app.close()

class OpenImageAction(Action):
    """ Simple open image action """

    FILTER_NAMES = ["All Files (*.*)"]
    FILTER_EXTS = ["*.*"]

    def __init__(self, app):
        self.app = app
        self.text = "O&pen@Ctrl+O"
        self.toolTipText = "Open and display image"
        self.imageDescriptor = App.getImageRegistry().getDescriptor("file.open")

    def run(self):
        # this code shows FileDialog usage
        dlg = FileDialog(app.getShell(), SWT.OPEN)
        dlg.filterNames = OpenImageAction.FILTER_NAMES
        dlg.filterExtensions = OpenImageAction.FILTER_EXTS
        dlg.text = "Open an image file or cancel"
        filename = dlg.open()
        
        if (filename != ""):
            # now we'll open image and draw it on canvas
            self.app.setStatus("Open file: " + filename)
            self.app.image = Image(Display.getCurrent(), filename)
            if (self.app.image != None):
                gc = GC(self.app.canvas)
                rect = self.app.canvas.getClientArea()
                gc.fillRectangle(0, 0, rect.width, rect.height)
                gc.drawImage(self.app.image, 0, 0)                
                gc.dispose()

class MainMenuManager(MenuManager):
    """ MenuManager is responsible for constructing  menu """
    
    def __init__(self, app):
        """constructor of MainMenuManager
        
        arguments:
        app - in order to do anything useful I am passing 
        object of my application.    
        """
        # let parent class to do it's stuff first
        MenuManager.__init__(self)
        self.app = app
        
    def createMainMenu(self):
        """ creates menu """
        mainMenu = MenuManager("")
        fileMenu = MenuManager("&File")
        mainMenu.add(fileMenu)
        
        # add Exit action to file menu 
        fileMenu.add(ExitAction(self.app))
        fileMenu.add(OpenImageAction(self.app))
        
        return mainMenu

class MainToolbarManager(ToolBarManager):
    """ """

    def __init__(self, app):
        """construcotr of MainToolbar
        
        arguments:
        app - in order to do anything useful I am passing 
        object of my application.    
        """
        # let parent class to do it's stuff first
        ToolBarManager.__init__(self)
        self.app = app        

    def createMainToolBar(self, style):
        """ add items to toolbar """
        mainToolBar = ToolBarManager(style)

        # add Exit action to toolbar 
        mainToolBar.add(ExitAction(self.app))
        mainToolBar.add(OpenImageAction(self.app))
        
 return mainToolBar

class App(ApplicationWindow):
    """ Main class for JFace application drived from ApplicationWindow class """

    # add static image registry
    imageRegistry = None

    # add class method for image registry
    @classmethod
    def getImageRegistry(cls):
        if (cls.imageRegistry == None):
            cls.imageRegistry = ImageRegistry()
            cls.imageRegistry.put("app.icon", ImageDescriptor.createFromImage(drawIcon(Display.getCurrent())))
            # load icon image from file
            cls.imageRegistry.put("file.exit", ImageDescriptor.createFromImage(Image(Display.getCurrent(), "img\system-log-out.png")))
            cls.imageRegistry.put("file.open", ImageDescriptor.createFromImage(Image(Display.getCurrent(), "img\document-open.png")))

        return cls.imageRegistry
    
    def __init__(self, shell):
        """ application constructor """
        
        # let parent class to do it's stuff first
        ApplicationWindow.__init__(self, shell)

        self.canvas = None

        #we will draw default image
 width = 150
 height = 200
 self.image = Image(shell.getDisplay(), width, height)
 gc = GC(self.image)
 gc.fillRectangle (0, 0, width, height)
 gc.drawLine (0, 0, width, height)
 gc.drawLine (0, height, width, 0)
 gc.drawText ("Default Image", 10, 10)
 gc.dispose ()

        self.origin = Point(0, 0)
        
        # lets add menu
        self.addMenuBar()

        # lets add toolbar
        self.addToolBar(SWT.FLAT | SWT.WRAP)

        # lets add status line
        self.addStatusLine()
    
    def dispose(self):
        """ dispose resources here """
        if (self.image != None):
            self.image.dispose()
        
    def createContents(self, parent):
        """Creates the main window's contents
        parent - the main window
        return - control
        """
        self.getShell().setImage(drawIcon(Display.getCurrent())) 
        self.getShell().text = 'JPictureMaster (Jython & JFace example)'
        
        panel = Composite(parent, SWT.BORDER)
        # set layout as one column grid
        panel.setLayout(GridLayout(1, True))
        
        # create canvas for image displaying
        self.canvas = Canvas(panel, SWT.NO_BACKGROUND|SWT.NO_REDRAW_RESIZE|SWT.V_SCROLL|SWT.H_SCROLL)
        self.canvas.setLayoutData(GridData(SWT.FILL, SWT.FILL, True, True, 1, 1))
        # add listeners to canvas, so we could react to events
        self.canvas.getHorizontalBar().addListener(SWT.Selection, HBarListener(self)) 
        self.canvas.getVerticalBar().addListener(SWT.Selection, VBarListener(self))
        self.canvas.addListener(SWT.Paint, CanvasPaintListener(self))
        self.canvas.addListener(SWT.Resize, CanvasResizeListener(self))
        
        return panel
    
    def createMenuManager(self):
        """ create main menu """
        return MainMenuManager(self).createMainMenu()

    def createToolBarManager(self, style):
        """ create main toolbar """
        return MainToolbarManager(self).createMainToolBar(style)

    def getStatusLineManagerForUpdate(self):
        """ get status line manager """
        return self.getStatusLineManager()

if __name__ == "__main__":
    """ The entry point for our application """
    display = Display()
    shell = Shell(display)
    
    app = App(shell)
    
    # Voodoo of SWT message loop
    try:
        app.setBlockOnOpen(True)
        app.open()
    finally:
        if app != None:
            app.dispose()
    
    display.dispose()
P.S. If you think I am some kind of Jython & JFace guru you are wrong my friend. So if you will spot any kind of bug in this example, please let me know about it!

Monday, June 15, 2009

Rapid application development with Jython and JFace (part IV – main toolbar and image registry)

You could read older posts from this series here, here and here. In this part we’ll add toolbar and image registry. Toolbar this useful thing by which user can trigger commands and then application will do its stuff. In order to have it in your application you should write class that will inherit from the ToolBarManager class. Add method to construct toolbar. And the last thing: you need to call addToolBar () method to your application's constructor. Good now you have toolbar, right? Not jet, first I’ll show you how you can use image registry. Image registry Rule(1): in every application you write you should minimize usage of resources. Image of actions are good candidates for rule no. 1. You can minimize resource usage with images by using imgae registry. Code:
"""
Hello world application with Jython and JFace
Part IV - Toolbar and image registry
GUID of this code snippet: 939698cb-d2ef-448b-90f2-32580ca3225es
Author: Darius Kucinskas (c) 2008-2009
Email: d[dot]kucinskas[eta]gmail[dot]com
Blog: http://blog-of-darius.blogspot.com/
License: GPL
"""
from org.eclipse.swt import *
from org.eclipse.swt.SWT import *
from org.eclipse.swt.widgets import *
from org.eclipse.swt.layout import *
from org.eclipse.jface.window import *
from org.eclipse.jface.action import *
from org.eclipse.jface.resource import *

# Skip this for now
# Draw glider emblem (I use it as icon for this example)
from org.eclipse.swt.graphics import *
def drawIcon(display):
    image = Image(display, 16, 16)
    gc = GC(image)

    gc.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT))
    gc.fillRectangle(0, 0, 16, 16)

    gc.setBackground(Color(display, 193, 39, 45))
    gc.fillRectangle( 1, 11, 4, 4)
    gc.fillRectangle( 6, 11, 4, 4)
    gc.fillRectangle(11, 11, 4, 4)
    gc.fillRectangle(11,  6, 4, 4)
    gc.fillRectangle( 6,  1, 4, 4)

    gc.setBackground(Color(display, 253, 185, 19))
    gc.fillRectangle( 1,  1, 4, 4)
    gc.fillRectangle( 1,  6, 4, 4)
    gc.fillRectangle(11,  1, 4, 4)

    gc.setBackground(Color(display, 0, 106, 68))
    gc.fillRectangle( 6,  6, 4, 4)

    gc.dispose()
    return image

# Draw exit icon
def drawExitIcon(display):
    image = Image(display, 16, 16)
    gc = GC(image)

    gc.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT))
    gc.fillRectangle(0, 0, 16, 16)

    gc.setBackground(Color(display, 193, 39, 45))
    gc.fillRectangle( 1, 11, 4, 4)
    gc.fillRectangle(11, 11, 4, 4)
    gc.fillRectangle( 1,  1, 4, 4)
    gc.fillRectangle(11,  1, 4, 4)
    gc.fillRectangle( 6,  6, 4, 4)

    gc.dispose()
    return image

class ExitAction(Action):
    """ This is simple quit application action.
    
    All action classes should inherit from Action (org.eclipse.jface.action.Action) class.
    """
    
    def __init__(self, app):
        """ constructor of ExitAction
        
        arguments:
        app - in order to do anything useful I am passing 
        object of my application.    
        """
        self.app = app
        self.text = "E&xit@Ctrl+Q"
        self.toolTipText = "Exit the application"
        self.imageDescriptor = App.getImageRegistry().getDescriptor("file.exit")
        
    def run(self):
        """ run() method of action. Every action class should have one.
        This time it closes application.
        """
        if self.app != None:
            self.app.close()

class MainMenuManager(MenuManager):
    """ MenuManager is responsible for constructing  menu """
    
    def __init__(self, app):
        """constructor of MainMenuManager
        
        arguments:
        app - in order to do anything useful I am passing 
        object of my application.    
        """
        # let parent class to do it's stuff first
        MenuManager.__init__(self)
        self.app = app
        
    def createMainMenu(self):
        """ creates menu """
        mainMenu = MenuManager("")
        fileMenu = MenuManager("&File")
        mainMenu.add(fileMenu)
        
        # add Exit action to file menu 
        fileMenu.add(ExitAction(self.app))
        
        return mainMenu

class MainToolbarManager(ToolBarManager):
    """ """

    def __init__(self, app):
        """construcotr of MainToolbar
        
        arguments:
        app - in order to do anything useful I am passing 
        object of my application.    
        """
        # let parent class to do it's stuff first
        ToolBarManager.__init__(self)
        self.app = app        

    def createMainToolBar(self, style):
        """ add items to toolbar """
        mainToolBar = ToolBarManager(style)

        # add Exit action to toolbar 
        mainToolBar.add(ExitAction(self.app))
 return mainToolBar

class App(ApplicationWindow):
    """ Main class for JFace application drived from ApplicationWindow class """

    # add static image registry
    imageRegistry = None

    # add class method for image registry
    @classmethod
    def getImageRegistry(cls):
        if (cls.imageRegistry == None):
            cls.imageRegistry = ImageRegistry()
            cls.imageRegistry.put("app.icon", ImageDescriptor.createFromImage(drawIcon(Display.getCurrent())))
            cls.imageRegistry.put("file.exit", ImageDescriptor.createFromImage(drawExitIcon(Display.getCurrent())))

        return cls.imageRegistry
    
    def __init__(self, shell):
        """ application constructor """
        
        # let parent class to do it's stuff first
        ApplicationWindow.__init__(self, shell)
        
        # lets add menu
        self.addMenuBar()

        # lets add toolbar
        self.addToolBar(SWT.FLAT | SWT.WRAP);
    
    def dispose(self):
        """ dispose resources here """
        pass
        
    def createContents(self, parent):
        """Creates the main window's contents
        parent - the main window
        return - control
        """
        self.getShell().setImage(drawIcon(Display.getCurrent())) 
        self.getShell().text = 'Fourth Jython & JFace example'
        
        panel = Composite(parent, SWT.BORDER)
        # set layout as one column grid
        panel.setLayout(GridLayout(1, True))
        
        label = Label(panel, SWT.CENTER)
        label.text = 'Hello, World'
        label.setLayoutData(GridData(SWT.CENTER, SWT.CENTER, False, False, 1, 1))
        
        # you can use action instead of button        
        ActionContributionItem(ExitAction(self)).fill(panel)
        
        return panel
    
    def createMenuManager(self):
        """ create main menu """
        return MainMenuManager(self).createMainMenu()

    def createToolBarManager(self, style):
        """ create main toolbar """
        return MainToolbarManager(self).createMainToolBar(style)

if __name__ == "__main__":
    """ The application entry point """
    display = Display()
    shell = Shell(display)
    
    app = App(shell)
    
    # Voodoo of SWT message loop
    try:
        app.setBlockOnOpen(True)
        app.open()
    finally:
        if app != None:
            app.dispose()
    
    display.dispose()

Friday, May 22, 2009

Rapid application development with Jython and JFace (part III – main menu and actions)

In first part of this series I showed how to create hello world application with Jython and JFace. In second part we added event listers and layouts. In this part we will add main menu and action. Menu This useful thing by which user can trigger commands and then application will do it's stuff. In order to have it in your application you should write class that will inherits from the MenuManager class. Add method to construct menu. And the last thing: you need to call addMenuBar() method to your application's constructor. Good now you have menu, right? Not jet, first you have to write some actions. Luck use your Actions! All action classes should inherit from Action (org.eclipse.jface.action.Action) class. Action is abstraction above event listeners. Actions are easy to implement and you reduce code size by using them. We will implement exit application action in todays example application. Code:
"""
Hello world application with Jython and JFace
Part III - Main menu and actions 
GUID of this code snippet: 7f75fc86-d78c-4ce1-8e28-97bb4f5d5b31
Author: Darius Kucinskas (c) 2008-2009
Email: d[dot]kucinskas[eta]gmail[dot]com
Blog: http://blog-of-darius.blogspot.com/
License: GPL
"""
from org.eclipse.swt import *
from org.eclipse.swt.SWT import *
from org.eclipse.swt.widgets import *
from org.eclipse.swt.layout import *
from org.eclipse.jface.window import *
from org.eclipse.jface.action import *

# Skip this for now
# Draw Lithuanian flag (I use it as icon for this example)
from org.eclipse.swt.graphics import *
def drawIcon(display):
    image = Image(display, 16, 16)
    gc = GC(image)
    gc.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT))
    gc.fillRectangle(0, 0, 16, 16)
    gc.setBackground(Color(display, 253, 185, 19))
    gc.fillRectangle(0, 1, 16, 5)
    gc.setBackground(Color(display, 0, 106, 68))
    gc.fillRectangle(0, 6, 16, 10)
    gc.setBackground(Color(display, 193, 39, 45))
    gc.fillRectangle(0, 11, 16, 15)
    gc.dispose()
    return image

class ExitAction(Action):
    """ This is simple quit application action.
    
    All action classes should inherit from Action (org.eclipse.jface.action.Action) class.
    """
    
    def __init__(self, app):
        """ constructor of ExitAction
        
        arguments:
        app - in order to do anything useful I am passing 
        object of my application.    
        """
        self.app = app
        self.text = "E&xit@Ctrl+Q"
        self.toolTipText = "Exit the application"
        
    def run(self):
        """ run() method of action. Every action class should have one.
        This time it closes application.
        """
        if self.app != None:
            self.app.close()

class MainMenuManager(MenuManager):
    """ MenuManager is responsible for constructing  menu """
    
    def __init__(self, app):
        """constructor of MainMenuManager
        
        arguments:
        app - in order to do anything useful I am passing 
        object of my application.    
        """
        # let parent class to do it's stuff first
        MenuManager.__init__(self)
        self.app = app
        
    def createMainMenu(self):
        """ creates menu """
        mainMenu = MenuManager("")
        fileMenu = MenuManager("&File")       
        mainMenu.add(fileMenu)
        
        # add Exit action to file menu 
        fileMenu.add(ExitAction(self.app))
        
        return mainMenu   

class App(ApplicationWindow):
    """ Your second JFace application in jython """
        
    def __init__(self, shell):
        """ application constructor """
        # let parent class to do it's stuff first
        ApplicationWindow.__init__(self, shell)
        
        # lets add menu
        self.addMenuBar()
    
    def dispose(self):
        """ dispose resources here """
        pass
        
    def createContents(self, parent):
        """ 
        Creates the main window's contents
        parent - the main window
        return - control
        """
        self.getShell().setImage(drawIcon(Display.getCurrent())) 
        self.getShell().text = 'Third Jython & JFace example'
        
        panel = Composite(parent, SWT.BORDER)
        # set layout as one column grid
        panel.setLayout(GridLayout(1, True))
        
        label = Label(panel, SWT.CENTER)
        label.text = 'Hello, World'
        label.setLayoutData(GridData(SWT.CENTER, SWT.CENTER, False, False, 1, 1))
        
        # you can use action instead of button        
        ActionContributionItem(ExitAction(self)).fill(panel)
        
        return panel
    
    def createMenuManager(self):
        """ create main menu """
        return MainMenuManager(self).createMainMenu()
    
if __name__ == "__main__":
    """ The application entry point """
    display = Display()
    shell = Shell(display)
    
    app = App(shell)
    
    # Voodoo of SWT message loop
    try:
        app.setBlockOnOpen(True)
        app.open()
    finally:
        if app != None:
            app.dispose()
    
    display.dispose()
May the Jython force be with you!

Saturday, May 16, 2009

Rapid application development with Jython and JFace (part II – event listener and layout)

In first part of this series I showed how to create hello world application with Jython and JFace. Now we will add event listers and layouts. What application is good for if it is not reacting to user input? Events Listeners are special kind of classes and you will derive your class from it in order to be able to react to user actions. So we created MyListener listener. We pass reference to application object to constructor (so we could do many interesting things with it later then event happened). We yest close application on event in MyListener handleEvent method. We connected button 'Close' with MyListener. Event will be fired then user will press this button. Layouts Layouts are used to organize widgets on the screen in desired order. This time we put all widgets in grid which is one column width and two rows in height. Code:
"""
Hello world application with Jython and JFace
Part II - Event listeners and layouts 
GUID of this code snippet: 53029f4d-a208-4f45-920c-07d81167daee
Author: Darius Kucinskas (c) 2008-2009
Email: d[dot]kucinskas[eta]gmail[dot]com
Blog: http://blog-of-darius.blogspot.com/
License: GPL
"""
from org.eclipse.swt import *
from org.eclipse.swt.SWT import *
from org.eclipse.swt.widgets import *
from org.eclipse.swt.layout import *
from org.eclipse.jface.window import *

class MyListener(Listener):
 """ Class for event listener """
 
 def __init__(self, app):
  self.app = app

 def handleEvent(self, event):
  """ Close application if button is pressed """
  self.app.close()
   
class SWTApp(ApplicationWindow):
    """ Your second JFace application in jython """
        
    def __init__(self, shell):
        """ application constructor """
        ApplicationWindow.__init__(self, shell)
    
    def dispose(self):
        """ dispose resources here """
        pass
        
    def createContents(self, parent):
        """ 
        Creates the main window's contents
        parent - the main window
        return - control
        """ 
        self.getShell().text = 'Second Jython & JFace App'
        
        panel = Composite(parent, SWT.BORDER)
        panel.setLayout(GridLayout(1, True))
        """ set layout as one column grid """
        
        label = Label(panel, SWT.CENTER)
        label.text = 'Hello, World'
        label.setLayoutData(GridData(SWT.CENTER, SWT.CENTER, False, False, 1, 1))
                
        button = Button(panel, SWT.PUSH)
        button.text = 'Close'
        button.setLayoutData(GridData(SWT.CENTER, SWT.CENTER, False, False, 1, 1))
        button.addListener(SWT.Selection, MyListener(self))
        """ set listener which will react on event (button pressing) """
        
        return panel

if __name__ == "__main__":
    """ The application entry point """
    display = Display()
    shell = Shell(display)
    
    app = SWTApp(shell)
    try:
        app.setBlockOnOpen(True)
        app.open()
    finally:
        if app != None:
            app.dispose()
    
    display.dispose()
Execute your program: Now execute your application. There it is, your second Jython and JFace application.

Friday, May 15, 2009

Rapid application development with Jython and JFace (part I)

In this series of articles I'll show you how to create applications with jython and jface. I assume that you know syntax of python if not please first visit this fine tutorial here or any other. We'll start by setting up environment needed for development and will create the simplest jface application which will be foundation for further development.

Jython

Jython, lest you do not know of it, is the most compelling weapon the Java platform has for its survival into the 21st century:-) [Sean McGrath, CTO, Propylon]

Download Jython

What are your waiting for? Go and download jython from here now! Installation is easy jest execute command java -jar jython_installer-2.5.0.jar and follow instructions.

SWT: The Standard Widget Toolkit

SWT is an open source widget toolkit for Java designed to provide efficient, portable access to the user-interface facilities of the operating systems on which it is implemented. I recommend using prepared SWT packages from your Eclipse installation. You are using Eclipse right?

Needed jar files are the following:

  • org.eclipse.swt.gtk.linux.x86_3.4.0.xxx.jar
  • org.eclipse.swt_3.4.0.xxx.jar
  • org.eclipse.jface_3.4.0.xxx.jar
  • org.eclipse.core.commands_3.4.0.xxx.jar
  • org.eclipse.osgi_3.4.0.xxx.jar
  • org.eclipse.equinox.common_3.4.0.xxx.jar

Setting environment

To be able to run Jython/SWT/JFace application you should properly set your classpath (or configure your Eclipse IDE). If your are using Linux operating system you should execute the following commands:

CLASSPATH=$CLASSPATH:"[path to jar]/org.eclipse.swt.gtk.linux.x86_3.4.0.xxx.jar"
CLASSPATH=$CLASSPATH:"[path to jar]/org.eclipse.swt_3.4.0.xxx.jar"
CLASSPATH=$CLASSPATH:"[path to jar]/org.eclipse.jface_3.4.0.xxx.jar"
CLASSPATH=$CLASSPATH:"[path to jar]/org.eclipse.core.commands_3.4.0.xxx.jar"
CLASSPATH=$CLASSPATH:"[path to jar]/org.eclipse.osgi_3.4.0.xxx.jar"
CLASSPATH=$CLASSPATH:"[path to jar]/org.eclipse.equinox.common_3.4.0.xxx.jar"
export CLASSPATH
For Windows execute the following command:
set CLASSPATH=.;[path to jar]\org.eclipse.swt.win32.win32.x86_3.4.xxx.jar;[path to jar]\org.eclipse.swt_3.4.xxx.jar;[path to jar]\org.eclipse.jface_3.4.xxx.jar;[path to jar]\org.eclipse.core.commands_3.4.xxx.jar;[path to jar]\org.eclipse.osgi_3.4.xxx.jar;[path to jar]\org.eclipse.equinox.common_3.4.xxx.jar

Code:
"""
Hello world application with Jython and JFace
GUID of this code snippet: cb4f368e-3b6b-42fe-ab1d-6f80e77ee3f5 
Author: Darius Kucinskas (c) 2008-2009
Email: d[dot]kucinskas[eta]gmail[dot]com
Blog: http://blog-of-darius.blogspot.com/
License: GPL
"""

from org.eclipse.swt import *
from org.eclipse.swt.SWT import *
from org.eclipse.swt.widgets import *
from org.eclipse.jface.window import *

class SWTApp(ApplicationWindow):
    """ Your first JFace application in jython """
    
    def __init__(self, shell):
        """ application constructor """
        ApplicationWindow.__init__(self, shell)
    
    def dispose(self):
        """ dispose resources here """
        pass
    
    def createContents(self, parent):
        """ 
        Creates the main window's contents
        parent - the main window
        return - control
        """ 
        self.getShell().text = 'First Jython & JFace App'
        self.label = Label(parent, SWT.CENTER)
        self.label.text = 'Hello, World'
        return self.label

if __name__ == "__main__":
    """ The application entry point """
    display = Display()
    shell = Shell(display)
    
    app = SWTApp(shell)
    try:
        app.setBlockOnOpen(True)
        app.open()
    finally:
        if app != None:
            app.dispose()
    
    display.dispose()

Save this code in file swtapp.py.

Execute your program:

Now execute your application: jython swtapp.py. There it is, your first jython and jface application.

Wednesday, May 13, 2009

Implementation of sort algorithms in python (part II – merge sort)

I am continuing my quest to implement all sort algorithms in python programming language. In this post I have implemented merge sort algorithm. Enjoy! (Previous post is available here).
"""
Merge sorting algorithms implemented in python
GUID of this code sniped: 83d44e30-e7b4-439e-b9eb-7dae165bf1af 
Author: Darius Kucinskas (c) 2008-2009
Email: d[dot]kucinskas[eta]gmail[dot]com
Blog: http://blog-of-darius.blogspot.com/
License: GPL
"""
def merge(left, right):
    r = []
    
    while len(left) > 0 and len(right) > 0:
        if left[0] <= right[0]:
            r.append(left[0])
            left = left[1:]
        else:
            r.append(right[0])
            right = right[1:]
            
    if len(left) > 0:
        r.extend(left)

    if len(right) > 0:
        r.extend(right)
    
    return r
    
def merge_sort(l):
    size = len(l)
    if size <= 1:
        return l

    middle = (size/2) - 1
    
    left = l[:middle+1]
    right = l[middle+1:]

    left = merge_sort(left)
    right = merge_sort(right)

    r = []
    if left[len(left) - 1] > right[0]:
        r = merge(left, right)
    else:
        r = merge(right, left)

    return r

if (__name__ == "__main__"):
    l = [i for i in range(10000)]
    print "sorted list"
    print l

    random.shuffle(l)
    print "unsorted original list"
    print l

    t1 = time.clock()
    lsorted = merge_sort(l)
    t2 = time.clock()
    print "soted list:"
    print lsorted
    print "merge sort time: %f " % (t2 - t1,)

Friday, May 8, 2009

Implementation of sort algorithms in python

I have found Wikipedia page about sorting algorithms. They are described in pseudo code, it is so easy to convert those in python code, so that I am hooked and can’t stop… :) Here is code, enjoy!
import random
import time

"""
Example of sorting algorithms implemented in python
GUID of this code sniped: 41ea3d8f-2330-4ddd-9e9d-ecd536ab4f4d 
Author: Darius Kucinskas (c) 2008-2009
Email: d[dot]kucinskas[eta]gmail[dot]com
Blog: http://blog-of-darius.blogspot.com/
License: GPL
"""

"""
simple bubble sort
"""
def bubble(l):
    sort_again = True
    while sort_again:
        sort_again = False

        i = 0
        size = len(l) - 1
        while i < size:
            if l[i] > l[i + 1]:
                swap(l, i, i + 1)
                sort_again = True
            i = i + 1

"""
insertion sort
"""
def insertion_sort(l):
    i = 0
    size = len(l) - 1
    while i < size:
        v = l[i]
        j = i - 1

        while j > 0 and l[j] > v:
            l[j + 1] = l[j]
            j = j - 1

        l[j + 1] = v
        i = i + 1

"""
shell sort
"""
def shell_sort(l):
    size = len(l)
    inc = int(size/2)

    while inc > 0:
        i = inc
        while i < size - 1:
            tmp = l[i]
            j = i
            while j >= inc and l[j - inc] > tmp:
                l[j] = l[j - inc]
                j = j - inc
            l[j] = tmp
            i = i + 1
        inc = int(inc/2.2)

"""
simple quicksort in python
"""
def quicksort1(l):
    if len(l) < 1:
        return l

    less = []
    greater = []

    pivot = l[len(l) / 2]
    l.remove(pivot)

    for i in l:
        if i < pivot:
            less.append(i)
        else:
            greater.append(i)

    return quicksort1(less) + [pivot] + quicksort1(greater)

def swap(l, a, b):
    tmp = l[a]
    l[a] = l[b]
    l[b] = tmp

if (__name__ == "__main__"):
    l = [i for i in range(10000)]
    print "sorted list"
    print l

    random.shuffle(l)
    print "unsorted original list"
    print l
    l2, l3, l4 = l[:], l[:], l[:]

    t1 = time.clock()
    bubble(l)
    t2 = time.clock()
    print "soted list l:"
    print l
    print "bubble sort time: %f " % (t2 - t1,)

    t1 = time.clock()
    insertion_sort(l2)
    t2 = time.clock()
    print "soted list l2:"
    print l2
    print "insertion sort time: %f " % (t2 - t1,)

    t1 = time.clock()
    shell_sort(l3)
    t2 = time.clock()
    print "soted list l3:"
    print l3
    print "shell sort time: %f " % (t2 - t1,)

    t1 = time.clock()
    lsorted = quicksort1(l4)
    t2 = time.clock()
    print "soted list l4:"
    print lsorted
    print "quick sort #1 time: %f " % (t2 - t1,)

Tuesday, May 5, 2009

back to the roots – linked list in C

I just had great fun to remember how to code linked list in C. I did it jest for propose of exercise. Next time I’ll try to do quick sort for linked list and will examine glibc if I have enough time for this exercise. Good lack and enjoy great game of coding ;)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

/**
 * Example of linked list in C
 * GUID of this code sniped: 75c6b760-1fa9-4b94-8f8d-53e5e4d6a20c
 * Author: Darius Kucinskas (c) 2008-2009
 * Email: d[dot]kucinskas[eta]gmail[dot]com
 * Blog: http://blog-of-darius.blogspot.com/
 * License: GPL
 */

typedef struct llnode LLNODE;

struct llnode
{
    void* data;
    LLNODE* next;
    LLNODE* prev;
};

int myprintstr(void* str)
{
    printf("'%s'\n", (char*)str);
    return 0;
}

int myfindstr(void *listdata, void *searchdata)
{
    return strcmp((char*)listdata, (char*)searchdata);
}

LLNODE* my_list_alloc0()
{
    LLNODE* n = malloc(sizeof(LLNODE));
    if (n == NULL)
    {
        return NULL;
    }

    memset(n, 0, sizeof(LLNODE));
    return n;
}

LLNODE* my_list_append(LLNODE* tail, void* data)
{
    LLNODE* n = my_list_alloc0();
    if (n == NULL)
    {
        printf("bad malloc my_list_append\n");
        return NULL;
    }

    n->data = data;

    if (tail != NULL)
    {
        assert(tail-<next == NULL);
        tail->next = n;
        n->prev = tail;
    }

    return n;
}

LLNODE* my_list_prepend(LLNODE* head, void* data)
{
    LLNODE* n = my_list_alloc0();
    if (n == NULL)
    {
        printf("bad malloc my_list_prepend\n");
        return NULL;
    }

    n->data = data;

    if (head != NULL)
    {
        assert(head->prev == NULL);
        n->next = head;
        head->prev = n;
    }

    return n;
}

int my_list_foreach(LLNODE* head, int(*func)(void*))
{
    LLNODE* p = head;
    while(p != NULL)
    {
        if (func(p->data) != 0)
        {
            return -1;
        }

        p = p->next;
    }
    return 0;
}

LLNODE* my_list_find(LLNODE* head, int (*func)(void*, void*), void* data)
{
    LLNODE* p = head;
    while(p != NULL)
    {
        if (func(p->data, data) == 0)
        {
            return p;
        }

        p = p->next;
    }

    return NULL;
}

void my_list_swap(LLNODE* p1, LLNODE* p2)
{
    void* p = p2->data;
    p2->data = p1->data;
    p1->data = p;
}

int my_list_sort_bubble(LLNODE** head, int(*func)(void*, void*))
{
    int sort_again = 1;

    while(sort_again == 1)
    {
        LLNODE* p = *head;
        sort_again = 0;

        while((p != NULL) && (p->next != NULL))
        {
            LLNODE* p2 = p->next;

            if (strcmp(p->data, p2->data) > 0)
            {
                my_list_swap(p, p2);
                sort_again = 1;
            }

            p = p->next;
        }
    }

    return 0;
}

void my_list_free1(LLNODE* node)
{
    assert(node != NULL);
    if (node == NULL)
    {
        return;
    }

    if (node->data != NULL)
    {
        free(node->data);
    }

    free(node);
}

void my_list_free(LLNODE* head)
{
    assert(head != NULL);
    if (head == NULL)
    {
        return;
    }

    LLNODE* p = head;
    while(p != NULL)
    {
        LLNODE* node = p;
        p = p->next;

        my_list_free1(node);
    }
}

unsigned long my_list_length(LLNODE* head)
{
    assert(head->prev == NULL);

    LLNODE* p = head;
    unsigned long count = 0;

    while(p != NULL)
    {
        count++;
        p = p->next;
    }

    return count;
}

long my_list_index(LLNODE *head, int (*func)(void*, void*), void* data)
{
    LLNODE* p = head;
    long index = 0;

    while(p != NULL)
    {
        if (func(p->data, data) == 0)
        {
            return index;
        }

        index++;
        p = p->next;
    }

    return -1;
}

LLNODE* my_list_concat(LLNODE* head1, LLNODE* head2)
{
    if ((head1 == NULL) || (head2 == NULL))
    {
        return NULL;
    }

    LLNODE* p = head1;
    while(p->next != NULL)
    {
        p = p->next;
    }

    p->next = head2;
    head2->prev = p;

    return head1;
}

int main(int argc, char** argv)
{
    LLNODE* head, *head2 = NULL;
    LLNODE* tail = NULL;

    tail = my_list_append(NULL, "first");
    if (tail == NULL)
    {
        printf("Failed to create new list");
        return 0;
    }
    head = tail;// save head of list

    // test of prepend
    head = my_list_prepend(head, "xxx");

    tail = my_list_append(tail, "second");
    tail = my_list_append(tail, "fird");
    tail = my_list_append(tail, "aac");
    tail = my_list_append(tail, "aaa");
    tail = my_list_append(tail, "test_very_long_string_jest_in_case!!!");
    tail = my_list_append(tail, "aab");
    tail = my_list_append(tail, "aba");
    tail = my_list_append(tail, "abb");

    printf("--- list: ---\n");
    my_list_foreach(head, myprintstr);
    printf("--- end of list ---\n");

    printf(" length of list: %ld \n", my_list_length(head));

    // sort
    my_list_sort_bubble(&head, myfindstr);
    printf("--- list after sort: ---\n");
    my_list_foreach(head, myprintstr);
    printf("--- end of list ---\n");

    // find test
    LLNODE* f1 = my_list_find(head, myfindstr, (void*)"test");
    if (f1 == NULL)
        printf("test not found\n");
    else
        printf("found '%s'\n", (char*)f1->data);

    // fins test
    LLNODE* f2 = my_list_find(head, myfindstr, (void*)"second");
    if (f2 == NULL)
        printf("test not found\n");
    else
        printf("found '%s'\n", (char*)f2->data);

    printf("Find index of 'xxx': %ld\n", my_list_index(head, myfindstr, (void*)"xxx"));
    printf("Find index of 'aba': %ld\n", my_list_index(head, myfindstr, (void*)"aba"));
    printf("Find index of 'test': %ld\n", my_list_index(head, myfindstr, (void*)"test"));

    // test concat
    tail = my_list_append(NULL, "ccc");
    if (tail == NULL)
    {
        printf("Failed to create new list");
        return 0;
    }
    head2 = tail;// save head of list
    tail = my_list_append(tail, "cbc");
    tail = my_list_append(tail, "cbb");
    tail = my_list_append(tail, "ddd");
    tail = my_list_append(tail, "ddc");
    tail = my_list_append(tail, "dcd");
    tail = my_list_append(tail, "dcc");
    tail = my_list_append(tail, "eee");
    tail = my_list_append(tail, "eed");

    head = my_list_concat(head, head2);
    printf("--- list after concat: ---\n");
    my_list_foreach(head, myprintstr);
    printf("--- end of list ---\n");

    // sort
    my_list_sort_bubble(&head, myfindstr);
    printf("--- list after sort: ---\n");
    my_list_foreach(head, myprintstr);
    printf("--- end of list ---\n");

    my_list_free(head);

    return 0;
}

Tuesday, April 28, 2009

the World's Most Influential Person is moot

In a stunning result, the winner of the third annual TIME 100 poll and new owner of the title World's Most Influential Person is moot. Read more here and here

Monday, April 27, 2009

Wednesday, April 15, 2009

c++ stl – find_if and not1 used to fined vector item which is exception to the rule

//Author: Darius Kucinskas (c) 2008-2009
//Email: d[dot]kucinskas[eta]gmail[dot]com
//Blog: http://blog-of-darius.blogspot.com/
//License: GPL

#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
#include <functional>

class Person
{
public:
    Person();
    Person(int a, std::string n);
    Person(const Person& src);

    bool Person::operator==(const Person& src);
    friend std::ostream& operator<<(std::ostream& out, const Person& person);

    int age;
    std::string name;
};

Person::Person()
: age(0)
, name("")
{};

Person::Person(int a, std::string n)
:age(a)
,name(n)
{};

Person::Person(const Person& src)
{
    age = src.age;
    name = src.name;
};

bool Person::operator==(const Person& src)
{
    if (name != src.name) return false;
    if (age != src.age) return false;
    return true;
}

std::ostream& operator<<(std::ostream& out, const Person& person)
{
    out << " Person name: '"
        << person.name
        << "' age: '"
        << person.age
        << "'";

    return out;
}

struct PersonOlderThen18: public std::unary_function<Person, bool>
{
    bool operator()(const Person& person) const
    {
        return (person.age >= 18);
    }
};

int main(int count, char** args)
{
    std::vector<Person> personVec;
    Person p1(18, "Person1");
    Person p2(20, "Person2");
    Person p3(12, "Person3");
    Person p4(21, "Person4");

    personVec.push_back(p1);
    personVec.push_back(p2);
    personVec.push_back(p3);
    personVec.push_back(p4);

    std::cout << std::endl;
    std::copy(personVec.begin(), personVec.end(), std::ostream_iterator<Person>(std::cout, "\n"));

    std::vector::const_iterator it;
    it = std::find_if(personVec.begin(), personVec.end(), std::not1(PersonOlderThen18()));
    if (it != personVec.end())
    {
        std::cout << std::endl;
        std::cout << " Found person (age < 18): " << *it << std::endl;
    }

    return 0;
}


Thursday, April 2, 2009

Google uncloaks once-secret server

Google uncloaks once-secret server

VirtualBox 2.1.4 and Ubuntu 9.04

When you try to install Guest Additions in Ubuntu 9.04 after executing the installer:
sudo sh ./VBoxLinuxAdditions-x86.run 
You will get the following error message: Warning: unknown version of the X Window System installed. Not installing X Window System drivers. What should you do? One work around for this problem Mount the VirtualBox Guest Additions CD. enter the following command in terminal:
$cd /media/cdrom/ 
Extract the installer: (Choose which file to extract ('x86' or 'amd64') and which directory will be target directory '/vbox').
 
sudo ./VBoxLinuxAdditions-x86.run --target /vbox
cd /vbox 
Open install.sh file with gedit editor:
sudo gedit install.sh 
In Line 415 change '1.5.99.* | 1.6 )' to '1.5.99.* | 1.6.0 )' Save and exit the file Now run installer:
sudo ./install.sh
Reboot your system.

Wednesday, April 1, 2009

c++ stl - use find_if for finding all items of set that contains satin substring

//Author: Darius Kucinskas (c) 2008-2009
//Email: d[dot]kucinskas[eta]gmail[dot]com
//Blog: http://blog-of-darius.blogspot.com/
//License: GPL

#include <iostream>
#include <set>
#include <functional>
#include <iterator>

struct checkIfContainsSubstr: 
public std::binary_function<std::string, std::string, bool>
{
    bool operator()(const std::string& str1, 
                    const std::string& str2) const 
    {
        return ((str1.find(str2) == std::string::npos)?(false):(true));
    }
};

int main(int argc, char** argv)
{
    std::set<std::string> testSet;

    testSet.insert("111test111");
    testSet.insert("test333");
    testSet.insert("111111");
    testSet.insert("222222");
    testSet.insert("2test222");
    testSet.insert("3test222");

    std::copy(testSet.begin(), testSet.end(),
            std::ostream_iterator<std::string>(std::cout, " "));
    std::cout << std::endl;            

    std::set<std::string>::iterator it = testSet.begin();
    while(it != testSet.end())
    {
        it = std::find_if(it, testSet.end(),
                            std::bind2nd(checkIfContainsSubstr(), "test"));
        if (it != testSet.end())
        {
            std::cout << "Found substr: " << (*it) << std::endl;
            it++;
        }
    }

    return 0;
}

Thursday, March 26, 2009

c++ stl - use transform to copy keys from map to set

//Author: Darius Kucinskas (c) 2008-2009
//Email: d[dot]kucinskas[eta]gmail[dot]com
//Blog: http://blog-of-darius.blogspot.com/
//License: GPL

#include <iostream>
#include <map>
#include <set>
#include <iterator>

typedef std::map<std::string, int> MyMap;

// also known as select1st in SGI STL implementation
template<typename T_PAIR>
struct GetKey: public std::unary_function<T_PAIR, typename T_PAIR::first_type>
{
   const typename T_PAIR::first_type& operator()(const T_PAIR& item) const
   {
      return item.first;
   }
};

int main(int argc, char** argv)
{
   MyMap m1,m2;

   m1["a"] = 1;
   m1["b"] = 2;
   m2["c"] = 3;
   m2["b"] = 3;

   std::set<std::string> s;
   std::transform(m1.begin(), m1.end(), std::inserter(s, s.begin()), GetKey<MyMap::value_type>());
   std::transform(m2.begin(), m2.end(), std::inserter(s, s.begin()), GetKey<MyMap::value_type>());
   std::copy(s.begin(), s.end(), std::ostream_iterator<std::string>(std::cout, " "));
   std::cout << std::endl;
   return 0;
}

Friday, March 20, 2009

c++ stl - fast way to check if map contains value

//Author: Darius Kucinskas (c) 2008-2009
//Email: d[dot]kucinskas[eta]gmail[dot]com
//Blog: http://blog-of-darius.blogspot.com/
//License: GPL

#include <iostream>
#include <map>
#include <string>
#include <functional>

typedef std::pair<std::string, int> MyPair;
typedef std::map<std::string, int> TestMap;

struct MapFind : public std::binary_function< MyPair, int, bool >
{
     bool operator()(const MyPair& p, int value) const
     {
         return p.second == value;
     }
};

int main(int argc, char** argv)
{
    TestMap testMap;
    testMap["a"] = 1;
    testMap["b"] = 2;
    testMap["c"] = 3;

    TestMap::iterator it;
    it = std::find_if(testMap.begin(), testMap.end(), std::bind2nd(MapFind(), 2));
    if (it != testMap.end())
    {
        std::cout  << " Found ! " 
                    << it->first << " " 
                    << it->second << std::endl;
    }
    else
    {
        std::cout << " Not Found ! " << std::endl;
    }

    return 0;
}

The kernel gets a new mascot

The kernel gets a new mascot

Thursday, March 19, 2009

Wednesday, March 18, 2009

Releasing early and often

I think it's always a good idea to learn from someone else mistakes

Mikrosoft :D ?

c++ stl - check if vector contains item

std::find is solution!

Whenever I want to check if vector contains satin item my preferred way is to use std::find.
//Author: Darius Kucinskas (c) 2008-2009
//Email: d[dot]kucinskas[eta]gmail[dot]com
//Blog: http://blog-of-darius.blogspot.com/
//License: GPL

#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
#include <functional>

class Person
{
public:
    Person();
    Person(int a, std::string n);
    Person(const Person& src);
    
    bool Person::operator==(const Person& src);

    int age;
    std::string name;
};

Person::Person()
: age(0)
, name("")
{};

Person::Person(int a, std::string n)
:age(a)
,name(n)
{};

Person::Person(const Person& src)
{
    age = src.age;
    name = src.name;
};

bool Person::operator==(const Person& src)
{
    if (name != src.name) return false;
    if (age != src.age) return false;
    return true;
}

int main(int count, char** args)
{
std::vector<Person> personVec;
Person p1(10, "Person1");
Person p2(12, "Person2");
Person p3(12, "Person3");

personVec.push_back(p1);
personVec.push_back(p2);
personVec.push_back(p3);

// use of find
Person f(12, "Person2"), f2(13, "Person1000");
std::vector<Person>::iterator it;

std::cout << "Find Person2" << std::endl;
it = std::find(personVec.begin(), personVec.end(), f);

if (it == personVec.end()){
    std::cout << " Person not found! " << std::endl;
}
std::cout << " Found person: " << it->name 
           << ":" << it->age 
           << " vector index: " << it - personVec.begin()
           << std::endl;

std::cout << "Find Person1000" << std::endl;
it = std::find(personVec.begin(), personVec.end(), f2);

if (it == personVec.end()){
    std::cout << " Person not found! " << std::endl;
}
std::cout << " Found person: " << it->name 
           << ":"<< it->age 
           << " vector index: " << it - personVec.begin()
           << std::endl;
 
}