How to code with Python and Glade (reloaded from Vala and Genie)

this post is a rather dumb translation, in python, of another dumb translation, for the genie language, of a tutorial written for his cousin language, vala.

the aim of the original tutorial (click here to read it) was to show how to use a glade user interface from a vala program. for this one the ideas are:

  1. install python GObjects;
  2. build a simple ui with glade (i.e. an xml-based description of the interface);
  3. write a vala genie python program to use this interface and perform some useful task (in this case, write a message to the standard error file descriptor using a gui widget value);

Install python GObjects is simple (on OSX with port, at least)

sudo port install py34-gobject3

The UI is the same from here (and save it to a file named sample.ui)

The program is simply a direct conversion

#! /usr/bin/env python3.4

import sys
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class Handler:
    def on_window1_destroy(self, *args):
        Gtk.main_quit(*args)

    def on_button1_clicked(self, button):
        button.label = "Clicked!"
        sys.stderr.write("Clicked! ---> ")

class MainWindow:

    entry = None

    def spool_text(self, widget):
        sys.stderr.write("%s\n" % (self.entry.get_text(),))

    def __init__(self):
        builder = Gtk.Builder()
    try:
        builder.add_from_file("sample.ui")
    except IOError as e:
        print("Error:", e)
        sys.exit(-1)

    builder.connect_signals(Handler())
    window = builder.get_object("window1")
    self.entry = builder.get_object ("entry1")
    button = builder.get_object ("button1")

    button.connect("clicked", self.spool_text)

    window.show_all()

if __name__ == "__main__":
    mw = MainWindow()
    Gtk.main()

It use the same class variable trick to do the job to print the entry text.

Thanks for your attention, have a nice day.

How to code with Genie and Glade (2nd part, with class)

this post is a rather dumb translation, for the genie language, of a tutorial written for his cousin language, vala.

the aim of the original tutorial (click here to read it) was to show how to use a glade user interface from a vala program. the ideas were:

  1. install vala and glade;
  2. build a simple ui with glade (i.e. an xml-based description of the interface);
  3. write a vala genie program to use this interface and perform some useful task (in this case, write a message to the standard error file descriptor using a gui widget value);
  4. build and run

we have discussed this case in another post: the problem there is that building the program

valac --pkg gtk+-3.0  sample_glade_gtk.gs 

sample_glade_gtk.gs:35.5-38.5: warning: deprecated syntax, use `connect' 
     method instead

Compilation succeeded - 1 warning(s)

we took a warning that advise us we are using a deprecated syntax (anonymous function) for the instruction

        button.clicked += def(button)
        stderr.printf ("%s\n", entry.get_text())

To use the connect method on a Button.clicked event… it seems simple but this is simply a button callback: it does not see the Entry widget, so it does not know what is the object we would like to get_text().

Solution? Not so simple, we need to rewrite the sample in a OOP fashion, to have a context where we can see the Entry widget get_text() value.

[indent=4]

uses
    Gtk

def on_button1_clicked (source : Button) : void
    source.label = "Clicked!"
    stderr.printf ("Clicked! --> ")

def on_window1_destroy (source: Window) : void
    /* When window close signal received */
    Gtk.main_quit()

init
    Gtk.init (ref args)
    new MainWindow ()
    Gtk.main ()

// main window definition

class MainWindow : Window

    // this class variable allow us to use its get_text() value
    entry : Entry

    def spool_text()
        stderr.printf ("%s\n", entry.get_text())

    // class constructor
    init

        var builder = new Builder()

        /* Getting the glade file */
        try
            builder.add_from_file ("sample.ui")
        except ex : GLib.Error
            print "Error: %s", ex.message
            Process.exit(-1)

        builder.connect_signals (null);

        var main_window = builder.get_object ("window1") as Window
        // "entry" Entry was already defined at class level
        entry = builder.get_object ("entry1") as Entry
        var button = builder.get_object ("button1") as Button

        /* connect the spool_text callback to the button's event */
        button.clicked.connect(spool_text)

        /* show the window */
        main_window.show_all ()

of course this tutorial is not intended to teach OOP, the callback on_button1_clicked outside of the scope of the MainWindow class but still related to its widget should be considered a bad programming sample.

Thanks for your attention, have a nice day.

How to code with Genie and Glade (first part)

this post is a rather dumb translation, for the genie language, of a tutorial written for his cousin language, vala.

the aim of the original tutorial (click here to read it) is to show how to use a glade user interface from a vala program. the ideas are:

  1. install vala and glade;
  2. build a simple ui with glade (i.e. an xml-based description of the interface);
  3. write a vala genie program to use this interface and perform some useful tasks (in this case, write a message to the standard error file descriptor);
  4. build and run

 

Very nice, and simple: let’s try to do the same with genie

the installation: on my OSX box (with port as package manager)

sudo port install vala glade

since vala and genie languages share the same translator to C, valac, no need for further installations.

the ui: let me shamelessly steal it  from here (and save it to a file named sample.ui)

the program: it is the one we have to rewrite in genie from vala. a breeze

[indent=4]

uses
    Gtk

def on_button1_clicked (source : Button) : void
    source.label = "Clicked!"
    stderr.printf ("Clicked! --> ")

def on_window1_destroy (source: Window) : void
    /* When window close signal received */
    Gtk.main_quit()

init

    Gtk.init (ref args)
    var builder = new Builder()

    /* Getting the glade file */
    try
        builder.add_from_file ("sample.ui")
    except ex : GLib.Error
        print "Error: %s", ex.message
        Process.exit(-1)

    builder.connect_signals (null);
    var window = builder.get_object ("window1") as Window
    var entry = builder.get_object ("entry1") as Entry
    var button = builder.get_object ("button1") as Button

    /* another way to do something when signal received */
    /* this will give a warning for deprecated syntax *|
    button.clicked += def(button)
        stderr.printf ("%s\n", entry.get_text())

    window.show_all ()
    Gtk.main ()

For a little improvement, I’ve added a trivial try…except block to control the ui file exists or exits the program.

finally build the program (save it to sample_glade_gtk.gs file)

valac --pkg gtk+-3.0  sample_glade_gtk.gs 

sample_glade_gtk.gs:35.5-38.5: warning: deprecated syntax, use `connect' 
     method instead

