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 393 total

Optimization - Minimum - Search and Golden Rule

   1  
   2  from math import sin
   3  def f(x):
   4      return ((x**4))
   5  
   6  def optMinSearch(f, xi, h, t=1.0e-9):
   7      ssx = xi
   8      x = xi
   9      fx = f(x)
  10      sx = x
  11      x += h
  12      fxn = f(x)
  13      n = 0
  14  
  15      while abs(fxn-fx) > t :
  16          while fx > fxn:
  17              n += 1
  18              fx = fxn
  19              ssx = sx
  20              sx = x
  21              x += h
  22              fxn = f(x)
  23      
  24          xx = x
  25          h = h / 2
  26          x = ssx
  27          fx = f(x)
  28          sx = x
  29          x += h
  30          fxn = f(x)
  31          n += 1
  32      
  33      
  34      return x, fxn, n, sx, xx
  35  
  36  
  37      
  38  
  39  def optMinGold(f, xi, xf, t=1.0e-9):
  40      # constants
  41      A = 0.6180339887
  42      
  43      n = 0
  44      
  45      x1 = xi
  46      x2 = xf
  47  
  48      x3 = x1 + A * (x2-x1)
  49      x4 = x2 - A * (x2-x1)
  50      
  51      fx3 = f(x3)
  52      fx4 = f(x4)
  53      
  54      while abs(x2-x1) > t:
  55          #print n, x1, x2, abs(x2-x1)
  56          n+=1
  57          if fx3 < fx4:
  58          # fx4 > fx3
  59              x1 = x4
  60              x4 = x3
  61              x3 = x1 + A * (x2-x1)
  62          else:
  63           # fx4 < fx3
  64              x2 = x3
  65              x3 = x4
  66              x4 = x2 - A * (x2-x1)
  67          
  68          fx3 = f(x3)
  69          fx4 = f(x4)
  70          
  71      return (x1,x2,n)
  72  
  73  
  74  xmin, fmin, n, sx, xx = optMinSearch(f, -2.0, 0.1)
  75  print xmin
  76  print fmin
  77  print n
  78  print "-----"
  79  
  80  
  81  (x1,x2,n) = optMinGold(f, -2.0, 2.0)
  82  print x1
  83  print f(x1)
  84  print x2
  85  print f(x2)
  86  print n

Euler and Range-Kutta

   1  
   2  from math import floor
   3  from math import cos
   4  
   5  def euler(xi, yi, f, xf, h):
   6      x = xi
   7      y = yi
   8      xlist = []
   9      ylist = []
  10      
  11      n = int(floor(xf-xi)/h)
  12  
  13      for i in range(0,n):
  14          xlist.append(x)
  15          ylist.append(y)
  16          m = f(x, y)
  17          y = y + h*m
  18          x = x + h
  19          i+=1
  20      
  21      return map(None, xlist, ylist)
  22  
  23  def rk(xi, yi, f, xf, h):
  24          x = xi
  25          y = yi
  26          xlist = []
  27          ylist = []
  28  
  29          n = int(floor(xf-xi)/h)
  30  
  31          for i in range(0,n):
  32              xlist.append(x)
  33              ylist.append(y)
  34              m1 = f(x, y)
  35              m2 = f(x+h/2, y+m1/2)
  36              m3 = f(x+h/2, y+m2/2)
  37              m4 = f(x+h, y+m3)
  38              y = y + h*(m1/6 + m2/3 + m3/3 + m4/6)
  39              x = x + h
  40              i+=1
  41  
  42          return map(None, xlist, ylist)
  43  
  44  def f(x, y):
  45      return (-y+cos(4*x))/4
  46  
  47  
  48  t = euler(0.0, -1.0, f, 5.0, 0.4)
  49  # # TODO erro
  50  # #
  51  # 
  52  for x,y in t:
  53       print "%f, %f" % (x,y)
  54  
  55  
  56  # print "---------------------------"
  57  # # hi = 0.2
  58  # # hf = 0.05
  59  # # h = hi
  60  # # s = []
  61  # # qc = []
  62  # # ec = []
  63  # # 
  64  # # r1 = rk(1.0, 2.0, f, 2.0, 1.0)
  65  # # r2 = rk(1.0, 2.0, f, 2.0, 0.5)
  66  # # r3 = rk(1.0, 2.0, f, 2.0, 0.25)
  67  # # 
  68  # # 
  69  # # qc = (r2[0][1]-r1[0][1]) / (r3[0][1]-r2[0][1])
  70  # # print qc
  71  # 
  72  # # while h >= hf:
  73  # #     r = rk(1.0, 2.0, f, 10.0, h)
  74  # #     s.append(r)
  75  # #     h = h / 2
  76  # # 
  77  # # 
  78  # # for j in range(0, len(s[0])):
  79  # #     for i in range(0, len(s)-2):
  80  # #         div = (s[i+2][4*j][1] - s[i+1][2*j][1]) # S''-S'
  81  # #         if div == 0:
  82  # #             break
  83  # # 
  84  # #         t = (s[i+1][2*j][1] - s[i][j][1]) / div # (S'-S)/div com div = (S''-S')<=>(S'-S)/(S''-S')
  85  # #         qc.append(t)
  86  # #         # t = div / 15
  87  # #         # ec.append(t)
  88  # 
  89  # for i in range(0, len(qc)):
  90  #     print qc[i]
  91  # #    print "%f  ---  %f" % (s[0][i][0], qc[i])
  92  # #qc ~= 16 implica validade => podemos usar os valores do erro: e => qualidade
  93  # # for i in range(0, len(qc)):
  94  # #     print "S=%.12f, S'=%.12f, S''=%.12f\n\t=> qc=%.12f\n" \
  95  # #             % (s[i][], s[i+1], s[i+2], qc[i])

