Category Archives: Python

Just learning Python and this is puzzling me

Is there no constants in Python? Otherwise why can you do this??

import numpy as np
np.nan = 0
print(np.nan == np.nan, np.isnan(np.nan))  # True False

The operator can return different type depending on input and you have to check the return type. And I guess someone thought it is a great idea designing it?

df = pd.DataFrame([{'Name': 'Alice'},
                   {'Name': 'Jack'},
                   {'Name': 'Helen'}],
print(type(df.loc['group1'])) # pandas.core.frame.DataFrame
print(type(df.loc['group2'])) # pandas.core.series.Series

print(type(df.loc[df.index == 'group2'])) # workaround to always get DataFrame

Another way to treat missing values (the most illogical as to me)

print(np.nan == np.nan, np.nan != np.nan) # False True

Personal File Sharing

If you need easy accessible personal file store, there are a lot of them on the web. Another solution is to use google blobstore service – a geek’s choise 🙂

import urllib
from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp.util import run_wsgi_app

class MainHandler(webapp.RequestHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload')
        <body style="font-family:arial,sans-serif;">
        <form action="%s" method="POST" enctype="multipart/form-data">
        Upload File:<br/>
        <input type="file" name="file"/>
        <input type="submit" name="submit" value="Submit"/>
        </form>""" % upload_url)
        for b in blobstore.BlobInfo.all():
                <a href="/serve/%s">%s</a>
                (<a href="/delete/%s">Delete</a>)"""
                % (str(b.key()), str(b.filename), str(b.key())))

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, resource):
        resource = str(urllib.unquote(resource))
        blob_info = blobstore.BlobInfo.get(resource)
        self.send_blob(blob_info, save_as=blob_info.filename)

class DeleteHandler(webapp.RequestHandler):
    def get(self, resource):
        resource = str(urllib.unquote(resource))
        blob_info = blobstore.BlobInfo.get(resource)

def main():
    application = webapp.WSGIApplication(
          [('/', MainHandler),
           ('/upload', UploadHandler),
           ('/delete/([^/]+)?', DeleteHandler),
           ('/serve/([^/]+)?', ServeHandler),
          ], debug=True)

if __name__ == '__main__':

Configuring Eclipse on Windows to Use With Google App Engine

The post “Configuring Eclipse on Windows to Use With Google App Engine” on Google has not been updated since 2008. Here is the updated version for Eclipse 3.7 (Indigo).

Before you start, download and install the following components:

Python Google App Engine Calculator

Couple of months ago, accidentally I found myself on a conference for Python developers. I thought “what the hell am I doing here”. Ok, now I got into an interesting project and have to learn Python… 🙂

My first program – Calculator:)

import webapp2

class MainPage(webapp2.RequestHandler):
    def get(self):
        # build a list of operations
        f = {'+': lambda x, y: str(float(x) + float(y)),
             '-': lambda x, y: str(float(x) - float(y)),
             '*': lambda x, y: str(float(x) * float(y)),
             '/': lambda x, y: str(float(x) / float(y)),
             'C': lambda x, y: "",
        # get page parameters
        x = self.request.get('x')
        y = self.request.get('y')
        operator = self.request.get('operator')
        # calculate 
        result = ""
            result = f[operator](x, y)
        except ValueError:
            result = "Error: Incorrect Number"
        except ZeroDivisionError:
            result = "Error: Division by zero"
        except KeyError:
        # build HTML response
        buttons = "".join(["<input type='submit' name='operator' value='"
                           + o + "'>" for o in sorted(f.keys())])
            <form action='/' method='get' autocomplete='off'> 
            <input type='text' name='x' value='%s'/><br/>
            <input type='text' name='y'/><br/> 
            </html>""" % (result, buttons))

app = webapp2.WSGIApplication([('/', MainPage)], debug=True)