Monday, March 17

Get started with Scrapy

As usual I setup the virtual environment and just pip install packages: lxml and Scrapy, lxml being the prerequisite. But this time it failed with following error:


It seems it tried to build lxml with packages libxml2 and libxsit from anaconda. Anaconda is a python distribution I installed to my machine, enabling easy installation of many scientific packages like scipy, matplotlib and pandas. It is strange because in virtual environment the python distribution should be the one within the environment.

After poking around, I found I had following line in my ~/.bash_profile:
# added by Anaconda 1.8.0 installer
export PATH="//anaconda/bin:$PATH"

It looks like to be added automatically when I installed Anaconda, making the python distribution in Anaconda the default one. In my virtual environment, where the supposed python distribution should be the virtual one, when I install packages, it still look for the system default one. By removing the line from bash profile, it seems fine now.

[TODO]


Monday, March 3

Basic mongodb administration

Recently picked up mongodb for the ongoing project. It is a popular NoSQL database; I prefer to call it schema-less database, and that is also why I use it: the data goes into the database does not have to follow any predefined schema like they do in SQL ones. This is perfect for any exploratory data analysis like we do when we have to constantly add/delete items/attributes for your data. Previously I use SQL database, in which I have to rebuild the database every time if any new stuff is added; it is painful.

In this post I include a few commands to quickly get you started with regular administration with mongodb.
mongod --dbpath /srv/mongodb/

This initiates the mongodb server with predefined local database path.
mongodump --dbpath /data/db/ --out /data/backup/
This uses mongodump creates a backup for the entire database you point to.
mongorestore --dbpath <database path> <path to the backup>
This restores/dumps a backup copy into defined database.

I will update once I come across necessary commands.

Thursday, May 23

Basic of R

Objects - variables

use c() to create a collection of data and assign them to a variable.

metallicaNames<-c("Lars", "James", "Kirk", "Rob")

Dataframes

A dataframe is similar to a spreadsheet, an object that containing several objects. To combine different objects.

metallica<-data.frame(Name=metallicaNames, Age=metallicaAges)

To add column to a dataframe

metallica$chidAge<-c(12, 12, 4, 6)

To see the column names of a dataframe

names(metallica)

Create a list: a list of separate objects


> metallica2<-list(metallicaNames, metallicaAges)
> metallica2
[[1]]
[1] "Lars"  "James" "Kirk"  "Rob"

[[2]]
[1] 47 47 48 46

> metallica2[1]
[[1]]
[1] "Lars"  "James" "Kirk"  "Rob"

> metallica2[2]
[[1]]
[1] 47 47 48 46

Dates

To create date type objects

birth_data<-as.Date(c("1977-07-03", "1969-05-24", "1973-06-21", "1970-07-16", "1949-10-10", "1983-11-05", "1987-10-08", "1989-09-16", "1973-05-20", "1984-11-12"))

Coding variable

It is used to indicate different groups for participants, such as "Tablet" and "Phone" group. First we create collection of different numbers to indicate the different group, and then assign them to corresponding factors using factor().


> job<-c(rep(1, 5), rep(2, 5))
> job
 [1] 1 1 1 1 1 2 2 2 2 2
> job<-factor(job, levels=c(1:2), labels=c("Lecturer", "Student"))
> job
 [1] Lecturer Lecturer Lecturer Lecturer Lecturer Student  Student  Student
 [9] Student  Student
Levels: Lecturer Student

Alternative to create coding variables

job<-gl(2, 5, labels=c("Lecturer", "Student"))

Importing data

csv -> dataframe
lecturerData2 = read.csv("Lecturer Data.dat", header=TRUE)

dat or txt -> dataframe
lecturerData2<-read.delim("Lecturer Data.dat", header=TRUE)

to navigate to different directory we could use setwd("xx/xx")

Manipulating data

select a part of data

newDataf <- oldDataf[rows, frames]

lecturerPersonality <- lecturerData[, c("friends", "alcohol", "neurotic")]
lecturerOnly <- lecturerData[job=="Lecturer",]
alcoholPersonality <- lecturerData[alcohol > 10, c("friends", "alcohol", "neurotic")]

stack the dataframe (wide -> long)

select columns to be stacked on top of each other