Simpson's Rule - Importing From CSV file

   1  
   2  import csv
   3  
   4  class simpsonCsv:
   5      def __init__(self, filename):
   6          reader = csv.reader(open(filename, "rb"))
   7  
   8          xlist = []
   9          ylist = []
  10          
  11          for row in reader:
  12              try:
  13                 x = float(row[0])
  14                 y = float(row[1])
  15              except TypeError:
  16                  continue
  17              except ValueError:
  18                  continue
  19              xlist.append(float(x))
  20              ylist.append(float(y))
  21          
  22          self.len = len(xlist) - 1
  23          self.xstart = xlist[0]
  24          self.xend = xlist[self.len]
  25          self.interval = self.xend / self.len
  26          
  27          self.data = map(None, xlist, ylist)
  28      
  29      def f(self, x):
  30          for (u,v) in self.data:
  31              if u == x:
  32                  return v
  33                  
  34          print "Bad x value (probably bad n): %s" % (x)
  35          return None
  36          
  37          
  38      
  39      def simpson(self, n):
  40          "Approximate the definite integral of f from a to b by Simpson's rule."
  41  
  42          if self.len % n != 0:
  43              print "Error: %d mod %d is not zero but should be." % (self.len, n)
  44              return -1
  45          
  46          
  47          h  = float(self.xend - self.xstart)/n
  48          
  49      
  50          si = 0.0
  51          sp = 0.0
  52          xk = 0.0
  53      
  54          for i in range(1, n, 2):
  55              xk = self.xstart + i*h
  56              si += self.f(xk)
  57      
  58          for i in range(2, n, 2):
  59              xk = self.xstart + i*h
  60              sp += self.f(xk)
  61          
  62          
  63          s = 2*sp + 4*si + self.f(self.xstart) + self.f(self.xend)
  64  
  65          return (h/3)*s
  66      
  67  
  68  filename = "integral_tabela_CO2_csv.csv"
  69  s = simpsonCsv(filename)
  70  
  71  print s.simpson(20)
  72  print s.simpson(40)
  73  print s.simpson(60)
  74  print s.simpson(100)
  75  print s.simpson(300)
  76  print s.simpson(600)
  77  print s.simpson(900)
  78  print s.simpson(1800)

