The most important aspect of mysql that needs to be monitored is error log file. MySQL will write almost all important errors to this file. Here is a cron that will monitor it every hour and let the DBA know when the file is updated.
02 * * * * tail -1000 `mysqladmin variables | grep log_error | awk '{print $4}'` | grep -e "`date +'\%y\%m\%d \%k' --date='1 hour ago'`" | mail -s "crashed lo from `hostname`" dba@company.com > /home/alert_mail_success.txt 2> /home/alert_mail_err.txt
1) Replace "mail -s" with "mail -E -s" so that blank (empty) mails will not be sent.
2) The "-E" option may not work with older mail version. But the following cron should work...
02 * * * * tail -1000 `mysqladmin variables | grep log_error | awk '{print $4}'` | grep -e "`date +'\%y\%m\%d \%k' --date='1 hour ago'`" > myerror.txt; if [[ -s myerror.txt ]]; then cat myerror.txt | mail -s "last hour error log from `hostname`" dba@company.com ; fi > /home/alert_mail_success.txt 2> /home/alert_mail_err.txt
It will not send a mail if the error log extract file (myerror.txt) is empty.
Regular Expressions demystified
There are times when using regular expression is the only way to find the text from a given string.
Here is a really useful utility that will explain and at the same time help us to write complex regular expressions.
http://gskinner.com/RegExr/?31u07
_____
SQL formatter
The following utility will help to format a complex SQL query.
http://www.dpriver.com/pp/sqlformat.htm
Labels: mysql tips, usability
import sqlite3 as sqlite
conn = sqlite.connect(":memory:")
conn.execute("CREATE TABLE A (name integer PRIMARY KEY AUTOINCREMENT, address varchar(100))")
conn.execute("insert into A values (22, 'india')")
conn.execute("insert into A values (23, 'usa')")
a = conn.execute("SELECT * FROM A").fetchall()
for i in a:
print i[1]
# will print this...
#india
#usa
# The cursor retains the id of the last row inserted in the lastrowid attribute
import sqlite3
connection = sqlite3.connect(':memory:')
cursor = connection.cursor()
cursor.execute('CREATE TABLE foo (id integer primary key autoincrement ,
username varchar(50),
password varchar(50))')
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
('test', 'test'))
print(cursor.lastrowid)
# fetchone() returns the first row from the select statement as a tuple, so fetchone()[0] will return the first (and only) column in the first (and only) row, i.e. the max(id).
cursor = sqlite3.execute('SELECT max(id) FROM table_name')
max_id = cursor.fetchone()[0]
_____
# it is also possible to update a value based on some other column
cursor.execute('SELECT column2 FROM Table ORDER BY column2')
column2 = [row[0] for row in cursor]
for j, c in zip(lst, column2):
cursor.execute('UPDATE Table SET column = ? WHERE column2 = ?', [j, c])
Labels: python
It is possible to directly import a module and initialize the class.
>>> exec(urllib2.urlopen('http://www.ics.uci.edu/~eppstein/PADS/UnionFind.py').read())
>>> uf = UnionFind()
We can use wget or curl
$ wget http://www.ics.uci.edu/~eppstein/PADS/UnionFind.py
>>> from UnionFind import UnoinFind
>>> uf = UnionFind()
Labels: python
If you are looking for concise, pythonic and elegant way of writing a loop then list comprehension is the right choice.
## normal loop to print numbers till 10 except 2 and 3
# expected output
# [1, 4, 5, 6, 7, 8, 9, 10]
t = 0
l = []
while t < 10:
t += 1
if t == 2 or t == 3: continue
l.append(t)
## list comprehension # 6 lines in 1
a = [x for x in range(1,10) if x != 2 and x != 3]
## a is now a list and can be used in for x in a:
# use unpacking in list comprehension
dict((s, v) for (o, s), v in mydict.iteritems() if o is co1)
Labels: python
# following has no loop for it is printed only once
def thisLines(n):
mv = 0
if n > mv:
print "testme22"
n += 1
thisLines(10)
# Using while loop
def printLines(nr):
myva = 0
while nr > myva:
print "testme"
myva += 1
printLines(10)
# Using recursive function:
def nLines(n):
if n > 0:
print "test"
nLines(n-1)
nLines(10)
Labels: python
'''
save the URL list in a file and then copy the source code to a text file
'''
import urllib
class mydict():
def myurllist():
fp = open('URLS-HERE.txt', "w")
fp.write('http://google.com/index.html')
fp.close()
def read_myurllist():
for line in open('URLS-HERE.txt','r'):
if line.startswith('http'):
fichier = open("other.txt", "w")
allhtml = urllib.urlopen(line)
fichier.write(allhtml.read())
fichier.close()
m = mydict()
m.myurllist
m.read_myurllist
fp1 = open('other.txt', 'r')
for myline in fp1.readlines():
print myline
fp1.close()
_____
parse_qs is used to Parse a query string. Data are returned as a dictionary.
import urllib2
import urlparse
url = 'http://www.tip.it/runescape/gec/price_graph.php?avg=1&start=1327715574&mainitem=10350&item=10350'
response = urllib2.urlopen(url)
content = response.read()
params = urlparse.parse_qs(content)
print(params['values'])
NumPy for windows can be downloaded from...
http://sourceforge.net/projects/numpy/files/NumPy/
## np allows to construct array differently:
import numpy as np
z = np.array(zip([1,2,3,4,5], ['a','b','c','d','e']), dtype=[('int', int), ('str', '|S1')])
np.savetxt('test.txt', z, fmt='%i %s')
# Find the ten most common words in abc.txt
def cat(filename):
f = open(filename, 'rU')
text = f.read()
wordlist = text.split()
for myword in wordlist:
oldval = d.get(myword, 0)
d[myword] = oldval + 1
t = sorted(d.iteritems(), key=lambda x:-x[1])[:3]
for x in t: print "{0}: {1}".format(*x)
# Better
def cat(filename):
f = open(filename, 'rU')
text = f.read()
wordlist = text.split()
return collections.Counter(wordlist).most_common(3)
# Best
import re
wordlist = re.findall('\w+', open('abc.txt').read().lower())
collections.Counter(wordlist).most_common(3)
## Counter ##
>>> from collections import Counter
>>> c=Counter({2:2, 3:1, 5:1,9:4})
>>> type(c)
>>> list(c.elements())
[9, 9, 9, 9, 2, 2, 3, 5]
_____
If I need to total the values for each key, I can use the counter method available in collections.
d = {'apple': {'a': 1, 'b': 4, 'c': 2}, 'orange': {'a': 4, 'c': 5}, 'pear': {'a': 1, 'b': 2}}
# expected results
# Counter({'c': 7, 'a': 6, 'b': 6})
from collections import Counter
one = sum(map(Counter, d.values()), Counter())
two = sum((Counter(v) for v in d.itervalues()), Counter())
# using loop to count
three = Counter()
for v in d.values():
three.update(v)
Or it is also possible to use default dictionary method as shown below.
from collections import defaultdict
de = defaultdict(int)
for dct in d.values():
for k,v in dct.items():
de[k] += v
print(de)
Labels: python
## list ##
## A list can contain anything like integer, string, tuple, another list etc.
>>> a = [1,2,'abc']
>>> a
[1, 2, 'abc']
## Variables are only containers or pointers to the real stuff.
## So when a is appended, b will also change. But when a is removed b is not removed because it will still point to the old data.
>>> b = a
>>> a.append(4)
>>> b
[1, 2, 'abc', 4]
>>> del a
>>> a
Traceback (most recent call last):
File "
", line 1, in a
NameError: name 'a' is not defined
>>> b
[1, 2, 'abc', 4]
## sort ##
>>> sort
Traceback (most recent call last):
File "", line 1, in sort
NameError: name 'sort' is not defined
>>> sorted
built-in function sorted
>>>help sorted
SyntaxError: invalid syntax
>>> help (sorted)
Help on built-in function sorted in module __builtin__:
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
## sorted is a function that returns the sorted list while a.sort() is a method that will sort data in-place.
>>> a = ['amar', 'akbar', 'anthony']
>>> sorted(a)
['akbar', 'amar', 'anthony']
>>> sorted(a, reverse=True)
['anthony', 'amar', 'akbar']
>>> def Last(s): return s[-1]
>>> sorted(a, key=Last, reverse=True)
['anthony', 'amar', 'akbar']
## reverse sort is possible as well as custom sort can be achived using a function like "Last" in this case
## slicing ##
>>> b = ':'.join(a)
>>> b
'amar:akbar:anthony'
>>> b.split(':')
['amar', 'akbar', 'anthony']
## tuples ##
>>> x = (1,2,3)
>>> type(x)
type 'tuple'
>>> a = (1,2,3)
>>> len(a)
3
>>> a[0]
1
## looping tuple values in a list called result
>>> result = []
>>> type (result)
type 'list'
>>> for s in x: result.append(s)
>>> result
[1, 2, 3]
## or simply use the built-in function list to convert a tuple to list
>>> x = (1,2,3)
>>> y = list(x)
>>> type (x)
type 'tuple'
>>> type (y)
type 'str'
## Lists are mutable while tuples and strings are not.
## it means tuple values can not be changed just like list values
>>> x[0] = 9
Traceback (most recent call last):
File "", line 1, in
a[0] = 9
TypeError: 'tuple' object does not support item assignment
## dictionary ##
>>> d = {}
>>> d['a'] = 'alpha'
>>> d['o'] = 'omega'
>>> d['g'] = 'gamma'
>>> d
{'a': 'alpha', 'g': 'gamma', 'o': 'omega'}
>>> d['a']
'alpha'
>>> d.get('a')
'alpha'
>>> d['x']
Traceback (most recent call last):
File "
", line 1, in d['x']
KeyError: 'x'
>>> d.get('x')
>>> d.get('x', 'mydefault')
'mydefault'
>>> 'a' in d
True
>>> 'x' in d
False
>>> d.keys()
['a', 'g', 'o']
>>> d.values()
['alpha', 'gamma', 'omega']
>>> d.items()
[('a', 'alpha'), ('g', 'gamma'), ('o', 'omega')]
>>> for k in d: print 'key:', k, '->', d[k]
key: a -> alpha
key: g -> gamma
key: o -> omega
>>> for tuple in d.items(): print tuple
('a', 'alpha')
('g', 'gamma')
('o', 'omega')
>>> for k in sorted(d.keys()): print 'key:', k, '->', d[k]
key: a -> alpha
key: g -> gamma
key: o -> omega
# first, second and third ranks
rank = range(1,4)
# player names
player = ['amar','akbar','anthony']
# link the ranks with players
result = dict(zip(rank,player))
# find who is third
result[3]
# find what is the rank of amar
[k for k, v in result.iteritems() if v == 'amar'][0]
# the values can also be assigned to a tuple
(amar, akbar, anthony) = range(1,4)
zip can also be used to transpose data
>>> rows = [[1, 1, 2, 3], [4, 5, 6, 7], [1, 2, 5, 7], [6, 9, 8, 5]]
>>> zip(*rows)
[(1, 4, 1, 6), (1, 5, 2, 9), (2, 6, 5, 8), (3, 7, 7, 5)]
Labels: python