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

About this user

Korakot Chaovavanich http://korakot.stumbleupon.com

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

Get LAST_INSERT_ID from Symbian DBMS

   1  
   2  # table schema
   3  # CREATE TABLE person (id COUNTER, name VARCHAR)
   4  
   5  db = e32db.Dbms()
   6  db.begin()  # begin transaction (lock other inserts)
   7  db.execute(u"INSERT INTO person(name) VALUES 'korakot' ") # insert a new row
   8  
   9  dbv = e32db.Db_view()
  10  dbv.prepare(db, u"SELECT id FROM person ORDER BY id DESC")
  11  dbv.first_line()
  12  dbv.get_line()
  13  last_id = dbv.col(1)  # get it!
  14  
  15  db.commit()  # commit the transaction

Keep light on using thread

Copy-paste version
   1  
   2  import e32, miso, thread
   3  running = 1
   4  def lighton():
   5    while running:
   6      miso.reset_inactivity_time()
   7      e32.ao_sleep(5)
   8  
   9  thread.start_new_thread(lighton, ())
  10  # end by set running = 0


2 functions (lighton, lightoff) version.
   1  
   2  import e32
   3  import miso
   4  import thread
   5  
   6  flag = 1
   7  def _lighton():
   8      while flag:
   9          miso.reset_inactivity_time()
  10          e32.ao_sleep(5)
  11  
  12  def lighton():
  13      thread.start_new_thread(_lighton, ())
  14  
  15  def lightoff():
  16      global flag
  17      flag = 0

Simple thread in python

Taken from this article.

   1  
   2  import time
   3  import thread
   4  
   5  def myfunc(string,sleeptime):
   6      while 1:
   7          print string
   8          time.sleep(sleeptime)
   9  
  10  thread.start_new_thread(myfunc,("Thread No:1",2))
  11  # Then do other things.

classmethod and staticmethod

   1  
   2  class K(object):
   3  
   4    # normal method (instance method)
   5    def method1(self):
   6      print 'obj.method1() becomes method1(obj)'
   7  
   8    # class method
   9    def method2(cls):
  10      print 'K.method2() becomes method2(K)'
  11    method2 = classmethod(method2)
  12  
  13    # static method
  14    def method3():
  15      print 'K.method3() become just method3()'
  16    method3 = staticmethod(method3)
  17  
  18  obj = K()
  19  obj.method1()
  20  K.method2()
  21  K.method3()

Sending html mail with embedded image

See detail in this recipe.
The code below show the key parts of embedding an image.
   1  
   2  # require the new email package
   3  from email.MIMEMultipart import MIMEMultipart
   4  from email.MIMEText import MIMEText
   5  from email.MIMEImage import MIMEImage
   6  
   7  ...
   8  ...
   9  msgRoot = MIMEMultipart('related')
  10  ...
  11  ...
  12  
  13  # Assumes the image is in current directory
  14  fp = open('test.jpg', 'rb')
  15  msgImage = MIMEImage(fp.read())
  16  fp.close()
  17  
  18  # Define the image's ID as referenced above
  19  msgImage.add_header('Content-ID', '<image1>')
  20  msgRoot.attach(msgImage)
  21  
  22  ...
  23  smtp.sendmail(strFrom, strTo, msgRoot.as_string())
  24  ...

Gallery thumbnails

   1  
   2  from appuifw import *
   3  from graphics import Image
   4  from key_codes import *
   5  #from status import *
   6  #from e32db import format_time
   7  import os, e32
   8  
   9  dir = u'C:\\Nokia\\Images\\_PAlbTN\\'
  10  os.chdir(dir)
  11  fs = os.listdir('')
  12  mtime = os.path.getmtime
  13  # newest first
  14  fs.sort(lambda a,b: cmp(mtime(b), mtime(a)))
  15  
  16  app.body = canvas = Canvas()
  17  # show just 16 images
  18  for k in range(min(16, len(fs))):
  19      j, i = divmod(k, 4)
  20      im = Image.open(dir + fs[k])
  21      canvas.blit(im, target=(2+44*i, 2+34*j))
  22  canvas.rectangle([(0,0), (43,33)], 0xff, width=2)  # selected
  23  
  24  x, y, k = 0, 0, 0
  25  def move(dx, dy):
  26      global x, y, k
  27      canvas.rectangle([(44*x,34*y), (44*x+43,34*y+33)], 0xffffff, width=2)  
  28      k = 4*y + x + 4*dy + dx
  29      y, x = divmod(k, 4)
  30      canvas.rectangle([(44*x,34*y), (44*x+43,34*y+33)], 0xff, width=2)
  31      if 0 <= k < len(fs):
  32          app.title = u''+fs[k]
  33          #status_on(format_time(mtime(fs[k])))
  34  
  35  # move cursor and open image
  36  canvas.bind(EKeyUpArrow,   lambda: move(0,-1))
  37  canvas.bind(EKeyDownArrow, lambda: move(0,1))
  38  canvas.bind(EKeyLeftArrow, lambda: move(-1,0))
  39  canvas.bind(EKeyRightArrow,lambda: move(1,0))
  40  canvas.bind(EKeySelect,    lambda: Content_handler().open(dir[:-8]+fs[k]))
  41  
  42  # standard code for non-loop app
  43  lock = e32.Ao_lock()
  44  app.exit_key_handler = lock.signal
  45  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.
   1  
   2  from __future__ import generators
   3  import e32db, re
   4  db = e32db.Dbms()
   5  dbv = e32db.Db_view()
   6  db.open(u'C:\\test.db')
   7  
   8  # Some helping classes (need more in next version)
   9  class String:
  10      pass
  11  
  12  class Integer:
  13      pass
  14  
  15  class Float:
  16      pass
  17  
  18  class column:
  19      def __init__(self, coltype):
  20          self.coltype = coltype