Simpson's Rule

   1  
   2  from math import log, cos
   3  def simpson(f, a, b, n):
   4      "Approximate the definite integral of f from a to b by Simpson's rule."
   5  
   6      if n % 2 != 0:
   7          print "Ups: n must be even!"
   8          return -1
   9          
  10      h  = (float(b) - a)/n
  11      
  12      si = 0.0
  13      sp = 0.0
  14      
  15      for i in range(1, n, 2):
  16          xk = a + i*h
  17          si += f(xk)
  18      
  19      for i in range(2, n, 2):
  20          xk = a + i*h
  21          sp += f(xk)
  22          
  23          
  24      s = 2*sp + 4*si + f(a) + f(b)
  25  
  26      return (h/3)*s
  27  
  28  # def f(x):
  29  #     return x**4
  30  def f(x):
  31      return (log(x+1)**(1+cos(x)))
  32  
  33  print simpson(f, 3, 4, 2)
  34  exit()
  35  
  36  ni = 50
  37  nf = 1000000
  38  n = ni
  39  a = -20
  40  b = 0
  41  s = []
  42  qc = []
  43  ec = []
  44  t = 0.0
  45  div = 0.0
  46  i = 0.0
  47  
  48  
  49  # Calcular S para diferentes valores de n [n(i+1) = ni * 2]
  50  # para poder ter S (h), S' (h'=h/2), S'' (h''=h/4)
  51  while n < nf:
  52      t = simpson(f, a, b, n)
  53      s.append(t)
  54      n = n * 2
  55  
  56  # Calcular quociente (S'-S)/(S''-S') [que deve ser aprox igual a 16]
  57  # e erro em que e = (S''-S')/15
  58  for i in range(0, len(s)-2):
  59      div = (s[i+2] - s[i+1]) # S''-S'
  60      if div == 0:
  61          break
  62      
  63      t = (s[i+1] - s[i]) / div # (S'-S)/div com div = (S''-S')<=>(S'-S)/(S''-S')
  64      qc.append(t)
  65      t = div / 15
  66      ec.append(t)
  67  
  68  #qc ~= 16 implica validade => podemos usar os valores do erro: e => qualidade
  69  for i in range(0, len(qc)):
  70      print "S=%.12f, S'=%.12f, S''=%.12f\n\t=> qc=%.12f, e=%.12f\n" \
  71              % (s[i], s[i+1], s[i+2], qc[i], ec[i])
  72  

Bisection, Rope and Newton Methods

   1  
   2  from math import log
   3  
   4  def bisect(f, a, b, e):
   5  	""" Determines zero between a and b using Bisection. """
   6  	n = 0
   7  	fa = f(a)
   8  	if fa == 0.0: return (a, n)
   9  	fb = f(b)
  10  	if fb == 0.0: return (b, n)
  11  		
  12  	while (abs(a-b) > e):
  13  		c = 0.5*(a+b)
  14  		fc = f(c)
  15  		
  16  		if fc == 0.0: return (c, n)
  17  		n = n + 1
  18  		if fb*fc < 0.0:
  19  			a = c
  20  			fa = fc
  21  		
  22  		else:
  23  			b = c
  24  			fb = fc
  25  	
  26  		
  27  	if fa < fb:
  28  		return (a, n)
  29  	else:
  30  		return (b, n)
  31  
  32  def rope(f, a, b, e):
  33  	""" Determines zero between a and b using the Rope methode. """
  34  	n = 0
  35  	fa = f(a)
  36  	if fa == 0.0: return (a, n)
  37  	fb = f(b)
  38  	if fb == 0.0: return (b, n)
  39  	
  40  	while (abs(a-b) > e):
  41  		c = (a*fb - b*fa) / (fb - fa)
  42  		fc = f(c)
  43  		if fc == 0.0: return (c, n)
  44  		n = n + 1
  45  		if fb*fc < 0:
  46  			a = c
  47  			fa = fc
  48  		
  49  		else:
  50  			b = c
  51  			fb = fc
  52  		
  53  	
  54  	if fa < fb:
  55  		return (a, n)
  56  	else:
  57  		return (b, n)
  58  
  59  # Note: must verify that for the function f and guess c
  60  #		the method will _converge_.
  61  def newton(f, df, c, t):
  62  	""" Determines zero between a and b using Newton """
  63  	n = 0
  64  	fc = f(c)
  65  	if fc == 0.0: return (c, n)
  66  	
  67  	
  68  	while (True):
  69  		fc = f(c)
  70  		dfc = df(c)
  71  		if dfc == 0:
  72  			print "dfc is 0"
  73  			return (0, -1)
  74  		
  75  		dc = -fc/dfc
  76  		
  77  		c = c + dc
  78  		n = n + 1
  79  		print c
  80  		if abs(dc) < t: return (c, n)
  81  	
  82  		
  83  
  84  ##Tests
  85  #def f(x): return -log(x)+4.0
  86  #def df(x): return -1.0/x
  87  #x= bisect(f, 1, 70, 0.00000001)
  88  #print x
  89  #x = rope(f, 1, 70, 0.00000001)
  90  #print x
  91  #x = newton(f, df, 0.1, 0.0001)
  92  #print x
  93  
  94  def f(x): return (x+2)*log(2*x**3)+3.0
  95  def df(x): return log(2*x**3)+(3*(x+2))/x
  96  
  97  x,y = newton(f, df, 1.0, 0.0001)
  98  print x,y