satisfactionStacked<-stack(satisfactionData, select=c("Satisfaction_Base", "Satisfaction_6_Months", "Satisfaction_12_Months", "Satisfaction_18_Months"))



Sunday, October 7

Measure cache parameters

1. to use gettimeofday()
Note from unix manual, if you use it in C, you have to add "struct" before "timeval xx". Also, include <sys/time.h> instead of <time.h>, because the former is where the struct timeval get defined.

2.

Tuesday, October 2

Step by step https client/server building

Server side with apache, mysql and python scripting on ec2 ubuntu server 12.04; client side with android 2.3 and sqlite built-in. Also, both of them have secure tls connection ability.

I will go directly into the topic. Start with server side. For a basic http server on ec2 using apache, refer here. Note in this article the environment is actually different, instead of using source code to build the apache, I install apache directly using command apt-get install apache2. It surprisingly takes good care of all details and works well at least for now. The configuration is different in these two installation and I suggest you use apt-get.

When done installing, apache is already up to go. Default http configuration file is located at /etc/apache2/sites-available/default. If you fire up http://localhost you should be seeing "It works" page. This is page, index.html is located at /var/www, it serves as your site, where you could put all html files in and if your computer has an ip address, others could see your site by accessing the ip address. Another easier way to test if the server is working well is to use curl command, curl http://localhost and it will return the response of the server, which in this case the default index.html. Curl is easier to use when you want to test the response of server, you don't need any other clients to fire the request.

Now let's go into tls. I assume you already have the key file and cert file on your server. Put them into /etc/ssl/private and /etc/ssl/certs respectively, they are the default dir apache is looking at for key and cert files. Then follow this excellent doc to setup ssl module for apache. There is a default ssl configuration file you could customize: /etc/apache2/sites-available/default-ssl, it includes file directories of ssl request and so on. The default dir is the same as http connection, which is /var/www. If you put a different index.html in it, when you test using curl -k -3 https://localhost, k means accessing without any cert files and 3 is the version number of ssl protocol you are gonna use. This will give this page so that you know you are in a https connection.

Ok, now we have this ssl server working pretty well. There is one more step to go on the server side which is add the handler to deal with different requests. Now all we could request is the default page. We want more. Particularly, I need a handler that takes in a POST method, extract its data, and then put them into a table in mysql db on the server.

First to install mysql. apt-get install mysql-server mysql-client. Note, in ec2, you could directly sudo su, without typing in any password, go into root. just to make things easier, cause most of configurations and commands here need to root. Then, I install mysql python interface, python-mysqldb, you could install whatever you like, php, etc.

Then we will see how to use python script to handle http/https request. We use CGI (Common gateway interface); it is a way to make executable file like scripts request-able at client side. The default dir for cgi scripts is /usr/lib/cgi-bin. Put your scripts there and they should be immediately up for http request. Here is my echo python script:

Basically for a POST request with several key/value pairs, it will print out # of pairs and every pair. It uses a python module called cgi, and cgitb is another module to enable debugging function. Note the line 9 is necessary because it tells the server and client this is valid html text, otherwise client would probably throw out "invalid response" error. In fact CGI is not the best way to do script request, it is highly unstable when scripts get complex. But it is the easiest way to get it going. Now curl --data "key1=value1&key2=value2" https://localhost/cgi-bin/yourscript.py it will and should return the result of the script. Note --data is how you send POST request via curl.

To this point, the server setup should reach a happy ending. Now let's look at the client side. The very first thing you need to do is, in your android project, be sure to include the cert file of your server, maybe at /res/raw; it is required in tls connection. Details could be found here.

Assuming you know how to use httpClient in android, you should be already connecting your server and client. Have fun!






Monday, September 24

Apache http server on ec2

Now I get a little bit involved with server side. Have to setup a server for our projects. While the machine is not ready, I decide to first try setting up the server at aws ec2 platform to just have a taste.

I choose Apache because I know nothing about running a server and also this is the word I heard most of the time when people talk about server stuff. It is totally not hard to install it but there are some wrong turns that I took, turns that some guides would be appreciated.

Therefore, following is the walk to setup httpd on ec2.

First package to download is of course the apache httpd itself, 2.4.3 to-date. Extract it into a folder say ~/httpd. Note there is a subfolder named ~/httpd/srclib, which will be used later.