Compilation succeeded - 1 warning(s)

The program actually works: the residual problem we have is the warning that advise us we are using a deprecated syntax (anonymous function) for the instruction

    button.clicked += def(button)
        stderr.printf ("%s\n", entry.get_text())

 

Next time, we’ll see that to use the button.clicked.connect(some_callback) as suggested we’ll have to rewrite our sample in a OOP fashion.

 

Thanks for your attention, have a nice day.

Tutorial: How to code with Vala and Glade? Simple!

time to leverage this fine tutorial. stay tuned.

Radioactive bytes.

Today, I’m going to show you how to code a simple and small Glade interface application in Vala using Gtk.builder.

Screenshot from 2013-01-30 05:18:52

Special thanks for my friend Ahmed Shams. He helps me a lot 🙂

Every Glade program consists of two files: the glade UI file and the program (the code) itself.

Glade uses a simple method to connect with the code while Glade uses signals to tell the code that the user interacted with a widget (clicked, hovered, selected etc…)

For example: when we create a button, In glade side we attach a signal to it, ex:”clicked”, in the code side we will use something like “when signal button_clicked received: do something” Got it? 😀

First, we will use Glade to build our simple UI that will be used in our program.

If you haven’t installed glade yet, install it using:

 sudo apt-get install glade

Then run it and start…

View original post 384 altre parole

tornare alle cose, il setup

vi sono mancato? non credo proprio, in fondo per tornare su questi argomenti bastano pochi comandi (almeno su OSX): con questi, ad esempio, ci prepariamo a macinare milionate e milionate di righe

git clone https://github.com/LMDB/lmdb.git

e

git clone https://github.com/dw/py-lmdb.git
python setup.py install

con questo, invece, ad archiviarle con destrezza

conda install h5py

Fetching package metadata .......
Solving package specifications: ..........

The following packages will be downloaded:

package | build
 ---------------------------|-----------------
 hdf5-1.8.17 | 1 1.7 MB
 h5py-2.6.0 | np111py27_2 827 KB
 pytables-3.2.3.1 | np111py27_0 1.7 MB
 ------------------------------------------------------------

 

che software sono? così minimi che fanno ridere. ma non riderete, per quello che (ci) farò.

 

 

algoritmi di JOIN: l’eredità dei DBMS ai tempi dei key-value store.

portate pazienza, si tratta di un post concettuale. abbiamo appena o stiamo per sostituire o affiancare, nei nostri programmini, agli ormai tradizionali DBMS (postgresql, mysql, sqlite – tanto per esemplificare) un qualche brillante key-value store (redis, riak, o il velocissimo lmdb – anche qui per esemplificare).

il key-value store si presenta logicamente come una pseudotabella di soli due campi (chiave, valore) dove la chiave indicizza il valore permettendone il ritrovamento all’interno della tabella. un altro modello logico di comprensione del key-value store è quello dell’array associativo – un vettore di valori indicizzati per chiave (di solito una stringa) – reso persistente su disco.