Gaussian Elimination

// description of your code here

   1  
   2  # this requires numpy get it from http://numpy.sf.net
   3  
   4  from copy import deepcopy
   5  from numpy import *
   6  
   7  
   8  # this function, swapRows, was adapted from
   9  # Numerical Methods Engineering with Python, Jean Kiusalaas
  10  def swapRows(v,i,j):
  11  	"""Swaps rows i and j of vector or matrix [v]."""
  12  	if len(v) == 1:
  13  		v[i],v[j] = v[j],v[i]
  14  	else:
  15  		temp = v[i].copy()
  16  		v[i] = v[j]
  17  		v[j] = temp
  18  	
  19  def pivoting(a, b):
  20  	"""changes matrix A by pivoting"""
  21  	
  22  	n = len(b)
  23  	
  24  	for k in range(0, n-1):
  25  		p = int(argmax(abs(a[k:n, k]))) + k
  26  		if (p != k):
  27  			swapRows(b, k, p)
  28  			swapRows(a,k,p)
  29  
  30  def gauss(a, b, t=1.0e-9, verbose=False):
  31  	""" Solves [a|b] by gauss elimination"""
  32  	
  33  	n = len(b)
  34  	
  35  	# make copies of a and b so as not to change the values in the arguments
  36  	tempa = deepcopy(a)
  37  	tempb = deepcopy(b)
  38  	
  39  	# check if matrix is singular
  40  	if abs(linalg.det(tempa)) < t:
  41  		print "asn"
  42  		return -1
  43  	
  44  	pivoting(tempa, tempb)
  45  
  46  	for k in range(0,n-1):	
  47  		for i in range(k+1, n):
  48  			if tempa[i,k] != 0.0:
  49  				m = tempa[i,k]/tempa[k,k]
  50  				if verbose:
  51  				    print "m =", m
  52  				tempa[i,k+1:n] = tempa[i,k+1:n] - m * tempa[k,k+1:n]
  53  				tempb[i] = tempb[i] - m * tempb[k]
  54  	
  55  	# Back substitution
  56  	for k in range(n-1,-1,-1):
  57  		tempb[k] = (tempb[k] - dot(tempa[k,k+1:n], tempb[k+1:n]))/tempa[k,k]
  58  
  59  	return tempb
  60  
  61  def residue(a, b, c):
  62      """Calculates the residue of a system solved by gauss elimination"""
  63      n = len(b)
  64  
  65      t = a * c # t is the A with the values of x replaced (an [n x n] matrix) 
  66  
  67      s = []
  68      for i in range(0, n):
  69          s.append(sum(t[i])) # s is the solution
  70  
  71  
  72      res = b - s # res is the residue
  73  
  74      return res
  75  
  76  # 1) dA = Somar uma pequena quantidade a A
  77  # 2) dB = Somar uma pequena quantidade a B
  78  # 3) A.dX = dB - dA.x0
  79  
  80  def disturb(a, b, ai, bi):
  81      """Calculates the extarnal disturbance cause by da and db"""
  82      
  83      x = gauss(a, b)
  84      
  85      n = len(b)
  86      
  87      da = array([1])
  88      da.resize(n, n)
  89      da.fill(ai)
  90      
  91      print "da = ", da
  92      
  93      db = array([1])
  94      db.resize(1, n)
  95      db.fill(bi)
  96      
  97      print "db = ", db
  98      
  99      t = db - da*x
 100      nx = gauss(a, t)
 101  
 102      return nx
 103      
 104  
 105  
 106  #a = array([[1.0, 2.0, 0.0],[-1.0, 2.0, 3.0],[1.0, 4.0, 1.0]])
 107  #b = array([3.0, -1.0, 4.0])
 108  #a = array([[-1.414214, 2, 0],[1, -1.414214, 1], [0, 2, -1.414214]])
 109  #b = array([1.0,1.0,1.0])
 110  #a = array([[2.0, 2.0, 2.0],[1.0, 1.0, 5.0], [2.0, 5.0, 1.0]])
 111  #b = array([6.0, 7.0, 8.0])
 112  #a = array([[1.001, 2.001, 3.001],[0.999, 2.0, 2.999], [1.002, 1.999, 2.999]])
 113  #b = array([4.003, 4.001, 3.999])
 114  
 115  a = array([[0.7, 8.0, 3.0],[-6.0, 0.45, -0.25], [8.0, -3.1, 1.05]])
 116  b = array([2.3, 3.5, 10.3])
 117  
 118  x = gauss(a, b)
 119  print "Solution = ", x
 120  
 121  #sol = linalg.solve(a, b)
 122  #print "linalg Solution = ", sol
 123  
 124  #y = residue(a, b, x)
 125  #print "Residue = ", y
 126  
 127  #u = gauss(a, y)
 128  #print "Residue destribution = ", u
 129  
 130  #z = gauss(a, b+y)
 131  #print "New Solution (with added residue) = ", z
 132  
 133  #y2 = residue(a, b+y, z)
 134  #print "Residule of new solution = ", y2
 135  
 136  
 137  #if linalg.norm(y2) < linalg.norm(y):
 138  #    print "New solution has a smaller residue."
 139  #else:
 140  #    print "Original solution has a smaller residue."
 141  
 142  nx = disturb(a, b, 0.5, 0.5)
 143  print "Disturbed Solution = ", nx

