Tuesday, August 5, 2014

Swap usage by pid

for i in `find /proc -maxdepth 1 -type d|xargs -i basename {}`;do echo -n "PID: $i SWAP: ";cat /proc/$i/smaps|fgrep Swap|awk '{s=s+$2}END{print s}';done|sort -k4n

Wednesday, July 16, 2014

Bitwise operators in Python

>>> x = 10
>>> y = 6
>>> print "x={x} ({x:08b}), y={y} ({y:08b})".format(x=x, y=y)
x=10 (00001010), y=6 (00000110)

>>> print "x XOR y = {r:d} ({r:08b})".format(r=x ^ y)
x XOR y = 12 (00001100)

>>> print "x OR y = {r:d} ({r:08b})".format(r=x | y)
x OR y = 14 (00001110)

>>> print "x AND y = {r:d} ({r:08b})".format(r=x & y)
x AND y = 2 (00000010)

Wednesday, May 7, 2014

Python dict.fromkeys() magic

I just got some magic from python and what to share with the world.
Imagine we have some python code:
keys = ("T1", "T2", "T3")
td = dict.fromkeys(keys, [])
print td
{'T2': [], 'T3': [], 'T1': []}

Ok. Now lets try to populate new dictionary with some data:

for i in range(0,5):
 for v in td.itervalues():
  v.append(1)
print td

I think you are expecting to get something like:
{'T2': [1, 1, 1, 1, 1], 'T3': [1, 1, 1, 1, 1], 'T1': [1, 1, 1, 1, 1]}

But Nope! You will see this one:
{'T2': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 'T3': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 'T1': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}

The magic comes from fromkeys() function. It seems the function links all dictionary keys to one list object. Lets check it:

for k in td.itervalues():
 print id(k)
140567008377312
140567008377312
140567008377312

Yes, it's true! So be carefully with fromkeys() or use something like:
td = dict((k, []) for k in keys)

P.S.
Thanks to Alexey Gusev for this case.
And yes, when we have understood the problem I easily found this discussion on stackoverflow.