Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-20 of 105 total

Gallery thumbnails

from appuifw import *
from graphics import Image
from key_codes import *
#from status import *
#from e32db import format_time
import os, e32

dir = u'C:\\Nokia\\Images\\_PAlbTN\\'
os.chdir(dir)
fs = os.listdir('')
mtime = os.path.getmtime
# newest first
fs.sort(lambda a,b: cmp(mtime(b), mtime(a)))

app.body = canvas = Canvas()
# show just 16 images
for k in range(min(16, len(fs))):
    j, i = divmod(k, 4)
    im = Image.open(dir + fs[k])
    canvas.blit(im, target=(2+44*i, 2+34*j))
canvas.rectangle([(0,0), (43,33)], 0xff, width=2)  # selected

x, y, k = 0, 0, 0
def move(dx, dy):
    global x, y, k
    canvas.rectangle([(44*x,34*y), (44*x+43,34*y+33)], 0xffffff, width=2)  
    k = 4*y + x + 4*dy + dx
    y, x = divmod(k, 4)
    canvas.rectangle([(44*x,34*y), (44*x+43,34*y+33)], 0xff, width=2)
    if 0 <= k < len(fs):
        app.title = u''+fs[k]
        #status_on(format_time(mtime(fs[k])))

# move cursor and open image
canvas.bind(EKeyUpArrow,   lambda: move(0,-1))
canvas.bind(EKeyDownArrow, lambda: move(0,1))
canvas.bind(EKeyLeftArrow, lambda: move(-1,0))
canvas.bind(EKeyRightArrow,lambda: move(1,0))
canvas.bind(EKeySelect,    lambda: Content_handler().open(dir[:-8]+fs[k]))

# standard code for non-loop app
lock = e32.Ao_lock()
app.exit_key_handler = lock.signal
lock.wait()

ORM for pys60

I have asked for this a few months.
Here's my own first version for an ORM.
It's adapted from SQLAlchemy and SQLObject.
(and whatever library I have searched)

You need to create a database manually first.
My previous snippets (shell, SQL) may help.
from __future__ import generators
import e32db, re
db = e32db.Dbms()
dbv = e32db.Db_view()
db.open(u'C:\\test.db')

# Some helping classes (need more in next version)
class String:
    pass

class Integer:
    pass

class Float:
    pass

class column:
    def __init__(self, coltype):
        self.coltype = coltype

Here's the mother of all your classes that map to database tables.
class Mapper(object):
    def __init__(self, id=None, **kw):
        if id is None:
            self.id = self._insert(**kw)
        else:
            self.id = id
    def _insert(self, **kw):
        names = ','.join(kw.keys())
        values = ','.join([self.quote(k,v) for k,v in kw.items()])
        tablename = self.__class__.__name__
        q = u"INSERT INTO %s(%s) VALUES (%s)" % (tablename, names, values)
        db.execute(q)
        # get last insert ID
        dbv.prepare(db, u'SELECT id FROM '+tablename+' ORDER BY id DESC')
        dbv.first_line()
        dbv.get_line()
        return dbv.col(1)
    def __getattr__(self, name):
        if name in self.mapping.__dict__:
            q = 'SELECT '+name+' FROM '+self.__class__.__name__
            q += ' WHERE id='+str(self.id)
            dbv.prepare(db, unicode(q))
            dbv.first_line()
            dbv.get_line()
            return dbv.col(1)
        else:
            return self.__dict__[name]
    def __repr__(self):
        return '<%s id=%d>' % (self.__class__.__name__, self.id)
    def quote(self, name, value):
        if self.mapping.__dict__[name].coltype == String:
            return "'%s'" % value.replace("'", "''")  # encode single quote
        else:
            return str(value)
    def __setattr__(self, name, value):
        if name in self.mapping.__dict__:
            q = 'UPDATE '+self.__class__.__name__+' SET '+name+'='
            q += self.quote(name, value) + " WHERE id=" + str(self.id)
            db.execute(unicode(q))
        else:
            self.__dict__[name] = value
    def set(self, **kw):
        q = "UPDATE "+self.__class__.__name__+" SET "
        for k, v in kw.items():
            q += k+'='+self.quote(k,v)+','
        q = q[:-1]+" WHERE id=%s" % self.id
        db.execute(unicode(q))
    def delete(self):
        q = 'DELETE FROM '+self.__class__.__name__+" WHERE id=" + str(self.id)
        db.execute(unicode(q))
        self.id = None
    def dict(self):
        names = [k for k in self.mapping.__dict__.keys() if not k.startswith('__')]
        q = 'SELECT '+','.join(names)+' FROM '+self.__class__.__name__
        q += ' WHERE id=' + str(self.id)
        dbv.prepare(db, unicode(q))
        dbv.first_line()
        dbv.get_line()
        dct = {'id': self.id}
        for i in range(dbv.col_count()):
            dct[names[i]] = dbv.col(i+1)
        return dct
    def select(cls, where=None, orderby=None):
        q = 'SELECT id FROM '+cls.__name__
        if where:
            q += ' WHERE '+where
        if orderby:
            q += ' ORDER BY '+orderby
        dbv = e32db.Db_view()  # need its own cursor
        dbv.prepare(db, unicode(q))
        dbv.first_line()
        for i in range(dbv.count_line()):
            dbv.get_line()
            yield cls(dbv.col(1))
            dbv.next_line()
    select = classmethod(select)