Second we got APR and APR-Util. They are required for httpd installation, which ec2 doesnt have (at least ubuntu server doesnt). Extract them and put them into subfolders ~/httpd/srclib/apr and ~/httpd/srclib/apr-util respectively. This tells httpd to install them along the way if the system does not have them already.

One side note, during the install process the system would probably ask you for root password, which you dont have if you are using a ec2 instance. Dont worry, just set it: use command sudo passwd root. Set your password you are good to go.

Before going into installation, install PCRE (Perl-Compatible Regular Expression Lib). If you are using the same server as me, just type sudo apt-get install libpcre3-dev.

Now do the old trick: ./configure, make, sudo make install. Note add --with-included-apr in ./configure so that it will look at srclib we prepare for it for apr and apr-util.

The make and install commands will take some time, so relax and waste your time on some stupid videos, like this one, which I quite like.

After installation, use apachectl -k start and apachectl -k stop to test the server. If you install correctly, when you start the server, issue curl http://localhost.com will get you the 'it works' html page, which tells you everything is good. Use locate if you cannot find apachectl.

Thanks for watching. I am talking about the video...

Friday, September 7

http/tls connection in python, android, EC2

Have a side project to build a standard tls package for the team. Ive never tried socket, so start with python just to get a feel. Following is my own experiment, to connect the server side code on EC2, and the client side code on my local laptop.

1. simple http
I use sample code from official doc. It is really simple. All you need to do other than code is configure the port for EC2 instance.

For the instance you are running, configure its security group so that the specific port you want to communicate on is open like 2727 above.

2. simple https
Things get rough with security. Basically, what I know about https, i.e. tls, is that it utilizes a public key identification system to secure the communication via http. The server has a private key, which is only known to itself. It also has a corresponding public key ready to distribute to anyone need to communicate with it. In order for the other side to trust it, the server has to have its public key certified by trusted 3rd party, called a Certificate Authority. Same with client side.

However, if we just want a connection between our own server and client, we could generate keys and certificates ourselves without paying for CA cert file. This is called self-signed certificate, or root CA certificate.


openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem


If you have openssl installed on your computer, you could use it to generate keys. In this case, I generate private key and certificate in the same file. Then I just copy it to the other side. Both sides use the same keys. Things are simpler here, for which most cases you might wanna use a more secure authority to certify for you.

Then both sides I use sample scripts from official doc again. Note for https connection you also have to open the port for ec2 instance.

3. simple https with android
With android things are bit complex with certificates. I have this cert.pem file, which is not enough for android. Bouncy Castle encryption is supported well by android, which is the one we are gonna use to generate client side key file.

First is to install Bouncy Castle. Note android is using a different version of it, version 145, not 146 from official site. Find one, download it, a jar file. Put it in the directory '/usr/libexec/java_home/lib/ext', where on mac should be '/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/ext'. Second, add following sentence into the jave.security file also located in lib folder:


Having keytool in your machine, do following with the cert.pem file:
Now you will have mykeystore.bks file in raw directory. I here use a der file because android returns 'wrong version of certificate' error. To generate der file from pem:


We are almost done here. Just grab any sample code for https connection in android, using whether httpURLconnection or httpclient, put correct password and file name into place, everything should be fine now.



Wednesday, August 22

iterate, iterate, iterate!

Gather around and learn some iterate stuff again. Great great tutorials here, here, and especially here.

1. iter()
this is a function, takes in an object, return its iterator. It corresponds to the __iter__() method in the class definition. We use it as:

An iterator supports next() methods, which returns the next element in the object. Such object, that supports __iter__() and next(), is called iterable. There will be two different scenario when we call __iter__() on an object:

  1. the class itself has implemented next() and __iter__(). In this case the __iter__() would most likely just return the object itself - the object is the iterator;
  2. __iter__() returns an object of another class, which should be an iterator class. In such case, the object that calls __iter__() does not have next() implemented, only the iterator class has next().

2. iterator
As described above, an iterator is an object that supports next(). Note objects support __iter__() are called iterable, for being able to return an iterator.

Before getting to the iterator, let's meet container. Container mostly time refers to an abstract data type, meaning a collection of arbitrary objects. Lists, dictionaries, arrays could all be called containers. So what does iterator do? As far as I know, iterator is an efficient way to walk through all objects in one container.