gzip pipe

#! /usr/bin/python

from gzip import GzipFile
from StringIO import StringIO

class GZipPipe(StringIO) :
"""This class implements a compression pipe suitable for asynchronous
process.

Only one buffer of data is read/compressed at a time.
The process doesn't read the whole file at once : This improves performance
and prevent hight memory consumption for big files."""

# Size of the internal buffer
CHUNCK_SIZE = 1024

def __init__(self, source = None, name = "data") :
"""Constructor

@param source Source data to compress (as a stream/File/Buffer - anything with a read() method)
@param name Name of the data within the zip file"""

# Source file
self.source = source

# OEF reached for source ?
self.source_eof = False

# Buffer
self.buffer = ""

StringIO.__init__(self)

# Inherited constructor

# Init ZipFile that writes to us (the StringIO buffer)
self.zipfile = GzipFile(name, 'wb', 9, self)

def write(self, data) :
"""The write mzthod shouldn't be called from outside.
A GZipFile was created with this current object as a output buffer anbd it
fills it whenever we write to it (calling the read method of this object will do it for you)
"""

self.buffer += data

def read(self, size = -1) :
"""Calling read() on a zip pipe will suck data from the source stream.

@param size Maximum size to read - Read whole compressed file if not specified.
@return Compressed data"""

# Feed the zipped buffer by writing source data to the zip stream
while ((len(self.buffer) < size) or (size == -1)) and not self.source_eof :

# No source given in input
if self.source == None: break

# Get a chunk of source data
chunk = self.source.read(GZipPipe.CHUNCK_SIZE)

# Feed the source zip file (that fills the compressed buffer)
self.zipfile.write(chunk)

# End of source file ?
if (len(chunk) < GZipPipe.CHUNCK_SIZE) :
self.source_eof = True
self.zipfile.flush()
self.zipfile.close()
break


# We have enough data in the buffer (or source file is EOF): Give it to the output
if size == 0:
result = ""
if size >= 1 :
result = self.buffer[0:size]
self.buffer = self.buffer[size:]
else : # size < 0 : All requested
result = self.buffer
self.buffer = ""

return result

Split array or string into smaller arrays

