CMS 3D CMS Logo

helperFunctions.py
Go to the documentation of this file.
1 import os
2 import ROOT
3 from TkAlExceptions import AllInOneError
4 
5 ####################--- Helpers ---############################
6 def replaceByMap(target, the_map):
7  """This function replaces `.oO[key]Oo.` by `the_map[key]` in target.
8 
9  Arguments:
10  - `target`: String which contains symbolic tags of the form `.oO[key]Oo.`
11  - `the_map`: Dictionary which has to contain the `key`s in `target` as keys
12  """
13 
14  result = target
15  for key in the_map:
16  lifeSaver = 10e3
17  iteration = 0
18  while ".oO[" in result and "]Oo." in result:
19  for key in the_map:
20  try:
21  result = result.replace(".oO["+key+"]Oo.",the_map[key])
22  except TypeError: #try a dict
23  try:
24  for keykey, value in the_map[key].iteritems():
25  result = result.replace(".oO[" + key + "['" + keykey + "']]Oo.", value)
26  result = result.replace(".oO[" + key + '["' + keykey + '"]]Oo.', value)
27  except AttributeError: #try a list
28  try:
29  for index, value in enumerate(the_map[key]):
30  result = result.replace(".oO[" + key + "[" + str(index) + "]]Oo.", value)
31  except TypeError:
32  raise TypeError("Something is wrong in replaceByMap! Need a string, dict, or list, but the_map(%s)=%s!"%(repr(key), repr(the_map[key])))
33  iteration += 1
34  if iteration > lifeSaver:
35  problematicLines = ""
36  for line in result.splitlines():
37  if ".oO[" in result and "]Oo." in line:
38  problematicLines += "%s\n"%line
39  msg = ("Oh Dear, there seems to be an endless loop in "
40  "replaceByMap!!\n%s\n%s"%(problematicLines, the_map))
41  raise AllInOneError(msg)
42  return result
43 
44 
45 def getCommandOutput2(command):
46  """This function executes `command` and returns it output.
47 
48  Arguments:
49  - `command`: Shell command to be invoked by this function.
50  """
51 
52  child = os.popen(command)
53  data = child.read()
54  err = child.close()
55  if err:
56  raise RuntimeError('%s failed w/ exit code %d' % (command, err))
57  return data
58 
59 
60 def castorDirExists(path):
61  """This function checks if the directory given by `path` exists.
62 
63  Arguments:
64  - `path`: Path to castor directory
65  """
66 
67  if path[-1] == "/":
68  path = path[:-1]
69  containingPath = os.path.join( *path.split("/")[:-1] )
70  dirInQuestion = path.split("/")[-1]
71  try:
72  rawLines = getCommandOutput2("rfdir /"+containingPath).splitlines()
73  except RuntimeError:
74  return False
75  for line in rawLines:
76  if line.split()[0][0] == "d":
77  if line.split()[8] == dirInQuestion:
78  return True
79  return False
80 
81 def replacelast(string, old, new, count = 1):
82  """Replace the last occurances of a string"""
83  return new.join(string.rsplit(old,count))
84 
85 fileExtensions = ["_cfg.py", ".sh", ".root"]
86 
87 def addIndex(filename, njobs, index = None):
88  if index is None:
89  return [addIndex(filename, njobs, i) for i in range(njobs)]
90  if njobs == 1:
91  return filename
92 
93  fileExtension = None
94  for extension in fileExtensions:
95  if filename.endswith(extension):
96  fileExtension = extension
97  if fileExtension is None:
98  raise AllInOneError(fileName + " does not end with any of the extensions "
99  + str(fileExtensions))
100  return replacelast(filename, fileExtension, "_" + str(index) + fileExtension)
101 
102 def parsecolor(color):
103  try: #simplest case: it's an int
104  return int(color)
105  except ValueError:
106  pass
107 
108  try: #kRed, kBlue, ...
109  color = str(getattr(ROOT, color))
110  return int(color)
111  except (AttributeError, ValueError):
112  pass
113 
114  if color.count("+") + color.count("-") == 1: #kRed+5, kGreen-2
115  if "+" in color: #don't want to deal with nonassociativity of -
116  split = color.split("+")
117  color1 = parsecolor(split[0])
118  color2 = parsecolor(split[1])
119  return color1 + color2
120 
121  if "-" in color:
122  split = color.split("-")
123  color1 = parsecolor(split[0])
124  color2 = parsecolor(split[1])
125  return color1 - color2
126 
127  raise AllInOneError("color has to be an integer, a ROOT constant (kRed, kBlue, ...), or a two-term sum or difference (kGreen-5)!")
128 
129 def parsestyle(style):
130  try: #simplest case: it's an int
131  return int(style)
132  except ValueError:
133  pass
134 
135  try: #kStar, kDot, ...
136  style = str(getattr(ROOT,style))
137  return int(style)
138  except (AttributeError, ValueError):
139  pass
140 
141  raise AllInOneError("style has to be an integer or a ROOT constant (kDashed, kStar, ...)!")
142 
144  result = [cls]
145  for subcls in cls.__subclasses__():
146  result += recursivesubclasses(subcls)
147  return result
148 
149 def cache(function):
150  cache = {}
151  def newfunction(*args, **kwargs):
152  try:
153  return cache[args, tuple(sorted(kwargs.iteritems()))]
154  except TypeError:
155  print args, tuple(sorted(kwargs.iteritems()))
156  raise
157  except KeyError:
158  cache[args, tuple(sorted(kwargs.iteritems()))] = function(*args, **kwargs)
159  return newfunction(*args, **kwargs)
160  newfunction.__name__ = function.__name__
161  return newfunction
162 
163 def boolfromstring(string, name):
164  """
165  Takes a string from the configuration file
166  and makes it into a bool
167  """
168  #try as a string, not case sensitive
169  if string.lower() == "true": return True
170  if string.lower() == "false": return False
171  #try as a number
172  try:
173  return str(bool(int(string)))
174  except ValueError:
175  pass
176  #out of options
177  raise ValueError("{} has to be true or false!".format(name))
178 
179 
180 def pythonboolstring(string, name):
181  """
182  Takes a string from the configuration file
183  and makes it into a bool string for a python template
184  """
185  return str(boolfromstring(string, name))
186 
187 def cppboolstring(string, name):
188  """
189  Takes a string from the configuration file
190  and makes it into a bool string for a C++ template
191  """
192  return pythonboolstring(string, name).lower()
Definition: vlib.h:256
def parsestyle(style)
def pythonboolstring(string, name)
def getCommandOutput2(command)
def cppboolstring(string, name)
def addIndex(filename, njobs, index=None)
def replacelast(string, old, new, count=1)
def cache(function)
def replaceByMap(target, the_map)
— Helpers —############################
def boolfromstring(string, name)
def parsecolor(color)
def castorDirExists(path)
def recursivesubclasses(cls)