Instead of having all objects in the memory, an iterator only call and pick up one object a time by calling next(), until it hits the end of the container, where it will throw a StopIteration error. The for statement in python also call create an iterator automatically.

The life of an iterator is limited. It could only be iterated once, after which it will throw StopIteration if next() is called.

3. generator
The common case using an iterator would be: the iterator returns an object a time, then the program does some stuff on that object until objects are exhausted. In fact, most built-in data type in Python supports returning iterator as describe here.

A generator, on the other hand, could be considered a iterator with the ability to do stuff to objects: it picks up an object a time from a container, then instead of returning it directly, it does some stuff, and return the result of this process. It compresses code when you want to do complicate stuff on objects.

What is yield?

4. yield
Most generators created so far are created using yield. Yield often appears at places where return should be sitting at. Instead of simply returning whatever it follows, yield does an interesting process: the running code will return the statement following yield when it first meet it; at this time, the yield code will be suspended, i.e. paused but all its environment and variables get to survive; when the next time the code calls the generator again, it starts where it left previous time and continue until it hits yield again; then just repeat until the container is exhausted.

The code above, every time the for statement runs, it goes into the square generator, running until yield, return the square result and get back to the for statement.

What the advantage the generator brings is values it generates are creating on the air. It is different from the case that one first create all objects and then return them all or return one each time (iterator!). Generator is dynamic. Sometimes you dont know what to create until you actually run into the situation (gimme an example!).

One last note, both iterator and generator could only be walked once. Here is a subtle bug misusing generator.

5. why bother?
Speaking of why using iterator and generator. One major concern is the case that when you have a container that has so many objects if you put them all in memory it will just overflow, or super slow. If you will only use each object once or even you only want one particular object, it is more efficient to use them. Also, iterator and generator produce more clear and concise code.

By the way, I just know this is actually the predecessor of python. Looking good.

Tuesday, July 24

Euler project: Ulam spiral

Spiral like this:

This spiral is famous because it has the fact that most of prime number are present on the diagonal position of this rectangular.

Euler problem ask for the sum of all diagonal numbers like red ones above. The prime feature could not be used because not all diagonal positions are prime number. The hint is just every turn in this spiral, the length goes like: 1, 1, 2, 2, 3, 3, 4, 4,...

Since every turn is also the diagonal, except the first one, 2, use this length growth to build the sum is easy:

Every first odd turn should be taken care of because the actual diagonal number is the one before the turn number. Also, note the last turn is not included to form the required rectangular.

Sunday, July 15

Fibonacci and yield

Look at this problem 25 from euler project below:



Yes it is simple recursion:


But this one is like running forever. Considering the fact it needs the first number with 1000 digits, not surprising.

Then I start browsing and googling, met this one, using yield to generate fibonacci number; hell, when I saw the word "yield" I was like YEAH THATS IT:


When I run it I almost wet myself. So fast that makes you cant help but sing a song about it.

Basically, it returns a generator. Generator in python is lazy, it never actually calculates the next one until you force it by calling next. Old version every time it generates a new fib number, it goes to the very first and runs back one by one later. When number gets big the problem is like hell. Use generator however, you only do one addition every time, plus, in the while loop, you only return one number each time. Well I dont know you, but to a python rookie like me...


what happens to the old version? Still running.

Friday, July 13

Learning python: Iterator, Generator, Iterable object

An iterator is just like a fancy way to say "a for loop"; well it's not. I will walk through what I learn about those iters today.

There are three "iters" in Python:

  1. an iterator: it is an iteration object for a class, supported by two methods __iter__ and next. Classes support iteration object could create an iterator corresponding to themselves by iter method; then one could use next method to retrieve the next element in this class object. After calling the last element, two things happen: this iterator is exhausted and could not be used anymore; any more call would result in StopIteration exception. 
  2. a generator: it is a function to generate an iterator using yield. 
  3. an iterable object: treat it as a repeatable iterator

After definition, let's see some codes.

1. built-in iterators

See I create four iterators using iter method. For any class supports iterator you could create an iterator using iter. Moreover, when you just use for loop directly:

What happens behind the scene is, it will automatically create an iterator based on L, and then yield one element every time. Thus, when you are using for loop, you are basically implicitly calling i=iter(L) and i.next(). But an iterator is more than for loop, because we could explicitly call next if we like.