Splits an array or string into smaller arrays of the given size. Inspired on the ruby one ;).

   1  
   2  import math
   3  # v = value to split, l = size of each chunk
   4  f = lambda v, l: [v[i*l:(i+1)*l] for i in range(int(math.ceil(len(v)/float(l))))]


Example

   1  
   2  >>> f('000000111111222222333333444444567', 6)
   3  ['000000', '111111', '222222', '333333', '444444', '567']
   4  
   5  >>> f(tuple('000000111111222222333333444444567'), 6)
   6  [('0', '0', '0', '0', '0', '0'), ('1', '1', '1', '1', '1', '1'), ('2', '2', '2', '2', '2', '2'), ('3', '3', '3', '3', '3', '3'), ('4', '4', '4', '4', '4', '4'), ('5', '6', '7')]


Long live python :). Of course, a lisp/haskell implementation probably blows this snippet out.

Pattern Matching based WSGI-enabled URL routing tool.

Actual version on http://pypi.python.org/pypi/decoroute

   1  
   2  easy_install decoroute


Example:

   1  
   2  import decoroute
   3      
   4  app = decoroute.App()
   5      
   6  def render_response(status = '200 OK', **kw):
   7      # try your favorite templating engine here
   8      return status, [('Content-Type', 'text/plain')], [str(kw)]
   9  
  10  def redirect_to(env, endpoint, **kw):
  11      return '302 FOUND', [('Content-Type', 'text/plain'), \
  12      ('Location', '%s://%s%s' % (env['wsgi.url_scheme'], env['HTTP_HOST'], \
  13      env['decoroute.app'].url_for(endpoint, **kw)))], ['']
  14      
  15  @app.expose('/node', id = '1')
  16  @app.expose('/node/<id:\d+>')
  17  def node(env, id):
  18      return render_response(id = id)
  19      
  20  @app.expose('/url_for')
  21  def url_for(env):
  22      return render_response( \
  23          url = env['decoroute.app'].url_for(node, id = 666))
  24      
  25  @app.expose('/302')
  26  def found(env):
  27      return redirect_to(env, not_found)
  28      
  29  @app.expose('/404')
  30  def not_found(env):
  31      raise decoroute.NotFound()
  32      
  33  @app.not_found()
  34  def not_found_handler(env):
  35      return render_response('404 NF', url = env['PATH_INFO'])
  36      
  37  from wsgiref.simple_server import make_server
  38      
  39  make_server('', 5555, app).serve_forever()