Here's how you create your class.
class Person(Mapper):
    class mapping:
        # doesn't need id = column(Integer)
        name = column(String)
        age = column(Integer)

Getting phone model

I put Korakot snippet (Looking up phone model using firmware code) into an useful module.

You need miso module.
All info can be found at this site

#
# Firmware.py  infos found at http://homepage.mac.com/alvinmok/nokia/firmware.html
#

'''
firmware.prefix_name 
firmware.suffix_name 
firmware.phone_model
firmware.phone_cpu_speed
'''
import sysinfo
import miso

ECPUSpeed = 0x0B

mapping_firmware_model={
  'RM-51': '3230',
  'RM-38': '3250',
  'NHM-10': '3600',
  'NHM-10X': '3620',
  'NHL-8': '3650',
  'NHL-8X': '3660',
  'RM-25': '6260',
  'RM-29': '6260b',
  'NHL-10': '6600',
  'NHL-12': '6620',
  'NHL-12X': '6620',
  'RM-1': '6630',
  'RH-67': '6670',
  'RH-68': '6670b',
  'RM-36': '6680',
  'RM-57': '6681',
  'RM-58': '6682',
  'RH-51': '7610',
  'RH-52': '7610b',
  'NHL-2NA': '7650',
  'RM-49': 'E60-1',
  'RM-89': 'E61-1',
  'RM-10': 'E70-1',
  'RM-24': 'E70-?',
  'NEM-4': 'N-Gage',
  'RH-29': 'N-Gage QD (asia/europe)',
  'RH-47': 'N-Gage QD (americas)',
  'RM-84': 'N70-1',
  'RM-99': 'N70-5',
  'RM-67': 'N71-1',
  'RM-112': 'N71-5',
  'RM-91': 'N80-3',
  'RM-92': 'N80-1',
  'RM-42': 'N90-1',
  'RM-43': 'N91-1',
  'RM-158': 'N91-5' }

mapping_prefix_description ={
 'N':'Mobile Phone',
 'R':'Computing Device',
 'T':'Terminal'}

mapping_suffix_description ={
    'B': 'GSM 900/1900',
    'C': 'DAMPS 800',
    'D': 'CDMA/AMPS 800',
    'E': 'GSM 900/1800',
    'F': 'NMT-450',
    'K': 'GSM 1800',
    'L': 'GSM 900/1800/1900 or GSM 850/1800/1900',
    'M': 'EGSM 900/1800 (may include WCDMA)',
    'N': 'IEEE 802.11b',
    'P': 'CDMA 800',
    'W': 'AMPS/TDMA 800/1900',
    'X': 'ETACS/TACS'}

sw = sysinfo.sw_version()
sw_list = sw.split(' ')

firmware_version = sw_list[1]
firmware_date = sw_list[2]
firmware_code=sw_list[3]

temp = firmware_code.split('-')
firmware_prefix = temp[0][0]
firmware_suffix = temp[0][-1]