2. user defined iterators

Now if I have a class, whose data contains a sequence, maybe a list. To enable the iterator of this class I have to implement two functions __iter__ and next:
In __iter__, normally you just need to return the object itself; in next, you have to iterate over the sequence you want, and also indicate when to terminate the iteration and give the exception. Note the count variable is initiated in constructor as a instance variable, which means it could be re-initialized; this is to meet the requirement of every iterator could only iterate once. Also, in order to use your class in a loop, you have to enable its iterator like this.

3. generator

Being a function to generate an iterator means it works similar with iter; one difference is it looks more concise in your class: you dont need a instance variable to keep track of the sequence because now all stuff about the iterator has been put into the generator function. It use the yield block to implement the iteration; I am gonna dig deeper on yield later, but it basically is able to pause the function every time and produce one element at a time.

4. iterable objects

To be fair, all things I describe above could be treated as "subclass" of iterable objects with special constraints, like an iterator could only be used once. An iterable object could be called next multiple times, and when it runs to the end of the sequence, it restarts again.

If it is an iterator, looping it twice will only display one iteration. By making your class iterable, now it basically behaves like other built-in iterable objects, like list.

So what is the take-home message? There are several situations that you have to implement iterations, like you have this class with a sequence of data as instance variable and you want to loop through them.

Wednesday, July 11

Project update: location

In my project, the mobile application is supposed to periodically obtain user's current location and record it into a database; this process should be done even when user quits the app. Previously, my solution is to set a recurring task using AlarmManager, which will send an alarm every 30 seconds after user starts it; another class, extends AlarmReceiver, will start a service every time it receives the alarm task; lastly, in the service class, I create a location manager to obtain location using getLastKnownLocation().

This implementation, technically, issues location tracking task exact every 30 seconds. Two problems with this. First is, although the alarm is generated every 30 seconds, the location tracking might not be finished within 30 seconds every time. There might a situation that the mobile phone has not got any location for the current alarm task when the next one is generated. I am not so sure if this is 100% correct, but I do find sometimes there will be delay in updating location, like no location update for 5 minutes, then several new location updates appear in database with the same coordinates. Anyway, I am suspecting it is because my Activity Alarm -> Service -> LocationManager process take too much time. Another problem is, every task the mobile phone creates a new service, which seems inefficient and unnecessary.

Several days ago I find this post writing about LocationManager and LocationListener, come to my rescue. Basically it explains how the method requestLocationUpdates(long minTime, float minDistance, Criteria criteria, PendingIntent intent) works. This methods aims at saving energy while giving accurate location tracking. The minTime parameter gives the time duration that the location provider will rest (status changes into unavailable) before it activates and obtain location again. The actual time interval will be equal or greater than minTime, due to several reasons: location update only be sent to the app if the difference between new and old location is greater than minDistance, also the provider might take some time to obtain the latest location. This definitely takes longer time than getLastKnownLocation(), since the latter one uses cached location.

Anyway, it seems I could use this request method directly for my periodically update, while it is not exact update, it has several advantages: there will only updates if necessary, if user does not move, my previous version will still update as alarms go on and off; also it is definitely more efficient than multiple services. Now my activity will start the service after user presses the start button, which will then register a LocationListener and request location update. Note this request will not stop until the service stops or I explicitly use removeUpdate method. Lastly, in my class of Location Listener, I put location into database in the onLocationChanged method: it gets invoked every time there is a location update from the location listener.

Some digress, I just find this Notification class which could perfectly display the app status in the notification bar. Previously, I use a textview to hold the status passed from service, but setting it globally visible is better, especially when user quits the app.


I use the sample code comes with SDK. But it is somehow deprecated, thus I change a little. This snippet of code would be put in the onCreate method of my service, so that every time my service starts there will be a notification in the bar. I also put a cancel method in the onDestroy method so that it gets killed when the service stops. Note Notification class is in API level 11 (Honeycomb), which means if you are using the same API level I use (2.3.3, level 10, GingerBread) or lower, you need to import support package in your project.

I will test this new version tomorrow.

Toggle Button and Alert Dialog

Actually I tried them before and now I dont need them in my project. But write down them just for reference.

