CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
CommonUtil.py
Go to the documentation of this file.
1 '''This module collects some frequently used helper functions
2 '''
3 import time,ast,re,json,coral,array
4 def pairwise(lst):
5  """
6  yield item i and item i+1 in lst. e.g.
7  (lst[0], lst[1]), (lst[1], lst[2]), ..., (lst[-1], None)
8 
9  from http://code.activestate.com/recipes/409825-look-ahead-one-item-during-iteration
10  """
11  if not len(lst): return
12  #yield None, lst[0]
13  for i in range(len(lst)-1):
14  yield lst[i], lst[i+1]
15  yield lst[-1], None
16 def findInList(mylist,element):
17  """
18  check if an element is in the list
19  """
20  pos=-1
21  try:
22  pos=mylist.index(element)
23  except ValueError:
24  pos=-1
25  return pos!=-1
26 def is_intstr(s):
27  """test if a string can be converted to a int
28  """
29  try:
30  int(s)
31  return True
32  except ValueError:
33  return False
34 def is_floatstr(s):
35  """
36  test if a string can be converted to a float
37  """
38  try:
39  float(s)
40  return True
41  except ValueError:
42  return False
43 def count_dups(l):
44  """
45  report the number of duplicates in a python list
46  """
47  from collections import defaultdict
48  tally=defaultdict(int)
49  for x in l:
50  tally[x]+=1
51  return tally.items()
52 def transposed(lists, defaultval=None):
53  """
54  transposing list of lists
55  from http://code.activestate.com/recipes/410687-transposing-a-list-of-lists-with-different-lengths/
56  """
57  if not lists: return []
58  return map(lambda *row: [elem or defaultval for elem in row], *lists)
59 def pack(high,low):
60  """pack high,low 32bit unsigned int to one unsigned 64bit long long
61  Note:the print value of result number may appear signed, if the sign bit is used.
62  """
63  h=high<<32
64  return (h|low)
65 def packToString(high,low):
66  """pack high,low 32bit unsigned int to one unsigned 64bit long long in string format
67  Note:the print value of result number may appear signed, if the sign bit is used.
68  """
69  fmt="%u"
70  return fmt%pack(high,low)
71 def unpack(i):
72  """unpack 64bit unsigned long long into 2 32bit unsigned int, return tuple (high,low)
73  """
74  high=i>>32
75  low=i&0xFFFFFFFF
76  return(high,low)
78  """unpack 64bit unsigned long long in string format into 2 32bit unsigned int, return tuple(high,low)
79  """
80  return unpack(int(i))
82  """convert 64bit timestamp to local date in string format
83  """
84  return time.ctime(unpack(i)[0])
86  """convert 64bit timestamp to Universal Time in string format
87  """
88  t=unpack(i)[0]
89  return time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(t))
90 def unpackLumiid(i):
91  """unpack 64bit lumiid to dictionary {'run','lumisection'}
92  """
93  j=unpack(i)
94  return {'run':j[0],'lumisection':j[1]}
95 def inclusiveRange(start,stop,step):
96  """return range including the stop value
97  """
98  v=start
99  while v<stop:
100  yield v
101  v+=step
102  if v>=stop:
103  yield stop
104 
105 def tolegalJSON(inputstring):
106  '''
107  convert json like string to legal json string
108  add double quote around json keys if they are not there, change single quote to double quote around keys
109  '''
110  strresult=inputstring.strip()
111  strresult=re.sub("\s+","",strresult)
112  try:
113  mydict=ast.literal_eval(strresult)
114  except SyntaxError:
115  print 'error in converting string to dict'
116  raise
117  result={}
118  for k,v in mydict.items():
119  if not isinstance(k,str):
120  result[str(k)]=v
121  else:
122  result[k]=v
123  return re.sub("'",'"',str(result))
124 
125 def packArraytoBlob(iarray):
126  '''
127  Inputs:
128  inputarray: a python array
129  '''
130  result=coral.Blob()
131  result.write(iarray.tostring())
132  return result
133 
134 def unpackBlobtoArray(iblob,itemtypecode):
135  '''
136  Inputs:
137  iblob: coral.Blob
138  itemtypecode: python array type code
139  '''
140  if itemtypecode not in ['c','b','B','u','h','H','i','I','l','L','f','d']:
141  raise RuntimeError('unsupported typecode '+itemtypecode)
142  result=array.array(itemtypecode)
143  result.fromstring(iblob.readline())
144  return result
145 
146 def packListstrtoCLOB(iListstr,separator=','):
147  '''
148  pack list of string of comma separated large string CLOB
149  '''
150  return separator.join(iListstr)
151 
152 def unpackCLOBtoListstr(iStr,separator=','):
153  '''
154  unpack a large string to list of string
155  '''
156  return [i.strip() for i in iStr.strip().split(separator)]
157 
158 if __name__=='__main__':
159  a=[1,2,3,4,5]
160  for i,j in pairwise(a):
161  if j :
162  print i,j
163  lst = ['I1','I2','I1','I3','I4','I4','I7','I7','I7','I7','I7']
164  print count_dups(lst)
165  seqbag=[[1,2,3],[1,3,3],[1,4,6],[4,5,6,7],[8,9]]
166  print 'before ',seqbag
167  print 'after ',transposed(seqbag,None)
168  print [i for i in inclusiveRange(1,3,1)]
169 
170  result=tolegalJSON('{1:[],2:[[1,3],[4,5]]}')
171  print result
172  pp=json.loads(result)
173  print pp["2"]
174  result=tolegalJSON("{'1':[],'2':[[1,3],[4,5]]}")
175  print result
176  pp=json.loads(result)
177  print pp["2"]
178  result=tolegalJSON('{"1":[],"2":[[1,3],[4,5]]}')
179  print result
180  pp=json.loads(result)
181  print pp["2"]
182 
183  a=array.array('f')
184  a.append(1.3)
185  a.append(1.4)
186  a.append(2.3)
187  a.append(6.3)
188  myblob=packArraytoBlob(a)
189  print myblob.size()
190  print unpackBlobtoArray(myblob,'f')
191  b=array.array('f')
192  myblob=packArraytoBlob(b)
193  print myblob.size()
194  a=['aa_f', 'bb', 'dfc']
195  print packListstrtoCLOB(a)
def unpackCLOBtoListstr
Definition: CommonUtil.py:152
def unpackFromString
Definition: CommonUtil.py:77
def timeStamptoDate
Definition: CommonUtil.py:81
def packListstrtoCLOB
Definition: CommonUtil.py:146
def timeStamptoUTC
Definition: CommonUtil.py:85
def tolegalJSON
Definition: CommonUtil.py:105
return((rh^lh)&mask)
def transposed
Definition: CommonUtil.py:52
def packToString
Definition: CommonUtil.py:65
def unpack
Definition: CommonUtil.py:71
def unpackBlobtoArray
Definition: CommonUtil.py:134
def findInList
Definition: CommonUtil.py:16
def packArraytoBlob
Definition: CommonUtil.py:125
def inclusiveRange
Definition: CommonUtil.py:95
def is_floatstr
Definition: CommonUtil.py:34
def count_dups
Definition: CommonUtil.py:43
def is_intstr
Definition: CommonUtil.py:26
def pairwise
Definition: CommonUtil.py:4
def unpackLumiid
Definition: CommonUtil.py:90
double split
Definition: MVATrainer.cc:139