prefix_name = mapping_prefix_description[firmware_prefix]
suffix_name = mapping_suffix_description[firmware_suffix]
phone_model = mapping_firmware_model[firmware_code] 
phone_cpu_speed = miso.get_hal_attr(ECPUSpeed) # CPU speed in Hz


usage:
>>>import firmware
>>>firmware.phone_model
>>>'6600'
>>>firmware.phone_cpu_speed
>>>104000

Interactive SQL shell

To help myself learning about SQL in Symbain DBMS, I write
a small script to act as an interactive SQL shell.
First you need to connect to the database.
>>> import e32db
>>> db = e32db.Dbms()
>>> dbv = e32db.Db_view()
>>> db.open(u'C:\\test.db')  # might need db.create(...)

Here's the query simplification code.
def Q(sql):
    if sql.upper().startswith('SELECT'):
        dbv.prepare(db, unicode(sql))
        dbv.first_line()
        rows = []
        maxlen = [0] * dbv.col_count()
        for i in range(dbv.count_line()):
            dbv.get_line()
            result = []
            for i in range(dbv.col_count()):
                try:
                    val = dbv.col(i+1)
                except:    # in case coltype 16
                    val = None
                result.append(val)
                maxlen[i] = max(maxlen[i], len(str(val)))
            rows.append(result)
            dbv.next_line()
        fmt = '|'+ '|'.join(['%%%ds' % n for n in maxlen]) + '|'
        for row in rows:
            print fmt % tuple(row) 
    else:
        n = db.execute(unicode(sql))
        print '%d rows affected' % n

After that, playing with SQL is quite simple.
>>> Q("CREATE TABLE person (id COUNTER, name VARCHAR)")
0 rows affected
>>> Q("INSERT INTO person(name) VALUES ('Korakot')")
1 rows affected
>>> Q("INSERT INTO person(name) VALUES ('morning_glory')")
1 rows affected
>>> Q("SELECT * from person")
|0|      Korakot|
|1|morning_glory|

SQL for Symbian DBMS

I have summarized the allowable SQL below.
# 'SELECT' is the most popular SQL
SELECT select-list FROM table-name [ WHERE search-condition ] [ ORDER BY sort-order ] 
# 3 search condition types: compare, like, null

# DML : INSERT, DELETE, UPDATE 
INSERT INTO table-name [ ( column-identifier,… ) ] VALUES ( column-value,… ) 
DELETE FROM table-name [ WHERE search-condition ] 
UPDATE table-name SET update-column,… [ WHERE search-condition ] 

# DDL : Work with the schema
CREATE TABLE table-name (column-definition,…) 
DROP TABLE table-name 
ALTER TABLE table-name { ADD add-column-set [ DROP drop-column-set ] | DROP drop-column-set } 
CREATE [ UNIQUE ] INDEX index-name ON table-name ( sort-specification,… ) 
DROP INDEX index-name FROM table-name 

Plus a few column types (not all of them)
['BIT', 'INTEGER', 'COUNTER', 'BIGINT', 'FLOAT',
 'TIMESTAMP', 'VARCHAR(n)', 'LONG VARCHAR']
# COUNTER is an auto-incremented unsigned integer

Tag cloud using Text()


from appuifw import *
app.body = t = Text()

fonts = [u'', u'LatinPlain12', u'LatinBold12', u'LatinBold13', u'LatinBold17', u'LatinBold19']
tags = [(1, "apache"), (1, "array"), (1, "bash"), (1, "c"), (1, "cli"), (1, "csharp"), (1, "css"),
  (1, "database"), (1, "date"), (1, "expressionengine"), (1, "file"), (2, "html"), (1, "image"),
  (2, "java"), (4, "javascript"), (1, "lighttpd"), (1, "linux"), (1, "mac"), (1, "math"), (1, "mysql"),
  (1, "osx"), (1, "perl"), (3, "php"), (1, "pys60"), (5, "python"), (4, "rails"), (1, "regex"),
 (4, "ruby"), (1, "rubyonrails"), (1, "series"), (3, "series60"), (1, "servers"), (2, "shell"), (2, "sql"),
 (1, "ssh"), (1, "string"), (1, "text"), (1, "time"), (1, "unix"), (1, "web"), (1, "windows"), (1, "xml"),]