Both of them are ways to switch among given states; toggle button has 2 states, "on" and "off", while Alert Dialog could support unlimited ones, technically. I tried them for yes/no switch because I want to let user choose whether they want only GPS (fine location tracker) or currently best one to track the location in my project.

Toggle Button is really just switching the text on the button actually. At the same time, you could extract its text at other places, like another button. User could switch to "only GPS" or "all providers" before they hit the tracking button. In the tracking button, I will first extract the text of the toggle button, and then put different info in intent to start the tracking service.

To detect which state user chooses, I create two strings in the string.xml to hold the text for two states, and then compare the current text with them. Nothing fancy here; easy to go.

Alert Dialog is another class to let user choose options. When enabled, the app will pop up a window containing options. In current version of Android, we could use AlertDialog.Builder class to build the alert dialog with the title, content, on click methods we need, and then create it.

The doPositiveClick and doNegativeClick are two methods corresponding to two choices. What they do in my version is just passing different int to the service class in the intent; the service will initiate different location listener based on the int.

Android: Broadcast locally within the app

Previously, when I need to pass some info between my Activity and Service classes, I will use Broadcast class to send a new intent containing the info from the service side, then register a receiver at the activity side. However, Broadcast class is mainly used to send info across apps, e.g. you could send some info from your app to the calendar app to create a new calendar event: it is not for communication occurred inside one app. Exposing your in-app info globally might raise security issues and also not efficient.

OK, then I find this LocalBroadcastManager class, which, according to its name, mange the local broadcast, i.e. passing info within the app (from one app component to another). This is perfect for my use. While the official doc does not provide any details on how to use it, here is an excellent tutorial covering everything we need. I summarize below just for reference:

1. get the library
This class belongs to the support package, which means you have to add the package as a 3rd-party lib  and then import android.support.v4.content.LocalBroadcastManager.

2. create the sender
Pretty straightforward.

3. create the receiver
To receive any intents, globally or locally, you first have to create and register your own broadcast receiver:

All done. Very convenient to use.

Saturday, July 7

Datetime in python

I have constantly used the Datetime module in python during programming, especially in projects with database. Here I summarize some basics just for reference, because sometimes I find official python doc, while well-written, drills too much on details, which is a good thing for doc, but not for peoples who just want to get some basics and make them work.

Here we only care about two objects in this module, datetime and timedelta. Generally, we think datetime as a way to generate both date and time, like "1988 08 01 16:00", and all we (at least I) need to know about timedelta is we could use it for datetime calculation. There is also a date object that only involving date, "1988 08 11".

Before we create any time objects, let's learn some terms. UTC, stands for Coordinated Universal Time, generally the very primary time standard. Different countries in the world have different time, thought, that is because they are in different time zones. Their time is derived from the time zone offset and UTC; like in NJ, it is "UTC-4". Servers and applications using Internet tend to use UTC to store time-related data to achieve consistency.

There are several ways to create a datetime object.

now() and today() are basically the same, both generate a datetime object based on current local time, but now() has some optional arguments to make it more precise than today(), which could be found in official doc. utcnow() returns the UTC time in the same format of datetime. The last one, strptime() is to generate a datetime format object from a string. To do this you have to specific the format of the string. There is also a another method strftime() to generate a string based on a datetime object.

You could also convert the datetime object into a tuple in struct_time format of time module line 10. This is useful when you want to extract some of the time elements from a datetime object. Above are basically all I need for my small projects without any consideration on time zone stuff.

Now there is another interesting object, timedelta. I find this when I tackle a problem involving shifting time in a calendar. For example, today is July 7th, I want to shift it based on different offsets I give to it. This will cause a lot of problem if you have to design the shift rule, considering months have different number of days. However, use a timedelta object we could shift datetime object just like doing calculations:

The first line is to convert datetime object into date object since we only care about shifting days. Other parts are self-explanatory. You can also set other offset in the timedelta, including seconds, minutes, years, etc.

Finally, here is simple time parser in Java, just for reference:

I use the SimpleDateFormat class to make a time format, set time zone, then parse the long input. Including this is just because my projects involve both python and java.

Friday, July 6

Learning postgresql pt2

This actually should be the first part; because now Id like to look into db administration and management, etc.

