CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_4_4_5_patch3/src/RecoLuminosity/LumiDB/python/CommonUtil.py

Go to the documentation of this file.
00001 '''This module collects some frequently used helper functions
00002 '''
00003 import time,ast,re,json,coral,array
00004 def pairwise(lst):
00005     """
00006     yield item i and item i+1 in lst. e.g.
00007     (lst[0], lst[1]), (lst[1], lst[2]), ..., (lst[-1], None)
00008     
00009     from http://code.activestate.com/recipes/409825-look-ahead-one-item-during-iteration
00010     """
00011     if not len(lst): return
00012     #yield None, lst[0]
00013     for i in range(len(lst)-1):
00014         yield lst[i], lst[i+1]
00015     yield lst[-1], None
00016 def findInList(mylist,element):
00017     """
00018     check if an element is in the list
00019     """
00020     pos=-1
00021     try:
00022         pos=mylist.index(element)
00023     except ValueError:
00024         pos=-1
00025     return pos!=-1
00026 def is_intstr(s):
00027     """test if a string can be converted to a int
00028     """
00029     try:
00030         int(s)
00031         return True
00032     except ValueError:
00033         return False
00034 def is_floatstr(s):
00035     """
00036     test if a string can be converted to a float
00037     """
00038     try:
00039         float(s)
00040         return True
00041     except ValueError:
00042         return False
00043 def count_dups(l):
00044     """
00045     report the number of duplicates in a python list
00046     """
00047     from collections import defaultdict
00048     tally=defaultdict(int)
00049     for x in l:
00050         tally[x]+=1
00051     return tally.items()
00052 def transposed(lists, defaultval=None):
00053     """
00054     transposing list of lists
00055     from http://code.activestate.com/recipes/410687-transposing-a-list-of-lists-with-different-lengths/
00056     """
00057     if not lists: return []
00058     return map(lambda *row: [elem or defaultval for elem in row], *lists)
00059 def pack(high,low):
00060     """pack high,low 32bit unsigned int to one unsigned 64bit long long
00061        Note:the print value of result number may appear signed, if the sign bit is used.
00062     """
00063     h=high<<32
00064     return (h|low)
00065 def packToString(high,low):
00066     """pack high,low 32bit unsigned int to one unsigned 64bit long long in string format
00067        Note:the print value of result number may appear signed, if the sign bit is used.
00068     """
00069     fmt="%u"
00070     return fmt%pack(high,low)
00071 def unpack(i):
00072     """unpack 64bit unsigned long long into 2 32bit unsigned int, return tuple (high,low)
00073     """
00074     high=i>>32
00075     low=i&0xFFFFFFFF
00076     return(high,low)
00077 def unpackFromString(i):
00078     """unpack 64bit unsigned long long in string format into 2 32bit unsigned int, return tuple(high,low)
00079     """
00080     return unpack(int(i))
00081 def timeStamptoDate(i):
00082     """convert 64bit timestamp to local date in string format
00083     """
00084     return time.ctime(unpack(i)[0])
00085 def timeStamptoUTC(i):
00086     """convert 64bit timestamp to Universal Time in string format
00087     """
00088     t=unpack(i)[0]
00089     return time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(t))
00090 def unpackLumiid(i):
00091     """unpack 64bit lumiid to dictionary {'run','lumisection'}
00092     """
00093     j=unpack(i)
00094     return {'run':j[0],'lumisection':j[1]}
00095 def inclusiveRange(start,stop,step):
00096     """return range including the stop value
00097     """
00098     v=start
00099     while v<stop:
00100         yield v
00101         v+=step
00102     if v>=stop:
00103         yield stop
00104         
00105 def tolegalJSON(inputstring):
00106    '''
00107    convert json like string to legal json string
00108    add double quote around json keys if they are not there, change single quote to double quote around keys
00109    '''
00110    strresult=inputstring.strip()
00111    strresult=re.sub("\s+","",strresult)
00112    try:
00113        mydict=ast.literal_eval(strresult)
00114    except SyntaxError:
00115        print 'error in converting string to dict'
00116        raise
00117    result={}
00118    for k,v in mydict.items():
00119        if not isinstance(k,str):
00120            result[str(k)]=v
00121        else:
00122            result[k]=v
00123    return re.sub("'",'"',str(result))
00124 
00125 def packArraytoBlob(iarray):
00126     '''
00127     Inputs:
00128     inputarray: a python array
00129     '''
00130     result=coral.Blob()
00131     result.write(iarray.tostring())
00132     return result
00133 
00134 def unpackBlobtoArray(iblob,itemtypecode):
00135     '''
00136     Inputs:
00137     iblob: coral.Blob
00138     itemtypecode: python array type code 
00139     '''
00140     if itemtypecode not in ['c','b','B','u','h','H','i','I','l','L','f','d']:
00141         raise RuntimeError('unsupported typecode '+itemtypecode)
00142     result=array.array(itemtypecode)
00143     result.fromstring(iblob.readline())
00144     return result
00145 
00146 def packListstrtoCLOB(iListstr,separator=','):
00147     '''
00148     pack list of string of comma separated large string CLOB
00149     '''
00150     return separator.join(iListstr)
00151 
00152 def unpackCLOBtoListstr(iStr,separator=','):
00153     '''
00154     unpack a large string to list of string
00155     '''
00156     return [i.strip() for i in iStr.strip().split(separator)]
00157     
00158 if __name__=='__main__':
00159     a=[1,2,3,4,5]
00160     for i,j in pairwise(a):
00161         if j :
00162             print i,j
00163     lst = ['I1','I2','I1','I3','I4','I4','I7','I7','I7','I7','I7']
00164     print count_dups(lst)
00165     seqbag=[[1,2,3],[1,3,3],[1,4,6],[4,5,6,7],[8,9]]
00166     print 'before ',seqbag
00167     print 'after ',transposed(seqbag,None)
00168     print [i for i in inclusiveRange(1,3,1)]
00169     
00170     result=tolegalJSON('{1:[],2:[[1,3],[4,5]]}')
00171     print result
00172     pp=json.loads(result)
00173     print pp["2"]
00174     result=tolegalJSON("{'1':[],'2':[[1,3],[4,5]]}")
00175     print result
00176     pp=json.loads(result)
00177     print pp["2"]
00178     result=tolegalJSON('{"1":[],"2":[[1,3],[4,5]]}')
00179     print result
00180     pp=json.loads(result)
00181     print pp["2"]
00182     
00183     a=array.array('f')
00184     a.append(1.3)
00185     a.append(1.4)
00186     a.append(2.3)
00187     a.append(6.3)
00188     myblob=packArraytoBlob(a)
00189     print myblob.size()
00190     print unpackBlobtoArray(myblob,'f')
00191     b=array.array('f')
00192     myblob=packArraytoBlob(b)
00193     print myblob.size()
00194     a=['aa_f', 'bb', 'dfc']
00195     print packListstrtoCLOB(a)