Mostly Linux & Python syntax notes and hyperlinks.

Tuesday, November 29, 2011

python: note the non-intuitive behavior of range(start,end+1)


range(a,b) starts at a and ends at b-1

>>> for n in range(1,3):
...    print str(n)
...
1
2
>>>

You could introduce bugs in your code by not being careful of this.

Monday, November 28, 2011

python: 2-D dictionary, somewhat dynamically filled

counts=dict(A=dict(),B=dict())
for n in range(0,6): 

    Fn='F'+str(n)
    counts['A'][Fn]=n
    counts['B'][Fn]=-n



Then counts = {'A': {'F0': 0, 'F1': 1, 'F2': 2, 'F3': 3, 'F4': 4, 'F5': 5}, 'B': {'F0': 0, 'F1': -1, 'F2': -2, 'F3': -3, 'F4': -4, 'F5': -5}} 

That is:
for t in ('A','B'):
     for n in range(0,6):
         Fn='F'+str(n)
         print("counts[%s][%s]=%d" % (t,Fn,counts[t][Fn]))
will print


counts[A][F0]=0
counts[A][F1]=1
counts[A][F2]=2
counts[A][F3]=3
counts[A][F4]=4
counts[A][F5]=5
counts[B][F0]=0
counts[B][F1]=-1
counts[B][F2]=-2
counts[B][F3]=-3
counts[B][F4]=-4
counts[B][F5]=-5



Monday, October 24, 2011

python: real path after symbolic link

After calling a library method that renamed a file and linked it, I needed the name it renamed it to.

  filename=os.path.basename(os.path.realpath(symbolicLinkName))

 More at http://www.python.org/doc//current/library/os.path.html

Friday, August 19, 2011

python: Define an empty function using pass

I want to define a function for a parent class that can be used by child.
Using pass seems to be the proper way to do it:
def emptyFunction(self):
     pass

Thursday, June 23, 2011

python: get the last directory name in a path

If I want to pull just the parent directory name out of a long path to a file:
>>> import os
>>> pth="/abeja/blanca/zumbas/ebria/de/miel/en/mi/alma/y.te.tuerces"
>>> os.path.split(os.path.dirname(pth))[1]
'alma'
>>>

Friday, May 27, 2011

Linux: grep for $

This was harder than grep for tab.
I found instructions to escape the special character, but none of these
grep $ *
grep \$ *
grep "$" *
grep "\$" *
grep - $ *
grep "$" *
grep '$' *
egrep '$' *


worked until I read "Note that a $ sign loses its meaning if characters follow it" and remembered I was looking for a $ followed by a capital letter. So this works:

grep '$[A-Z]' *

but I still don't know how to find a $ by itself.

Wednesday, May 25, 2011

Python: os.path.lexists() vs os.path.exists() before os.symlink()

We were having intermittent failures with shutil.copy(src,dest) and decided to replace it with just a symbolic link, using os.symlink(src,dest). This triggered an error when we tried to create a symbolic link with the name of an existing file. So the code checks first. It uses os.path.lexists(), since that will return True for broken as well as valid links. os.path.exists() returns True for valid links, False for broken ones.
The os.remove() works whether or not the link is broken or valid or an actual file.
if os.path.lexists(dest):
    os.remove(dest)
os.symlink(src,dest)
(For more detail, see also June2013)

Linux: paste and diff -b

tidbits recently of use to me:
  • paste to put two files together by merging their columns, without the complications of join
  • diff -b to ignore blank lines etc, when comparing how my new code is different from the old code.

Friday, April 15, 2011

Rohit Bhardwaj's talk on Android programming last night at NE-JUG

Listing other dl.dropbox URL's for a zip of samples source code.
His twitter:
http://twitter.com/#!/rbhardwaj1

My notes:
  • Each App has its own 'Linux User' so it can't poach security info.
    • All the data locked in for that user.
    • There are ways to share data between apps.
  • APK 
    • instead of EXE
    • can be stored in SD-card
  • testing: need to test with at least 50 devices
    • use ADBridge
  • autogenerated R.java has all References. 
  • OnCreate(Bundle savedInstance)
  • Honeycomb/Android 3 like iPad, multitasking
  • Android marketplace $25 to sell your apps.

Tuesday, March 1, 2011

Python: appending column to end of tab-separated csv

Given this input file:
$ cat list.csv
a       b       c
d       e       f
g       h       i
Using this code:
import os,csv

def test_fcn() :
    try:
        tabReader = csv.reader( open("list.csv", "rb"), delimiter='\t', quoting=csv.QUOTE_NONE )
        fd = open("out.csv", "wb+")
        tabWriter = csv.writer(fd, delimiter='\t', quoting=csv.QUOTE_NONE)
        if tabReader != None :
            for record in tabReader:
                record.append("new_thing")
                tabWriter.writerow(record)
        fd.close()
        return

    except Exception,e :
        print "Exception : " + str(e)
        
def main():
    test_fcn()

if __name__ == '__main__':
    import sys
    main(*sys.argv[1:])
Here's the output:
$ cat out.csv
a       b       c       new_thing
d       e       f       new_thing
g       h       i       new_thing

Friday, January 28, 2011

Linux: Using whereis to find ifconfig

If something isn't in default path you still may be able to find it with whereis:

$ ifconfig
bash: ifconfig: command not found
$ whereis ifconfig
ifconfig: /sbin/ifconfig /usr/share/man/man8/ifconfig.8.gz
$ /sbin/ifconfig
eth2 Link encap:Ethernet HWaddr ...

Tuesday, January 4, 2011

Linux: to grep for dash, use grep --

For example, to search for python code containing the string "-D":
grep -- -D *.py
From http://stackoverflow.com/questions/2427913/grepping-for-string-containing-dash

Blog Archive