Top Vim commands you should know

Vim is a text editor written by Bram Moolenaar and first released publicly in 1991. Based on the vi editor common to Unix-like systems, Vim is designed for use both from a command line interface and as a standalone application in a graphical user interface. Vim is free and open source software and is released under a license that includes some charityware clauses, encouraging users who enjoy the software to consider donating to children in Uganda. The license is compatible with the GNU General Public License.

Although Vim was originally released for the Amiga, Vim has since been developed to be cross-platform, supporting many other platforms. In 2006, it was voted the most popular editor amongst Linux Journal readers.

Syntax highlighting

Today, I would like to introduce Pure. It is a set of small, responsive CSS modules that you can use in every web project.
CSS with a minimal footprint.

Pure is ridiculously tiny. The entire set of modules clocks in at 4.2KB* minified and gzipped, without forgoing responsive styles, design, or ease of use. Crafted with mobile devices in mind, it was important to us to keep our file sizes small, and every line of CSS was carefully considered. If you decide to only use a subset of these modules, you'll save even more bytes.

* We can add correctly :) the numbers above are individual module sizes; when grouped together gzipping compresses them even more.

One of the most frequently used operations when you are learning a programming language would be open a file. This tutorial shows you how to manupinate different kinds of file.

How to read a Text File

Let's kick off by opening a text file "file.txt" with the built in function "open". In the following example with default setting, this file is opened in read-only model.

# the open keyword opens a file in read-only mode by default
f = open("/home/jeffery/file.txt")
# read all the lines in the file and return them in a list
lines = f.readlines()
f.close()

You can also use an extra parameter to be explicit.

f = open("/home/jeffery/file.txt", mode='r')

The “r” means to just read the file. You can also open a file in “rb” (read binary), “w” (write), “a” (append), or “wb” (write binary). Note that if you use either “w” or “wb”, Python will overwrite the file, if it exists already or create it if the file doesn’t exist.

If you want to read the file, you can use the following methods:

read - reads the whole file and returns the whole thing in a string

readline - reads the first line of the file and returns it as a string

readlines – reads the entire file and returns it as a list of strings

You can also read a file with a loop, like this:

f = open("/home/jeffery/file.txt", mode='r')
for line in f:
print line
f.close()

How to write a Text File

In this case, you first have to change the mode to "w" or "a" when you open the file.

SQLite Python tutorial

This is a Python programming tutorial for the SQLite database from Zencode. It covers the basics of SQLite programming with the Python language.

Prerequisites

To work with this tutorial, we must have Python language, SQLite database, pysqlite language binding and the sqlite3 command line tool installed on the system. If we have Python 2.5+ then we only need to install the sqlite3 command line tool. Both the SQLite library and the pysqlite language binding are built into the Python languge.

In the shell, we launch the Python interactive interpreter. We can see the Python version. In our case it is Python 2.7.2. The sqlite.version is the version of the pysqlite (2.6.0), which is the binding of the Python language to the SQLite database. The sqlite3.sqlite_version gives us the version of the SQLite database library. In our case it is 3.7.7.

Now we are going to use the sqlite3 command line tool to create a new database.

We provide a parameter to the sqlite3 tool. A "test.db" is a database name. It is a file on our disk. If it is present, it is opened. If not, it is created.

sqlite> .tables
sqlite> .exit
$ ls
test.db

The .tables command gives a list of tables in the test.db database. There are currently no tables. The .exitcommand terminates the interactive session of the sqlite3 command line tool. The ls Unix command shows the contents of the current working directory. We can see the test.db file. All data will be stored in this single file.

Version

In the first code example, we will get the version of the SQLite database.

In the above Python script we connect to the previously created test.db database. We execute an SQL statement which returns the version of the SQLite database.

import sqlite3 as lite

The sqlite3 module is used to work with the SQLite database.

con = None

We initialize the con variable to None. In case we could not create a connection to the database (for example the disk is full), we would not have a connection variable defined. This would lead to an error in the finally clause.

con = lite.connect('test.db')

Here we connect to the test.db database. The connect() method returns a connection object.

cur = con.cursor()
cur.execute('SELECT SQLITE_VERSION()')