Here's the mother of all your classes that map to database tables.
   1  
   2  class Mapper(object):
   3      def __init__(self, id=None, **kw):
   4          if id is None:
   5              self.id = self._insert(**kw)
   6          else:
   7              self.id = id
   8      def _insert(self, **kw):
   9          names = ','.join(kw.keys())
  10          values = ','.join([self.quote(k,v) for k,v in kw.items()])
  11          tablename = self.__class__.__name__
  12          q = u"INSERT INTO %s(%s) VALUES (%s)" % (tablename, names, values)
  13          db.execute(q)
  14          # get last insert ID
  15          dbv.prepare(db, u'SELECT id FROM '+tablename+' ORDER BY id DESC')
  16          dbv.first_line()
  17          dbv.get_line()
  18          return dbv.col(1)
  19      def __getattr__(self, name):
  20          if name in self.mapping.__dict__:
  21              q = 'SELECT '+name+' FROM '+self.__class__.__name__
  22              q += ' WHERE id='+str(self.id)
  23              dbv.prepare(db, unicode(q))
  24              dbv.first_line()
  25              dbv.get_line()
  26              return dbv.col(1)
  27          else:
  28              return self.__dict__[name]
  29      def __repr__(self):
  30          return '<%s id=%d>' % (self.__class__.__name__, self.id)
  31      def quote(self, name, value):
  32          if self.mapping.__dict__[name].coltype == String:
  33              return "'%s'" % value.replace("'", "''")  # encode single quote
  34          else:
  35              return str(value)
  36      def __setattr__(self, name, value):
  37          if name in self.mapping.__dict__:
  38              q = 'UPDATE '+self.__class__.__name__+' SET '+name+'='
  39              q += self.quote(name, value) + " WHERE id=" + str(self.id)
  40              db.execute(unicode(q))
  41          else:
  42              self.__dict__[name] = value
  43      def set(self, **kw):
  44          q = "UPDATE "+self.__class__.__name__+" SET "
  45          for k, v in kw.items():
  46              q += k+'='+self.quote(k,v)+','
  47          q = q[:-1]+" WHERE id=%s" % self.id
  48          db.execute(unicode(q))
  49      def delete(self):
  50          q = 'DELETE FROM '+self.__class__.__name__+" WHERE id=" + str(self.id)
  51          db.execute(unicode(q))
  52          self.id = None
  53      def dict(self):
  54          names = [k for k in self.mapping.__dict__.keys() if not k.startswith('__')]
  55          q = 'SELECT '+','.join(names)+' FROM '+self.__class__.__name__
  56          q += ' WHERE id=' + str(self.id)
  57          dbv.prepare(db, unicode(q))
  58          dbv.first_line()
  59          dbv.get_line()
  60          dct = {'id': self.id}
  61          for i in range(dbv.col_count()):
  62              dct[names[i]] = dbv.col(i+1)
  63          return dct
  64      def select(cls, where=None, orderby=None):
  65          q = 'SELECT id FROM '+cls.__name__
  66          if where:
  67              q += ' WHERE '+where
  68          if orderby:
  69              q += ' ORDER BY '+orderby
  70          dbv = e32db.Db_view()  # need its own cursor
  71          dbv.prepare(db, unicode(q))
  72          dbv.first_line()
  73          for i in range(dbv.count_line()):
  74              dbv.get_line()
  75              yield cls(dbv.col(1))
  76              dbv.next_line()
  77      select = classmethod(select)

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

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.
   1  
   2  >>> import e32db
   3  >>> db = e32db.Dbms()
   4  >>> dbv = e32db.Db_view()
   5  >>> db.open(u'C:\\test.db')  # might need db.create(...)

Here's the query simplification code.
   1  
   2  def Q(sql):
   3      if sql.upper().startswith('SELECT'):
   4          dbv.prepare(db, unicode(sql))
   5          dbv.first_line()
   6          rows = []
   7          maxlen = [0] * dbv.col_count()
   8          for i in range(dbv.count_line()):
   9              dbv.get_line()
  10              result = []
  11              for i in range(dbv.col_count()):
  12                  try:
  13                      val = dbv.col(i+1)
  14                  except:    # in case coltype 16
  15                      val = None
  16                  result.append(val)
  17                  maxlen[i] = max(maxlen[i], len(str(val)))
  18              rows.append(result)
  19              dbv.next_line()
  20          fmt = '|'+ '|'.join(['%%%ds' % n for n in maxlen]) + '|'
  21          for row in rows:
  22              print fmt % tuple(row) 
  23      else:
  24          n = db.execute(unicode(sql))
  25          print '%d rows affected' % n

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

Old and new-style class

Old style class
   1  
   2  class K:
   3    ...

New style class
   1  
   2  class K(object):
   3    ...

Some features such as properties are only avaiable in new-style class.
Learn more about New-style class

isinstance and issubclass

   1  
   2  >>> class P(object):  # parent class
   3  	pass
   4  
   5  >>> class K(P):       # subclass
   6  	pass
   7  
   8  >>> k = K()           # instace
   9  >>> isinstance(k, K)
  10  True
  11  >>> isinstance(k, P)
  12  True
  13  >>> isinstance(K, P)  # K is a class
  14  False
  15  
  16  >>> issubclass(K, P)
  17  True
  18  >>> issubclass(k, P)  # k is not a class
  19  
  20  TypeError: issubclass() arg 1 must be a class
  21  
  22  >>> isinstance(K, type)  # a class is an instace of type
  23  True
  24  >>> isinstance(k, type)  # not a class
  25  False
« Newer Snippets
Older Snippets »
Showing 11-20 of 176 total