Postgresql also use client/server model. In order to manipulate any database or its tables, we have to first connect to the database using client applications, for example, psql. This is an interactive query tool in terminal. We use it to connect to our database:

-U option provides the username that we would like to use to connect to the database. After issuing this the terminal will ask password corresponding to the username. By default, when freshly installed, postgresql will create several predefined stuff for you to get started: superuser role postgres, database postgres, etc. Therefore for the first time you could use postgres to connect to the database. After you login, the prompt will change into the name of the database you are currently logged into, now you could use various commands to know about this database.

\d displays all the tables in this database, \du displays all roles across all database clusters: in postgresql, every role acts like an account, with different privileges. Use \q to quit the interactive client. For more usage, please refer to the official manual.

I remember I come across some problems logging into the database as the default superuser, but I cannot remember exactly what the problem is. Anyway, you could always log in as the default superuser as long as you use sudo. To create your own username and password using createuser. Also createdb and dropdb is other commands that are pretty self-explanatory. Note all these commands are issued in the terminal before logging into psql.

Learning postgresql pt1

My graduate course database system teaches me many interesting things, like working in a push environment just like that in a real company, building web app, using AWS, but not database itself. In fact, until now I am still unable to write down a complex SQL query and assure you it is correct. Considering building web app alone requires me constantly manipulate database, its models and write queries,  it is time for me to roll back and study database from the scratch. I know MySQL is just a popular choice; but since Heroku uses postgresql, I might as well start with it.

As far as I know, it is an open source object relational database management system, using SQL. Relational database actually means database with tables. Other database systems like noSQL, does not require tables. ORDMS should work like: columns -> rows -> tables -> databases -> database cluster, which is stored on the database server.

Assuming you know what is relational database, what is "select xx from xx where xx", and other basics in database, let's begin. Most of codes below is from the official postgresql manual. It is great and easy to read, by the way.

Create a new table using standard sql:

Every column has a type, int, varchar, real (for floating number), etc. Brackets indicate the maximum number of this type of value could be put in this column; dashing provides description.

Line 2 indicates the primary key of the weather table. Primary key is just a constraint, which is equal vent to UNIQUE NOT NULL, i.e. the value of this column should be unique and should not be blank. By indicating this constraint, the table gives us this column as the unique identifier to identify any single row in it. One table should have at most one primary key; but a key could be a combination of several columns, as long as they do not violate the constraint. Also, it is optional for a table.

Line 7 indicates a relationship between two tables, called a foreign key. A relationship is another constraint. Now weather table will refer to the cities table for available city name. For example, now if you create a row in weather table with a city name that is not in the cities table, it will throw out an error.

Now we have two empty tables. To insert values into them:

Note now you have to first create a city in cities table and then refer it in weather table. If you have a large amount of data, you could format it in a file and use COPY command to import them into the table at once. Similarly, use COPY * TO file you could export your data in the table to a local file. Note first is the file should be publicly accessible, and second this is only allowed in the server side, i.e. you could not use COPY in a client query.

There are various ways to query data from a table:

They should be pretty self-explanatory. Note the 3rd and 4th queries join two tables to fetch data, which means they are querying multiple tables or multiple rows in one table at the same time. The 4th one is a special join, which means every row in the table mentioned on the left side of the join operator will be displayed at lease once. The output should be something like this:

Note the first row, it does not meet the constraint that "city = name" but still present, because it is in the left table. There are also some aggregate functions you could use up and go like max, min, count. However they are not allowed in the WHERE clause unless it is nested in a subquery like line 15.

To remove data from your table, you could indicate rows you want to delete by WHERE clause in a DELETE FROM query like line 22. If you don't assign any constraints, it will simply delete all rows in the table.

TBD.

Thursday, June 28

Django auth pt1

Nowadays, to use google api correctly in your web applications, most likely you have to use its own authentication oauth 2.0. They say it is simple and easy; to a newbie of web dev it is not. Anyway, I failed to integrate it with my web app, thusly I decide to learn auth from the scratch, and hope one day my web app will be popular enough to demand an authentication system (I mean it!).

Django has its own built-in auth package, which is ideal to use learn the concepts. Most importantly, built-in packages like this always come with built-in views, which could save you a lot of time to get started.

Let's see how to use built-in views: really simple.