From the connection, we get the cursor object. The cursor is used to traverse the records from the result set. We call the execute() method of the cursor and execute the SQL statement.

data = cur.fetchone()

We fetch the data. Since we retrieve only one record, we call the fetchone() method.

print "SQLite version: %s" % data

We print the data that we have retrieved to the console.

except lite.Error, e:
print "Error %s:" % e.args[0]
sys.exit(1)

In case of an exception, we print an error message and exit the script with an error code 1.

finally:
if con:
con.close()

In the final step, we release the resources.

In the second example, we again get the version of the SQLite database. This time we will use the withkeyword.

The first SQL statement drops the Cars table, if it exists. The second SQL statement creates the Cars table.

cur.executemany("INSERT INTO Cars VALUES(?, ?, ?)", cars)

We insert 8 rows into the table using the convenience executemany() method. The first parameter of this method is a parameterized SQL statement. The second parameter is the data, in the form of tuple of tuples.

We provide another way to create our Cars table. We commit the changes manually and provide our own error handling.

In SQLite, INTEGER PRIMARY KEY column is auto incremented. There is also an AUTOINCREMENT keyword. When used in INTEGER PRIMARY KEY AUTOINCREMENT a slightly different algorithm for Id creation is used.

Parameterized queries

Now we will concern ourselves with parameterized queries. When we use parameterized queries, we use placeholders instead of directly writing the values into the statements. Parameterized queries increase security and performance.

The Python sqlite3 module supports two types of placeholders. Question marks and named placeholders.

Inserting images

In this section, we are going to insert an image to the SQLite database. Note that some people argue against putting images into databases. Here we only show how to do it. We do not dwell into technical issues of whether to save images in databases or not.

sqlite> CREATE TABLE Images(Id INTEGER PRIMARY KEY, Data BLOB);

For this example, we create a new table called Images. For the images, we use the BLOB data type, which stands for Binary Large Objects.

These two lines select and fetch data from the Images table. We obtain the binary data from the first row.

Metadata

Metadata is information about the data in the database. Metadata in a SQLite contains information about the tables and columns, in which we store data. Number of rows affected by an SQL statement is a metadata. Number of rows and columns returned in a result set belong to metadata as well.

Metadata in SQLite can be obtained using the PRAGMA command. SQLite objects may have attributes, which are metadata. Finally, we can also obtain specific metatada from querying the SQLite system sqlite_master table.

In this example, we issue the PRAGMA table_info(tableName) command, to get some metadata info about our Cars table.

cur.execute('PRAGMA table_info(Cars)')

The PRAGMA table_info(tableName) command returns one row for each column in the Cars table. Columns in the result set include the column order number, column name, data type, whether or not the column can be NULL, and the default value for the column.

for d in data:
print d[0], d[1], d[2]

From the provided information, we print the column order number, column name and column data type.

$ ./colnames1.py
0 Id INT
1 Name TEXT
2 Price INT

Output of the example.

Next we will print all rows from the Cars table with their column names.

In the above example, we recreate the Cars table in the memory. We delete some rows from the table and dump the current state of the table into a cars.sql file. This file can serve as a current backup of the table.

These lines create a Cars table, insert values and delete rows, where the Price is less than 30000 units.

data = '\n'.join(con.iterdump())

The con.iterdump() returns an iterator to dump the database in an SQL text format. The built-in join()function takes the iterator and joins all the strings in the iterator separated by a new line. This data is written to the cars.sql file in the writeData() function.

The output shows, that we have successfully recreated the saved Cars table.

Transactions

A transaction is an atomic unit of database operations against the data in one or more databases. The effects of all the SQL statements in a transaction can be either all committed to the database or all rolled back.

In SQLite, any command other than the SELECT will start an implicit transaction. Also, within a transaction a command like CREATE TABLE ..., VACUUM, PRAGMA, will commit previous changes before executing.

Manual transactions are started with the BEGIN TRANSACTION statement and finished with the COMMIT OR ROLLBACK statements.

SQLite supports three non-standard transaction levels. DEFERRED, IMMEDIATE and EXCLUSIVE. SQLite Python module also supports an autocommit mode, where all changes to the tables are immediately effective.