Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
s = ' '.join(sys.argv)

 

Join path and name

Code Block
        path_name = os.path.join(path,fname)

...

Code Block
exp = 'xpptut13'
if 'tut' is in exp : <do something> 

...

String alignment

Code Block
msg = '%s' % (k.ljust(16))

 

...

 

 

Useful string parsing options

...

Code Block
 my_string.replace("abcde","cde")

 

String formatting

Code Block
s = 'some text %s  %s' % (msg.ljust(30), str(val).rjust(30)

...

Code Block
sys._getframe().f_code.co_name

Function parameters

Code Block
locals() # returns (dict) of method input parameters

Converting integer to bin(), oct(), hex() string

...

Code Block
from time import localtime, gmtime, strftime, clock, time

time_sec = time() # epoch time

def get_current_local_time_stamp(fmt='%Y-%m-%d %H:%M:%S %Z'):
    return strftime(fmt, localtime())

def get_current_gm_time_stamp(fmt='%Y-%m-%d %H:%M:%S %Z'):
    return strftime(fmt, gmtime())

def get_local_time_str(time_sec, fmt='%Y-%m-%d %H:%M:%S %Z'):
    return strftime(fmt, localtime(time_sec))

def get_gm_time_str(time_sec, fmt='%Y-%m-%d %H:%M:%S %Z'):
    return strftime(fmt, gmtime(time_sec))

 

Set PYTHONPATH

In command-line:

...

Code Block
import os
os.environ['PYTHONPATH'] = '/reg/neh/home1/dubrovin/LCLS/git-work/pyapps:%s' % os.environ.get('PYTHONPATH', '')

 

...

Replace symbols in string

Code Block
text.replace("|",":").replace("-",".")
range.replace('9999','end')
msg.replace('\n',' ')

...

List of comprehension

list_of_x2 = [x*x for x in list_of_x]

...

Code Block
def f(x,y) :
    return x if y>0 else -x

list = map(f, arrX, arrY)

 

Constructor, destructor etc.

Code Block
class PeakListFile :
    def __init__(self, fname) :
	    print 'constructor'
        self.f=open(fname,'r')

    def __del__(self) :
	    print 'destructor'
        try :
            self.f.close()

    def __call__(self) :
	    print 'this is a default method of this object called as obj()'

...

Polymorphism

Derived class initialization

Code Block
class Base :
    def __init__(self) :
       ...
       
class Derived(Base) :
    def __init__(self) :
        Base.__init__(self)
        # OR
        super(Derived, self).__init__()   

...

Create/save temporary file

Code Block
import tempfile
tmp_file = tempfile.NamedTemporaryFile(mode='r+b',suffix='.tiff')
tfile = tmp_file.name

 

 

...


tfile = tmp_file.name

Good example of __main__

Code Block
import sys

def test_all() :
    print _sep_, '\n%s' % sys._getframe().f_code.co_name
    test_ricker()
    test_morlet()

#------------------------------
if __name__ == "__main__" :
    from time import time
    tname = sys.argv[1] if len(sys.argv) > 1 else '0'
    print 50*'_', '\nTest %s:' % tname
    t0_sec = time()
    if   tname == '0': test_all() 
    elif tname == '1': test_ricker()
    elif tname == '2': test_morlet()
    else : print 'Not-recognized test name: %s' % tname
    msg = 'End of test %s, consumed time (sec) = %.6f' % (tname, time()-t0_sec)
    sys.exit(msg)

Virtualenv

Code Block
virtualenv dir-name
source <directoryName>/bin/activate.csh # for tcsh
# or
source <directoryName>/bin/activate     # for bash
pip install <packageName>

... work

deactivate

Python - useful references

...

http://docs.python.org/library/functions.html#setattr

PyQt4

 

 

...

Know How

  • QGraphicsScene item priority is set by setZValue(v)
  • All re-implemented Event methods like {{mouseMoveEvent(self, e)}} etc. in items will get control only if QGraphicsView their default version will be called.

PyQt4 class references

All classes
Selected:

...

Code Block
fig.clear()

Graphic

Code Block
import pyimgalgos.Graphics as gr
axes.clear()
axes.plot(xarr1, yarr1, '-r', xarr2, yarr2,  '-g')
gr.show(mode='do_not_hold') 

Histogram

Code Block
axes.clear()
axes.hist(arr, bins=100, range=(10,50), log=False) # log for vertical scale only

Image (with colorbar)

Code Block
img = axes.imshow(arr2d, interpolation='nearest', origin='bottom', aspect='auto')
img.set_clim(Amin,Amax)

cbar = self.fig.colorbar(img, orientation='vertical', \
                         fraction=0.1, pad=0.01, shrink=1.0, aspect=20)

        # fraction - of the 2d plot occupied by the color bar
        # pad      - is a space between 2d image and color bar
        # shrink   - factor for the length of the color bar
        # aspect   - ratio length/width of the color bar

...