pretty

Tuesday, March 18, 2014

Sort tuples in a list

Sort tuples in list based on date


import datetime
import pprint

data = [(3, "2012-01-02 12:11:00"),(2, "2012-01-03 12:11:00")\
        , (1, "2014-01-02 12:11:00"), (4, "2011-01-02 12:11:00")]

def get_date(record):
    return datetime.datetime.strptime(record[1], "%Y-%m-%d %H:%M:%S")


def sortitemsondate(items):
    items = sorted(items, key=get_date, reverse=True)
    return items

pprint.pprint(sortitemsondate(data))

# [(1, '2014-01-02 12:11:00'),
#  (2, '2012-01-03 12:11:00'),
#  (3, '2012-01-02 12:11:00'),
#  (4, '2011-01-02 12:11:00')]




Monday, January 27, 2014

Read a file in bash

Read a file line by line in bash


while read line           
do           
    echo $line

done < test.txt   

oneliner version

while read line ; do echo $line ; done < test.txt

Monday, January 13, 2014

Check if process is running in bash script

Check if process is running in bash script

#!/bin/bash

if [ -z "$(pgrep mysql)" ]
 then
     echo "Mysql is not running"     
 else
     echo "Mysql is running"
fi

Friday, January 10, 2014

Backup and restore mysql database

Make backup

mysqldump -u user -p password  | gzip > outputfile.sql.gz

Restore

gunzip < outputfile.sql.gz | mysql -u user -p password databasename
adapted from http://www.ducea.com/2006/10/28/compressing-mysqldump-output/