Complete source < 100 lines of code:

   1  
   2  #!/usr/bin/env python
   3  # vim:ts=4:sw=4:et
   4  # -*- coding: utf-8 -*-
   5  # $Id: decoroute.py,v 6eb37aeee5cd 2008/06/09 07:38:26 vsevolod $
   6  #
   7  # Pattern Matching based WSGI-enabled URL routing tool.
   8  # Actual version on http://pypi.python.org/pypi/decoroute
   9  # (C) 2008 by Vsevolod S. Balashov <vsevolod@balashov.name>
  10  # under terms of GNU LGPL v2.1 http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
  11  
  12  __author__ = "Vsevolod Balashov"
  13  __email__ = "vsevolod at balashov dot name"
  14  
  15  import re
  16  from sets import ImmutableSet
  17  import wsgistraw
  18  
  19  __all__ = ['NotFound', 'App']
  20  
  21  class NotFound(Exception):
  22      pass
  23  
  24  _pattern_re = re.compile(r'''
  25      ([^<]+)                     # static rule data
  26      (?:<
  27          ([a-zA-Z][a-zA-Z0-9_]*) # variable name
  28          \:
  29          ([^>]+)                 # regexp constraint
  30      >)?
  31  ''', re.VERBOSE)
  32  
  33  def pattern2regexp(pattern, f, s = lambda x: re.escape(x)):
  34      def parser():
  35          for t in _pattern_re.findall(pattern):
  36              yield s(t[0])
  37              if t[1] != '':
  38                  yield f(t[1], t[2])
  39      return parser()
  40  
  41  make_url_for = lambda p: ''.join(pattern2regexp(p, lambda v, r: '%%(%s)s' % v, lambda s: s))
  42  make_variables = lambda p: filter(lambda x: x, pattern2regexp(p, lambda v, r: v, lambda s: None))
  43  make_pattern = lambda p: r''.join(pattern2regexp(p, lambda v, r: r'(?P<%s>%s)' % (v, r)))
  44  make_selector_fragment = lambda p: r''.join(pattern2regexp(p, lambda v, r: r'(?:%s)' % r))
  45  make_selector = lambda i: re.compile(r'(^%s$)' % r'$)|(^'.join(map(make_selector_fragment, i)))
  46  
  47  class UrlMap(object):
  48      def __init__(self):
  49          self._endpoints = {}
  50          self._patterns = {}
  51          self._pattern_selector = make_selector(self._patterns.iterkeys())
  52      
  53      def add(self, pattern, endpoint, **kw):
  54          if self._patterns.has_key(pattern):
  55              raise Exception('duplicate pattern', pattern)
  56          self._endpoints[(endpoint, ImmutableSet(make_variables(pattern)))] = make_url_for(pattern)
  57          self._patterns[pattern] = (re.compile(make_pattern(pattern)), endpoint, kw)
  58          self._pattern_selector = make_selector(self._patterns.iterkeys())
  59      
  60      def route(self, url):
  61          try:
  62              p = self._patterns.values()[re.match(self._pattern_selector, url).lastindex - 1]
  63              d = re.match(p[0], url).groupdict().copy()
  64              d.update(p[2])
  65              return p[1], d
  66          except:
  67              raise NotFound('route not found', url)
  68      
  69      def url_for(self, endpoint, **kw):
  70          return self._endpoints[(endpoint, ImmutableSet(kw.keys()))] % kw
  71  
  72  class App(object):
  73      def __init__(self, key = 'decoroute.app'):
  74          self._key = key
  75          self._map = UrlMap()
  76          self._not_found = lambda e: ('404 NOT FOUND', [("Content-Type", "text/plain")], [''])
  77      
  78      @wsgistraw.app
  79      def __call__(self, env):
  80          try:
  81              env[self._key] = self
  82              endpoint, kw = self._map.route(env['PATH_INFO'])
  83              return endpoint(env, **kw)
  84          except NotFound:
  85              return self._not_found(env)
  86      
  87      def expose(self, pattern, **kw):
  88          def decorate(f):
  89              self._map.add(pattern, f, **kw)
  90              return f
  91          return decorate
  92      
  93      def not_found(self):
  94          def decorate(f):
  95              self._not_found = f
  96              return f
  97          return decorate
  98      
  99      def url_for(self, endpoint, **kw):
 100          return self._map.url_for(endpoint, **kw)

Get a Jaiku personal_key given a username and password

Logs into Jaiku and then gets the personal_key for using the API.

   1  
   2  def GetJaikuPersonalKey(user, password):
   3    """Finds the Jaiku API personal_key from a username and password.
   4  
   5    One day I'll learn to use urllib2 properly and cookie parsing and stuff.
   6    """
   7  
   8    # login and find a cookie
   9    login_url = "http://jaiku.com/login"
  10    request_body = urllib.urlencode({'log': user,
  11                                     'pwd': password,
  12                                     'rememberme': '1'})
  13    # Open a connection to the authentication server.
  14    auth_connection = httplib.HTTPConnection('jaiku.com')
  15    # Begin the POST request to the client login service.
  16    auth_connection.putrequest('POST', '/login')
  17    # Set the required headers for an Account Authentication request.
  18    auth_connection.putheader('Content-type',
  19                              'application/x-www-form-urlencoded')
  20    auth_connection.putheader('Content-Length', str(len(request_body)))
  21    auth_connection.endheaders()
  22    auth_connection.send(request_body)
  23    auth_response = auth_connection.getresponse()
  24    if auth_response.status == 303:
  25      cookie_str = auth_response.getheader("set-cookie")
  26      # TODO(ark) parse this properly!
  27      res = re.search("(jaikuuser_[^;]*).*(jaikupass_[^;]*)", cookie_str)
  28      if res:
  29        auth_cookie = "%s; %s" % (res.group(1), res.group(2))
  30        apikey_url = "http://api.jaiku.com/key"
  31        req = urllib2