va tutto bene, anzi una meraviglia – solo che prima o poi mi accorgo che devo mettere in una qualche relazione dati immagazzinati in due pseudotabelle diverse. oops, ma per queste cose con il DBMS avrei fatto una bella JOIN mentre, sorpresa, i key-value store non implementano l’algebra relazionale. 
ah ok è un classico caso del principio detto di faenza – si fa senza; andiamo solo a vedere come fanno i DBMS ad implementare le join, poi le riproporremo funzionalmente nel nostro codice applicativo.

per fortuna qualcuno su wikipedia si è preso il disturbo di tramandare ai posteri tutta questa scienza: ecco infatti come funzionano, in linea di principio, le nested loop join, le hash join, le sort-merge join: buona lettura.
ora, qualcuno potrebbe pensare, e non avrebbe tutti i torti, che stiamo facendo un gigantesco passo all’indietro se dopo quarant’anni circa di database relazionale ci tocca reimplementare le join a manina: è un’opinione legittima.

lmdb (e py-lmdb): dentro OpenLDAP si nasconde la nuova lepre dei database key/value store

sembra che ci sia un nuovo sceriffo in città. il suo nome è Lightning MDB (lmdb): è un key/value store (logicamente si presenta come un semplice tabellone con due campi, una chiave ed un valore) ai benchmark fa faville (batte anche levelDb di google). ah, in giro non si trova facilmente – è però a disposizione con la distribuzione di OpenLDAP.

ovviamente c’è l’interfaccia per python, py-lmdb, eccola qui.

fosse tutto qui non sarebbe davvero male, ma non molto interessante. quando ho provato ad usarlo però – su un esempietto facile facile (trovare le righe doppie in un file da 7M di righe circa) – ho mandato in vacca il programma per aver provato a fare tutto in un’unica transazione: la bestiaccia mi ha dato MDB_TXN_FULL (errore -30788) cioè “Txn has too many dirty pages”.

uh-uh, sembra ci sia un limite hard-coded (cioè “inchiodato” nel codice) alla dimensione max di una transazione, così almeno riporta la mailing list di openLDAP assieme alla (consueta) promessa che il limite verrà tosto eliminato.

già, ma nel frattempo? beh, visto che py-lmdb si porta appreso una copia dei sorgenti di lmdb si può provare ad inchiodarci un valore più elevato (non risolverò del tutto ma almeno sposto il confine più avanti). cerca cerca (mi piace vincere facile, lmdb sono in tutto quattro soli file) ecco finalmente in midl.h la riga responsabile (la riga 60)

#define MDB_IDL_LOGN    16  /* DB_SIZE is 2^16, UM_SIZE is 2^17 */

è stato sufficiente impostare il valore a 24 e ricompilare il module. per comodità mia ho fatto una copia del modulo con il (nuovo) nome lmbdXXL (extra-large) in modo da poter tenere a disposizione anche l’originale e fare così tutti i confronti del caso. l’interfaccia tramite cpython funziona (la cffi no, boh devo ancora capire).

astenersi perditempo seriali

esempio banale che illustra come poter dormire per più di un secondo al secondo.

#! /usr/bin/env python

import multiprocessing
from time import time, sleep
import random
import sys, os

# how big is the process pool

POOLSIZE = 5

# how many (named) works to process

BEDS = [“b0”, “b1”, “b2”, “b3”, “b4”, “b5”, “b6”, “b7”, “b8”, “b9”]
sleepList = BEDS[0:POOLSIZE] * 10

    
def PerdiTempo(aSleepName):
    currtime = time()
    name = multiprocessing.current_process().name
    rc = random.randint(1,10)
    sleep(rc)
    sys.stderr.write(“name %s, pid: %d – (bed %s) – sleep %d. time elapsed %f\n” % (name, os.getpid(), aSleepName, rc, time() – currtime))
    return rc

if __name__ == “__main__”:
    currtime = time()
    print “%s started, pid: %d, pool size: %d” % (sys.argv[0], os.getpid(), POOLSIZE)
    print “to sleep:”, sleepList
    po = multiprocessing.Pool(POOLSIZE)
    res = po.map_async(PerdiTempo,(i for i in sleepList))
    w = sum(res.get())
    print “total time lost: %d (sec.)” % (w,)
    elap = time() – currtime
    print ‘pid: %d ended, pool size of %d workers. time elapsed: %f (sec.). speedup: %5.2fx’ % (os.getpid(), POOLSIZE, elap, w/elap)

primavera: è tempo per i massive open online courses

sono stato distratto da qualche altra attività nell’ultimo mese, ma cmq tutto bene. l’ultima mia passione compulsiva – fresca fresca di stamane, sono i MOOC (massive open online courses), corsi online aperti per formazione a distanza. mi sono pure iscritto al mio primo mooc, Introduction to Data Science, che guarda caso utilizza i miei stessi building blocks (python, sql, R in misura minore) preferiti.