In urls.py, we define three extra patterns besides admin ones. One is for the index view, the home page, which will require login authentication to see its content. The other two utilize the built-in views for login and logout. Note for login view you have to define a template to make it go if you don't want to copy the default template from django package; for logout I here use the logout_then_login view, which is pretty self-explained. Since it will redirect to login page automatically, we don't have to add any template for this view.

Now take a look at view.py:

Two things to know: @login_required decorator indicates that this view needs authentication, if currently the user is not logged in, it will take the user to the login view we defined above; if already logged in, it will render the index view as required.

I don't include the template it uses because you could find it in django doc. Only one thing is a little bit tricky: the default login view will pass several variables to the template, including one called next. This contains the url that the app will redirect to after successful login, which should be the url triggered this login (in our case it is "/" for index view). To make the redirect happens, in the template you have to define a redirect to the next, like this if your login page uses a form: <input type="hidden" name="next" value="{{ next }}"/>.

Lastly, remember to add a link to logout url in your index page in order to complete the whole login/logout process.

All done.

Euler project 12: triangle number

I am writing this only because I find these simple math trick is like magic.
Triangle number is ones composed by adding previous number together, like the additive analog of factorial number: Tn = 1 + 2 + 3 + ... + n. Now it asks what is the first triangle number with more than 500 divisors?

There are several ways to generate a triangle number. One is use the plain equation to sum up; other one is clearly use the sum-up equation Tn = n*(n-1)/2. However, since what we basically need here is to iterate all triangle numbers starts with 1 (or some bigger yet still small number), I add a step every time using Tn = Tn-1 + n. I think latter two should be mostly at the same speed.

Another thing is to find the number of divisors for a number. This is just iterate from 1 to sqrt(n), according to many math properties. Also since divisors appear in pairs, one might add two every time it finds a fit one if one uses this method; but minus one if the divisor it finds happens to be the sqrt(n).

Codes:

Monday, June 25

GRE helper project update 1

UPDATE: I cut this project. It turns out giving her a list generated by python script is much faster. Not everything needs a web app.

I start yet another django project on heroku today. It's a rather simple one, just to help my girlfriend memorize vocabulary and prepare her GRE test.

GRE is difficult for people whose first language is not English. The test involves so many non-daily English. You have to memorize, like hardcoded in your brain, thousands of words in order to just understand what this test is talking about, not mention other requirements. A typical preparation for GRE involves at least 4 months of memorizing words repeatedly. I have been through this before, it's a very stressful and boring period of time, especially when you spend several weeks and look back, realize you don't remember one damn word. Sadly I could not turn it into a happy thing; however, I think I could make it efficient and maybe shorten its duration somehow.

What I want it to do is let you type in how many vocabulary lists (do you want to know how many words Chinese have to memorize for just a single test?), then it will generate a calendar filled with each list as task, and distributed based on a predefined memory curve. Basically a customizable repetitive task generator hooked up with google calendar. I know it is still dull, but an organized and well-executed repetition on memorizing could efficiently reduce the amount of time you need to achieve your goal. For the calendar, I don't want to reinvent such a good calendar system, besides Google calendar API has a good python support.

Start with the model. It is pretty simple and common, but I intend to add maybe a list as a instance variable so that every list could have a list of dates on which they needs to be memorized. For the progress field, which is supposed to be within 0 to 100, I add two validators from django.core.validators to prevent overflow.


I make just one page, in which you will have a input area for you to type in how many lists you have, and a display area to show the calendar. The input with the submit button will issue a http POST request to server side, along with some parameters, including the number of your lists. Note django itself disable post method automatically to prevent CSRF attack. To reenable it:

  1. add 'django.middleware.csrf.CsrfViewMiddleware' to the MIDDLEWARE_CLASSES in your settings.py (this should be done by default in the latest version now)
  2. right after your <form> tag that involving POST action, add {% csrf_token %}
  3. in the view associated with this POST request, add context_instance=RequestContext(request) as a parameter in your http response.
In the view, when received a POST request, I will generate List objects according to POST parameters. Note that for django models, when you create it, django will automatically generate an unique id as primary key so that you don't have to worry about it. When you create objects for your model in admin site, you also don't have to explicitly indicate their ids. Therefore when you want to manipulate ids for your objects, you have to explicitly mention it in your constructor or whatever.

TBD...