for level, tag in tags:
    t.font = fonts[level]
    t.add(tag + u' ')

See screenshot.

If using font is not enough, we can use other styles or colors.
See a related snippet.

Generate tone frequency using au file

The first part of my attempt to produce a tone sound.
from struct import pack
from math import sin, pi

def au_file(name='out.au', freq=400, length=2, A=0.5):
	f = open(name, 'wb')
	f.write('.snd')
	f.write(pack('>5L', 24, -1, 2, 8000, 1))
	T = 8000./freq
	for i in range(length*8000):
		angle = 2*pi*i/T
		val = pack('b', A*sin(angle)*127)
		f.write(val)
	f.close()

The reason that I use '.au' instead of '.wav' is that
the format is much simpler. Both are supported on my 6600 phone.

Here's the second step, after removing some bug.
(data size can't be -1, I must calculate it too)
from struct import pack
from math import pi, sin
import e32, audio 

def tone(freq=440, duration=1000, volume=0.5):
    f = open('D:\\out.au', 'wb')    # temp file
    f.write('.snd' + pack('>5L', 24, 8*duration, 2, 8000, 1))  #header
    for i in range(duration*8):
        sin_i = sin(i * 2*pi*freq/8000)  # sine wave
        f.write(pack('b', volume*127*sin_i))
    f.close()
    # now play the file
    s = audio.Sound.open('D:\\out.au')
    s.play()
    while s.state()==2: # playing
        e32.ao_yield()
    s.close()

The code is still quite slow. I'm not sure why (haven't test).
Either because of sin() or pack() or f.write()
A solution could be using a smaller file and play it multiple times.
But this small code should be enough to demonstrate an idea.

Preview available fonts

>>> from appuifw import *
>>> fonts = available_fonts()
>>> fonts.sort()
>>> t = Text()
>>> for f in fonts:
...   t.font = f
...   t.add(f + ' ')
...
>>> app.body = t

See screenshot.

Bouncing rectangle in python

This is taken partly from the random rectangle script. It bounces a rectangle round the screen leaving a trail in different colors.

from appuifw import *
import e32
from random import randrange

running = 1
def quit():
	global running
	running = 0
app.exit_key_handler = quit

app.screen = 'large'
app.body = canvas = Canvas()
res_x, res_y = canvas.size

dy = 1
dx = 1
x1 = 10
y1 = 10

while running:
	x1 = x1 + dx
	y1 = y1 + dy
	x2 = x1 + 10
	y2 = y1 + 10
	if (x1 < 1):
		dx = -1 * dx
	if (y1 < 1):
		dy = -1 * dy
	if (x1 > res_x - 15):
		dx = -1 * dx
	if (y1 > res_y - 15):
		dy = -1 * dy
	color = randrange(0xffffff)
	canvas.rectangle((x1, y1, x2, y2), fill=color)
	e32.ao_yield()// insert code here..

Formatting time

>>> from e32db import format_time
>>> from time import *
>>> t = time()
>>>
>>> format_time(t)   # for Symbian SQL
u'06/03/2006 23:26:35'
>>> strftime('%d/%m/%Y %H:%M:%S')  # like above
'06/03/2006 23:26:39'
>>> ctime()
'Mon Mar 06 23:26:49 2006'
>>> strftime("%a, %d %b %Y %H:%M:%S +0000")  # email RFC
'Mon, 06 Mar 2006 23:26:59 +0000'

Here's the (shortened) table for strftime.
%a  weekday name.  
%A  weekday name (full).  
%b  month name.  
%B  month name (full).  
%c  date and time (locale)
%d  day of month [01,31].  
%H  hour [00,23].  
%I  hour [01,12].  
%j  day of year [001,366].  
%m  month [01,12].  
%M  minute [00,59].  
%p  AM or PM
%S  Second [00,61]
%U  week of year (Sunday)[00,53].
 w  weekday [0(Sunday),6].
 W  week of year (Monday)[00,53].
 x  date (locale).
%X  time (locale).
%y  year [00,99].
%Y  year [2000].
%Z  timezone name.  
« Newer Snippets
Older Snippets »
Showing 11-20 of 105 total