CMS 3D CMS Logo

Mixins.py
Go to the documentation of this file.
1 import inspect
2 
4  """Denotes a class that can be used by the Processes class"""
5  def _isTaskComponent(self):
6  return False
7 
9  def __init__(self):
10  self.indent_= 0
11  self.deltaIndent_ = 4
12  self.isCfg = True
13  def indentation(self):
14  return ' '*self.indent_
15  def indent(self):
16  self.indent_ += self.deltaIndent_
17  def unindent(self):
18  self.indent_ -= self.deltaIndent_
19 
21  """base class for classes which are used as the 'parameters' for a ParameterSet"""
22  def __init__(self):
23  self.__dict__["_isFrozen"] = False
24  self.__isTracked = True
25  self._isModified = False
26  def isModified(self):
27  return self._isModified
28  def resetModified(self):
29  self._isModified=False
30  def configTypeName(self):
31  if self.isTracked():
32  return type(self).__name__
33  return 'untracked '+type(self).__name__
34  def pythonTypeName(self):
35  if self.isTracked():
36  return 'cms.'+type(self).__name__
37  return 'cms.untracked.'+type(self).__name__
38  def dumpPython(self, options=PrintOptions()):
39  return self.pythonTypeName()+"("+self.pythonValue(options)+")"
40  def __repr__(self):
41  return self.dumpPython()
42  def isTracked(self):
43  return self.__isTracked
44  def setIsTracked(self,trackness):
45  self.__isTracked = trackness
46  def isFrozen(self):
47  return self._isFrozen
48  def setIsFrozen(self):
49  self._isFrozen = True
50 
52  """base class for parameter classes which only hold a single value"""
53  def __init__(self,value):
54  super(_SimpleParameterTypeBase,self).__init__()
55  self._value = value
56  if not self._isValid(value):
57  raise ValueError(str(value)+" is not a valid "+str(type(self)))
58  def value(self):
59  return self._value
60  def setValue(self,value):
61  if not self._isValid(value):
62  raise ValueError(str(value)+" is not a valid "+str(type(self)))
63  if value!=self._value:
64  self._isModified=True
65  self._value=value
66  def configValue(self, options=PrintOptions()):
67  return str(self._value)
68  def pythonValue(self, options=PrintOptions()):
69  return self.configValue(options)
70  def __eq__(self,other):
71  if isinstance(other,_SimpleParameterTypeBase):
72  return self._value == other._value
73  return self._value == other
74  def __ne__(self,other):
75  if isinstance(other,_SimpleParameterTypeBase):
76  return self._value != other._value
77  return self._value != other
78  def __lt__(self,other):
79  if isinstance(other,_SimpleParameterTypeBase):
80  return self._value < other._value
81  return self._value < other
82  def __le__(self,other):
83  if isinstance(other,_SimpleParameterTypeBase):
84  return self._value <= other._value
85  return self._value <= other
86  def __gt__(self,other):
87  if isinstance(other,_SimpleParameterTypeBase):
88  return self._value > other._value
89  return self._value > other
90  def __ge__(self,other):
91  if isinstance(other,_SimpleParameterTypeBase):
92  return self._value >= other._value
93  return self._value >= other
94 
95 
97  """For injection purposes, pretend this is a new parameter type
98  then have a post process step which strips these out
99  """
100  def __init__(self,value, s='', loc=0, file=''):
101  super(UsingBlock,self).__init__(value)
102  self.s = s
103  self.loc = loc
104  self.file = file
105  self.isResolved = False
106  @staticmethod
107  def _isValid(value):
108  return isinstance(value,str)
109  def _valueFromString(value):
110  """only used for cfg-parsing"""
111  return string(value)
112  def insertInto(self, parameterSet, myname):
113  value = self.value()
114  # doesn't seem to handle \0 correctly
115  #if value == '\0':
116  # value = ''
117  parameterSet.addString(self.isTracked(), myname, value)
118  def dumpPython(self, options=PrintOptions()):
119  if options.isCfg:
120  return "process."+self.value()
121  else:
122  return self.value()
123 
124 
126  """Base class for classes which allow addition of _ParameterTypeBase data"""
127  def __init__(self,*arg,**kargs):
128  self.__dict__['_Parameterizable__parameterNames'] = []
129  self.__dict__["_isFrozen"] = False
130  """The named arguments are the 'parameters' which are added as 'python attributes' to the object"""
131  if len(arg) != 0:
132  #raise ValueError("unnamed arguments are not allowed. Please use the syntax 'name = value' when assigning arguments.")
133  for block in arg:
134  if type(block).__name__ != "PSet":
135  raise ValueError("Only PSets can be passed as unnamed argument blocks. This is a "+type(block).__name__)
136  self.__setParameters(block.parameters_())
137  self.__setParameters(kargs)
138  self._isModified = False
139 
140  def parameterNames_(self):
141  """Returns the name of the parameters"""
142  return self.__parameterNames[:]
143  def isModified(self):
144  if self._isModified:
145  return True
146  for name in self.parameterNames_():
147  param = self.__dict__[name]
148  if isinstance(param, _Parameterizable) and param.isModified():
149  self._isModified = True
150  return True
151  return False
152 
153  def hasParameter(self, params):
154  """
155  _hasParameter_
156 
157  check that pset provided has the attribute chain
158  specified.
159 
160  Eg, if params is [ 'attr1', 'attr2', 'attr3' ]
161  check for pset.attr1.attr2.attr3
162 
163  returns True if parameter exists, False if not
164  """
165  return (self.getParameter(params) != None)
166 
167  def getParameter(self, params):
168  """
169  _getParameter_
170 
171  Retrieve the specified parameter from the PSet Provided
172  given the attribute chain
173 
174  returns None if not found
175  """
176  lastParam = self
177  # Don't accidentally iterate over letters in a string
178  if type(params).__name__ == 'str':
179  return getattr(self, params, None)
180  for param in params:
181  lastParam = getattr(lastParam, param, None)
182  print str(lastParam)
183  if lastParam == None:
184  return None
185  return lastParam
186 
187  def parameters_(self):
188  """Returns a dictionary of copies of the user-set parameters"""
189  import copy
190  result = dict()
191  for name in self.parameterNames_():
192  result[name]=copy.deepcopy(self.__dict__[name])
193  return result
194 
195  def __addParameter(self, name, value):
196  if not isinstance(value,_ParameterTypeBase):
197  self.__raiseBadSetAttr(name)
198  if name in self.__dict__:
199  message = "Duplicate insert of member " + name
200  message += "\nThe original parameters are:\n"
201  message += self.dumpPython() + '\n'
202  raise ValueError(message)
203  self.__dict__[name]=value
204  self.__parameterNames.append(name)
205  self._isModified = True
206 
207  def __setParameters(self,parameters):
208  for name,value in parameters.iteritems():
209  self.__addParameter(name, value)
210 
211  def __setattr__(self,name,value):
212  #since labels are not supposed to have underscores at the beginning
213  # I will assume that if we have such then we are setting an internal variable
214  if self.isFrozen() and not (name in ["_Labelable__label","_isFrozen"] or name.startswith('_')):
215  message = "Object already added to a process. It is read only now\n"
216  message += " %s = %s" %(name, value)
217  message += "\nThe original parameters are:\n"
218  message += self.dumpPython() + '\n'
219  raise ValueError(message)
220  # underscored names bypass checking for _ParameterTypeBase
221  if name[0]=='_':
222  super(_Parameterizable,self).__setattr__(name,value)
223  elif not name in self.__dict__:
224  self.__addParameter(name, value)
225  self._isModified = True
226  else:
227  # handle the case where users just replace with a value, a = 12, rather than a = cms.int32(12)
228  if isinstance(value,_ParameterTypeBase):
229  self.__dict__[name] = value
230  else:
231  self.__dict__[name].setValue(value)
232  self._isModified = True
233 
234  def isFrozen(self):
235  return self._isFrozen
236  def setIsFrozen(self):
237  self._isFrozen = True
238  for name in self.parameterNames_():
239  self.__dict__[name].setIsFrozen()
240  def __delattr__(self,name):
241  if self.isFrozen():
242  raise ValueError("Object already added to a process. It is read only now")
243  super(_Parameterizable,self).__delattr__(name)
244  self.__parameterNames.remove(name)
245  @staticmethod
246  def __raiseBadSetAttr(name):
247  raise TypeError(name+" does not already exist, so it can only be set to a CMS python configuration type")
248  def dumpPython(self, options=PrintOptions()):
249  sortedNames = sorted(self.parameterNames_())
250  if len(sortedNames) > 200:
251  #Too many parameters for a python function call
252  # The solution is to create a temporary dictionary which
253  # is constructed by concatenating long lists (with maximum
254  # 200 entries each) together.
255  # This looks like
256  # **dict( [(...,...), ...] + [...] + ... )
257  others = []
258  usings = []
259  for name in sortedNames:
260  param = self.__dict__[name]
261  # we don't want minuses in names
262  name2 = name.replace('-','_')
263  options.indent()
264  #_UsingNodes don't get assigned variables
265  if name.startswith("using_"):
266  usings.append(options.indentation()+param.dumpPython(options))
267  else:
268  others.append((name2, param.dumpPython(options)))
269  options.unindent()
270 
271  resultList = ',\n'.join(usings)
272  longOthers = options.indentation()+"**dict(\n"
273  options.indent()
274  longOthers += options.indentation()+"[\n"
275  entriesInList = 0
276  options.indent()
277  for n,v in others:
278  entriesInList +=1
279  if entriesInList > 200:
280  #need to start a new list
281  options.unindent()
282  longOthers += options.indentation()+"] +\n"+options.indentation()+"[\n"
283  entriesInList = 0
284  options.indent()
285  longOthers += options.indentation()+'("'+n+'" , '+v+' ),\n'
286 
287  longOthers += options.indentation()+"]\n"
288  options.unindent()
289  longOthers +=options.indentation()+")\n"
290  options.unindent()
291  ret = []
292  if resultList:
293  ret.append(resultList)
294  if longOthers:
295  ret.append(longOthers)
296  return ",\n".join(ret)
297  #Standard case, small number of parameters
298  others = []
299  usings = []
300  for name in sortedNames:
301  param = self.__dict__[name]
302  # we don't want minuses in names
303  name2 = name.replace('-','_')
304  options.indent()
305  #_UsingNodes don't get assigned variables
306  if name.startswith("using_"):
307  usings.append(options.indentation()+param.dumpPython(options))
308  else:
309  others.append(options.indentation()+name2+' = '+param.dumpPython(options))
310  options.unindent()
311  # usings need to go first
312  resultList = usings
313  resultList.extend(others)
314  return ',\n'.join(resultList)+'\n'
315  def __repr__(self):
316  return self.dumpPython()
317  def insertContentsInto(self, parameterSet):
318  for name in self.parameterNames_():
319  param = getattr(self,name)
320  param.insertInto(parameterSet, name)
321 
322 
324  """Base class for classes which are Parameterizable and have a 'type' assigned"""
325  def __init__(self,type_,*arg,**kargs):
326  self.__dict__['_TypedParameterizable__type'] = type_
327  #the 'type' is also placed in the 'arg' list and we need to remove it
328  #if 'type_' not in kargs:
329  # arg = arg[1:]
330  #else:
331  # del args['type_']
332  arg = tuple([x for x in arg if x != None])
333  super(_TypedParameterizable,self).__init__(*arg,**kargs)
334  saveOrigin(self, 1)
335  def _place(self,name,proc):
336  self._placeImpl(name,proc)
337  def type_(self):
338  """returns the type of the object, e.g. 'FooProducer'"""
339  return self.__type
340  def copy(self):
341  returnValue =_TypedParameterizable.__new__(type(self))
342  params = self.parameters_()
343  args = list()
344  if len(params) == 0:
345  args.append(None)
346  returnValue.__init__(self.__type,*args,
347  **params)
348  returnValue._isModified = self._isModified
349  return returnValue
350  def clone(self, *args, **params):
351  """Copies the object and allows one to modify the parameters of the clone.
352  New parameters may be added by specify the exact type
353  Modifying existing parameters can be done by just specifying the new
354  value without having to specify the type.
355  A parameter may be removed from the clone using the value None.
356  #remove the parameter foo.fred
357  mod.toModify(foo, fred = None)
358  A parameter embedded within a PSet may be changed via a dictionary
359  #change foo.fred.pebbles to 3 and foo.fred.friend to "barney"
360  mod.toModify(foo, fred = dict(pebbles = 3, friend = "barney)) )
361  """
362  returnValue =_TypedParameterizable.__new__(type(self))
363  myparams = self.parameters_()
364  if len(myparams) == 0 and len(params) and len(args):
365  args.append(None)
366 
367  _modifyParametersFromDict(myparams, params, self._Parameterizable__raiseBadSetAttr)
368 
369  returnValue.__init__(self.__type,*args,
370  **myparams)
371  returnValue._isModified = False
372  returnValue._isFrozen = False
373  saveOrigin(returnValue, 1)
374  return returnValue
375 
376  @staticmethod
377  def __findDefaultsFor(label,type):
378  #This routine is no longer used, but I might revive it in the future
379  import sys
380  import glob
381  choices = list()
382  for d in sys.path:
383  choices.extend(glob.glob(d+'/*/*/'+label+'.py'))
384  if not choices:
385  return None
386  #now see if any of them have what we want
387  #the use of __import__ is taken from an example
388  # from the www.python.org documentation on __import__
389  for c in choices:
390  #print " found file "+c
391  name='.'.join(c[:-3].split('/')[-3:])
392  #name = c[:-3].replace('/','.')
393  mod = __import__(name)
394  components = name.split('.')
395  for comp in components[1:]:
396  mod = getattr(mod,comp)
397  if hasattr(mod,label):
398  default = getattr(mod,label)
399  if isinstance(default,_TypedParameterizable):
400  if(default.type_() == type):
401  params = dict()
402  for name in default.parameterNames_():
403  params[name] = getattr(default,name)
404  return params
405  return None
406 
407  def dumpConfig(self, options=PrintOptions()):
408  config = self.__type +' { \n'
409  for name in self.parameterNames_():
410  param = self.__dict__[name]
411  options.indent()
412  config+=options.indentation()+param.configTypeName()+' '+name+' = '+param.configValue(options)+'\n'
413  options.unindent()
414  config += options.indentation()+'}\n'
415  return config
416 
417  def dumpPython(self, options=PrintOptions()):
418  result = "cms."+str(type(self).__name__)+'("'+self.type_()+'"'
419  nparam = len(self.parameterNames_())
420  if nparam == 0:
421  result += ")\n"
422  else:
423  result += ",\n"+_Parameterizable.dumpPython(self,options)+options.indentation() + ")\n"
424  return result
425 
426  def dumpPythonAttributes(self, myname, options):
427  """ dumps the object with all attributes declared after the constructor"""
428  result = ""
429  for name in sorted(self.parameterNames_()):
430  param = self.__dict__[name]
431  result += options.indentation() + myname + "." + name + " = " + param.dumpPython(options) + "\n"
432  return result
433 
434  def nameInProcessDesc_(self, myname):
435  return myname;
436  def moduleLabel_(self, myname):
437  return myname
438  def insertInto(self, parameterSet, myname):
439  newpset = parameterSet.newPSet()
440  newpset.addString(True, "@module_label", self.moduleLabel_(myname))
441  newpset.addString(True, "@module_type", self.type_())
442  newpset.addString(True, "@module_edm_type", type(self).__name__)
443  self.insertContentsInto(newpset)
444  parameterSet.addPSet(True, self.nameInProcessDesc_(myname), newpset)
445 
446 
447 
449  """A 'mixin' used to denote that the class can be paired with a label (e.g. an EDProducer)"""
450  def label_(self):
451  if not hasattr(self, "_Labelable__label"):
452  raise RuntimeError("module has no label. Perhaps it wasn't inserted into the process?")
453  return self.__label
454  def hasLabel_(self):
455  return hasattr(self, "_Labelable__label") and self.__label is not None
456  def setLabel(self,label):
457  if self.hasLabel_() :
458  if self.label_() != label and label is not None :
459  msg100 = "Attempting to change the label of a Labelable object, possibly an attribute of the Process\n"
460  msg101 = "Old label = "+self.label_()+" New label = "+label+"\n"
461  msg102 = "Type = "+str(type(self))+"\n"
462  msg103 = "Some possible solutions:\n"
463  msg104 = " 1. Clone modules instead of using simple assignment. Cloning is\n"
464  msg105 = " also preferred for other types when possible.\n"
465  msg106 = " 2. Declare new names starting with an underscore if they are\n"
466  msg107 = " for temporaries you do not want propagated into the Process. The\n"
467  msg108 = " underscore tells \"from x import *\" and process.load not to import\n"
468  msg109 = " the name.\n"
469  msg110 = " 3. Reorganize so the assigment is not necessary. Giving a second\n"
470  msg111 = " name to the same object usually causes confusion and problems.\n"
471  msg112 = " 4. Compose Sequences: newName = cms.Sequence(oldName)\n"
472  raise ValueError(msg100+msg101+msg102+msg103+msg104+msg105+msg106+msg107+msg108+msg109+msg110+msg111+msg112)
473  self.__label = label
474  def label(self):
475  #print "WARNING: _Labelable::label() needs to be changed to label_()"
476  return self.__label
477  def __str__(self):
478  #this is probably a bad idea
479  # I added this so that when we ask a path to print
480  # we will see the label that has been assigned
481  return str(self.__label)
483  return str(self.__label)
484  def dumpSequencePython(self, options=PrintOptions()):
485  return 'process.'+str(self.__label)
486  def _findDependencies(self,knownDeps,presentDeps):
487  #print 'in labelled'
488  myDeps=knownDeps.get(self.label_(),None)
489  if myDeps!=None:
490  if presentDeps != myDeps:
491  raise RuntimeError("the module "+self.label_()+" has two dependencies \n"
492  +str(presentDeps)+"\n"
493  +str(myDeps)+"\n"
494  +"Please modify sequences to rectify this inconsistency")
495  else:
496  myDeps=set(presentDeps)
497  knownDeps[self.label_()]=myDeps
498  presentDeps.add(self.label_())
499 
500 
502  """A 'mixin' used to denote that the class can be used without a label (e.g. a Service)"""
503  pass
504 
505 class _ValidatingListBase(list):
506  """Base class for a list which enforces that its entries pass a 'validity' test"""
507  def __init__(self,*arg,**args):
508  super(_ValidatingListBase,self).__init__(arg)
509  if 0 != len(args):
510  raise SyntaxError("named arguments ("+','.join([x for x in args])+") passsed to "+str(type(self)))
511  if not self._isValid(iter(self)):
512  raise TypeError("wrong types ("+','.join([str(type(value)) for value in iter(self)])+
513  ") added to "+str(type(self)))
514  def __setitem__(self,key,value):
515  if isinstance(key,slice):
516  if not self._isValid(value):
517  raise TypeError("wrong type being inserted into this container "+self._labelIfAny())
518  else:
519  if not self._itemIsValid(value):
520  raise TypeError("can not insert the type "+str(type(value))+" in container "+self._labelIfAny())
521  super(_ValidatingListBase,self).__setitem__(key,value)
522  def _isValid(self,seq):
523  # see if strings get reinterpreted as lists
524  if isinstance(seq, str):
525  return False
526  for item in seq:
527  if not self._itemIsValid(item):
528  return False
529  return True
530  def append(self,x):
531  if not self._itemIsValid(x):
532  raise TypeError("wrong type being appended to container "+self._labelIfAny())
533  super(_ValidatingListBase,self).append(x)
534  def extend(self,x):
535  if not self._isValid(x):
536  raise TypeError("wrong type being extended to container "+self._labelIfAny())
537  super(_ValidatingListBase,self).extend(x)
538  def __add__(self,rhs):
539  if not self._isValid(rhs):
540  raise TypeError("wrong type being added to container "+self._labelIfAny())
541  import copy
542  value = copy.copy(self)
543  value.extend(rhs)
544  return value
545  def insert(self,i,x):
546  if not self._itemIsValid(x):
547  raise TypeError("wrong type being inserted to container "+self._labelIfAny())
548  super(_ValidatingListBase,self).insert(i,x)
549  def _labelIfAny(self):
550  result = type(self).__name__
551  if hasattr(self, '__label'):
552  result += ' ' + self.__label
553  return result
554 
556  def __init__(self,*arg,**args):
557  _ParameterTypeBase.__init__(self)
558  if len (arg) == 1 and not isinstance(arg[0],str):
559  try:
560  arg = iter(arg[0])
561  except TypeError:
562  pass
563  super(_ValidatingParameterListBase,self).__init__(*arg,**args)
564  def value(self):
565  return list(self)
566  def setValue(self,v):
567  self[:] = []
568  self.extend(v)
569  self._isModified=True
570  def configValue(self, options=PrintOptions()):
571  config = '{\n'
572  first = True
573  for value in iter(self):
574  options.indent()
575  config += options.indentation()
576  if not first:
577  config+=', '
578  config+= self.configValueForItem(value, options)+'\n'
579  first = False
580  options.unindent()
581  config += options.indentation()+'}\n'
582  return config
583  def configValueForItem(self,item, options):
584  return str(item)
585  def pythonValueForItem(self,item, options):
586  return self.configValueForItem(item, options)
587  def __repr__(self):
588  return self.dumpPython()
589  def dumpPython(self, options=PrintOptions()):
590  result = self.pythonTypeName()+"("
591  n = len(self)
592  if n>=256:
593  #wrap in a tuple since they don't have a size constraint
594  result+=" ("
595  indented = False
596  for i, v in enumerate(self):
597  if i == 0:
598  if hasattr(self, "_nPerLine"):
599  nPerLine = self._nPerLine
600  else:
601  nPerLine = 5
602  else:
603  if not indented:
604  indented = True
605  options.indent()
606  result += ', '
607  if i % nPerLine == 0:
608  result += '\n'+options.indentation()
609  result += self.pythonValueForItem(v,options)
610  if indented:
611  options.unindent()
612  #result+=', '.join((self.pythonValueForItem(v,options) for v in iter(self)))
613  if n>=256:
614  result +=' ) '
615  result += ')'
616  return result
617  @staticmethod
618  def _itemsFromStrings(strings,converter):
619  return (converter(x).value() for x in strings)
620 
621 def saveOrigin(obj, level):
622  #frame = inspect.stack()[level+1]
623  frame = inspect.getframeinfo(inspect.currentframe(level+1))
624  # not safe under old python versions
625  #obj._filename = frame.filename
626  #obj._lineNumber = frame.lineno
627  obj._filename = frame[0]
628  obj._lineNumber = frame[1]
629 
630 def _modifyParametersFromDict(params, newParams, errorRaiser, keyDepth=""):
631  if len(newParams):
632  #need to treat items both in params and myparams specially
633  for key,value in newParams.iteritems():
634  if key in params:
635  if value is None:
636  del params[key]
637  elif isinstance(value, dict):
638  if isinstance(params[key],_Parameterizable):
639  pset = params[key]
640  p =pset.parameters_()
642  value,errorRaiser,
643  ("%s.%s" if type(key)==str else "%s[%s]")%(keyDepth,key))
644  for k,v in p.iteritems():
645  setattr(pset,k,v)
646  elif isinstance(params[key],_ValidatingParameterListBase):
647  if any(type(k) != int for k in value.keys()):
648  raise TypeError("Attempted to change a list using a dict whose keys are not integers")
649  plist = params[key]
650  if any((k < 0 or k >= len(plist)) for k in value.keys()):
651  raise IndexError("Attempted to set an index which is not in the list")
652  p = dict(enumerate(plist))
654  value,errorRaiser,
655  ("%s.%s" if type(key)==str else "%s[%s]")%(keyDepth,key))
656  for k,v in p.iteritems():
657  plist[k] = v
658  else:
659  raise ValueError("Attempted to change non PSet value "+keyDepth+" using a dictionary")
660  elif isinstance(value,_ParameterTypeBase) or (type(key) == int):
661  params[key] = value
662  else:
663  params[key].setValue(value)
664  else:
665  if isinstance(value,_ParameterTypeBase):
666  params[key]=value
667  else:
668  errorRaiser(key)
669 
670 
671 if __name__ == "__main__":
672 
673  import unittest
675  def _itemIsValid(self,item):
676  return True
677  class testMixins(unittest.TestCase):
679  t = TestList(1)
680  self.assertEqual(t,[1])
681  t = TestList((1,))
682  self.assertEqual(t,[1])
683  t = TestList("one")
684  self.assertEqual(t,["one"])
685  t = TestList( [1,])
686  self.assertEqual(t,[1])
687  t = TestList( (x for x in [1]) )
688  self.assertEqual(t,[1])
689 
690  t = TestList(1,2)
691  self.assertEqual(t,[1,2])
692  t = TestList((1,2))
693  self.assertEqual(t,[1,2])
694  t = TestList("one","two")
695  self.assertEqual(t,["one","two"])
696  t = TestList(("one","two"))
697  self.assertEqual(t,["one","two"])
698  t = TestList( [1,2])
699  self.assertEqual(t,[1,2])
700  t = TestList( (x for x in [1,2]) )
701  self.assertEqual(t,[1,2])
702  t = TestList( iter((1,2)) )
703  self.assertEqual(t,[1,2])
704 
705 
706  def testLargeList(self):
707  #lists larger than 255 entries can not be initialized
708  #using the constructor
709  args = [i for i in xrange(0,300)]
710 
711  t = TestList(*args)
712  pdump= t.dumpPython()
713  class cms(object):
714  def __init__(self):
715  self.TestList = TestList
716  pythonized = eval( pdump, globals(),{'cms':cms()} )
717  self.assertEqual(t,pythonized)
718  def testUsingBlock(self):
719  a = UsingBlock("a")
720  self.assert_(isinstance(a, _ParameterTypeBase))
721  def testCopy(self):
722  class __Test(_TypedParameterizable):
723  pass
724  class __TestType(_SimpleParameterTypeBase):
725  def _isValid(self,value):
726  return True
727  a = __Test("MyType",t=__TestType(1), u=__TestType(2))
728  b = a.copy()
729  self.assertEqual(b.t.value(),1)
730  self.assertEqual(b.u.value(),2)
731  def testClone(self):
732  class __Test(_TypedParameterizable):
733  pass
734  class __TestType(_SimpleParameterTypeBase):
735  def _isValid(self,value):
736  return True
737  class __PSet(_ParameterTypeBase,_Parameterizable):
738  def __init__(self,*arg,**args):
739  #need to call the inits separately
740  _ParameterTypeBase.__init__(self)
741  _Parameterizable.__init__(self,*arg,**args)
742  a = __Test("MyType",
743  t=__TestType(1),
744  u=__TestType(2),
745  w = __TestType(3),
746  x = __PSet(a = __TestType(4),
747  b = __TestType(6),
748  c = __PSet(gamma = __TestType(5))))
749  b = a.clone(t=3,
750  v=__TestType(4),
751  w= None,
752  x = dict(a = 7,
753  c = dict(gamma = 8),
754  d = __TestType(9)))
755  self.assertEqual(a.t.value(),1)
756  self.assertEqual(a.u.value(),2)
757  self.assertEqual(b.t.value(),3)
758  self.assertEqual(b.u.value(),2)
759  self.assertEqual(b.v.value(),4)
760  self.assertEqual(b.x.a.value(),7)
761  self.assertEqual(b.x.b.value(),6)
762  self.assertEqual(b.x.c.gamma.value(),8)
763  self.assertEqual(b.x.d.value(),9)
764  self.assertEqual(hasattr(b,"w"), False)
765  self.assertRaises(TypeError,a.clone,None,**{"v":1})
766  def testModified(self):
767  class __TestType(_SimpleParameterTypeBase):
768  def _isValid(self,value):
769  return True
770  a = __TestType(1)
771  self.assertEqual(a.isModified(),False)
772  a.setValue(1)
773  self.assertEqual(a.isModified(),False)
774  a.setValue(2)
775  self.assertEqual(a.isModified(),True)
776  a.resetModified()
777  self.assertEqual(a.isModified(),False)
780  pass
782  def _isValid(self,value):
783  return True
784  class __DummyModule(object):
785  def __init__(self):
786  self.tLPTest = tLPTest
787  self.tLPTestType = tLPTestType
788  p = tLPTest("MyType",** dict( [ ("a"+str(x), tLPTestType(x)) for x in xrange(0,300) ] ) )
789  #check they are the same
790  self.assertEqual(p.dumpPython(), eval(p.dumpPython(),{"cms": __DummyModule()}).dumpPython())
791  unittest.main()
def __init__(self, arg, args)
Definition: Mixins.py:507
def indent(self)
Definition: Mixins.py:15
def __gt__(self, other)
Definition: Mixins.py:86
def moduleLabel_(self, myname)
Definition: Mixins.py:436
def testModified(self)
Definition: Mixins.py:766
def label_(self)
Definition: Mixins.py:450
def pythonTypeName(self)
Definition: Mixins.py:34
def dumpPython(self, options=PrintOptions())
Definition: Mixins.py:38
def dumpConfig(self, options=PrintOptions())
Definition: Mixins.py:407
def insertInto(self, parameterSet, myname)
Definition: Mixins.py:112
def __eq__(self, other)
Definition: Mixins.py:70
def _modifyParametersFromDict(params, newParams, errorRaiser, keyDepth="")
Definition: Mixins.py:630
def __setParameters(self, parameters)
Definition: Mixins.py:207
def _findDependencies(self, knownDeps, presentDeps)
Definition: Mixins.py:486
def testClone(self)
Definition: Mixins.py:731
def dumpPython(self, options=PrintOptions())
Definition: Mixins.py:589
bool any(const std::vector< T > &v, const T &what)
Definition: ECalSD.cc:37
def testCopy(self)
Definition: Mixins.py:721
def dumpPython(self, options=PrintOptions())
Definition: Mixins.py:118
def __init__(self, arg, kargs)
Definition: Mixins.py:127
def unindent(self)
Definition: Mixins.py:17
def dumpPythonAttributes(self, myname, options)
Definition: Mixins.py:426
def _valueFromString(value)
Definition: Mixins.py:109
def __ne__(self, other)
Definition: Mixins.py:74
def append(self, x)
Definition: Mixins.py:530
def setLabel(self, label)
Definition: Mixins.py:456
def nameInProcessDesc_(self, myname)
Definition: Mixins.py:434
def insert(self, i, x)
Definition: Mixins.py:545
bool setValue(Container &, const reco::JetBaseRef &, const JetExtendedData &)
associate jet with value. Returns false and associate nothing if jet is already associated ...
def __le__(self, other)
Definition: Mixins.py:82
def dumpPython(self, options=PrintOptions())
Definition: Mixins.py:248
def isModified(self)
Definition: Mixins.py:26
def testListConstruction(self)
Definition: Mixins.py:678
def __init__(self)
Definition: Mixins.py:9
def insertInto(self, parameterSet, myname)
Definition: Mixins.py:438
def setIsFrozen(self)
Definition: Mixins.py:236
def dumpPython(self, options=PrintOptions())
Definition: Mixins.py:417
def isModified(self)
Definition: Mixins.py:143
def __delattr__(self, name)
Definition: Mixins.py:240
def _itemsFromStrings(strings, converter)
Definition: Mixins.py:618
def configTypeName(self)
Definition: Mixins.py:30
def clone(self, args, params)
Definition: Mixins.py:350
def setIsFrozen(self)
Definition: Mixins.py:48
def dumpSequenceConfig(self)
Definition: Mixins.py:482
def __init__(self, type_, arg, kargs)
Definition: Mixins.py:325
def testLargeParameterizable(self)
Definition: Mixins.py:778
def indentation(self)
Definition: Mixins.py:13
def __repr__(self)
Definition: Mixins.py:315
def resetModified(self)
Definition: Mixins.py:28
def __init__(self, value, s='', loc=0, file='')
Definition: Mixins.py:100
def __addParameter(self, name, value)
Definition: Mixins.py:195
def _place(self, name, proc)
Definition: Mixins.py:335
Definition: value.py:1
def __findDefaultsFor(label, type)
Definition: Mixins.py:377
def __setattr__(self, name, value)
Definition: Mixins.py:211
def saveOrigin(obj, level)
Definition: Mixins.py:621
def __raiseBadSetAttr(name)
Definition: Mixins.py:246
def testUsingBlock(self)
Definition: Mixins.py:718
def configValue(self, options=PrintOptions())
Definition: Mixins.py:66
def _itemIsValid(self, item)
Definition: Mixins.py:675
def _isTaskComponent(self)
Definition: Mixins.py:5
def configValue(self, options=PrintOptions())
Definition: Mixins.py:570
def _isValid(self, seq)
Definition: Mixins.py:522
def setIsTracked(self, trackness)
Definition: Mixins.py:44
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def hasParameter(self, params)
Definition: Mixins.py:153
def setValue(self, value)
Definition: Mixins.py:60
def __ge__(self, other)
Definition: Mixins.py:90
def extend(self, x)
Definition: Mixins.py:534
def _isValid(value)
Definition: Mixins.py:107
def parameterNames_(self)
Definition: Mixins.py:140
def dumpPython(process, name)
def __str__(self)
Definition: Mixins.py:477
def __add__(self, rhs)
Definition: Mixins.py:538
def pythonValueForItem(self, item, options)
Definition: Mixins.py:585
if(dp >Float(M_PI)) dp-
def label(self)
Definition: Mixins.py:474
def testLargeList(self)
Definition: Mixins.py:706
def isFrozen(self)
Definition: Mixins.py:234
def hasLabel_(self)
Definition: Mixins.py:454
def __setitem__(self, key, value)
Definition: Mixins.py:514
def pythonValue(self, options=PrintOptions())
Definition: Mixins.py:68
def configValueForItem(self, item, options)
Definition: Mixins.py:583
def __init__(self, value)
Definition: Mixins.py:53
def parameters_(self)
Definition: Mixins.py:187
def getParameter(self, params)
Definition: Mixins.py:167
double split
Definition: MVATrainer.cc:139
def insertContentsInto(self, parameterSet)
Definition: Mixins.py:317
def dumpSequencePython(self, options=PrintOptions())
Definition: Mixins.py:484
def __init__(self, arg, args)
Definition: Mixins.py:556
How EventSelector::AcceptEvent() decides whether to accept an event for output otherwise it is excluding the probing of A single or multiple positive and the trigger will pass if any such matching triggers are PASS or EXCEPTION[A criterion thatmatches no triggers at all is detected and causes a throw.] A single negative with an expectation of appropriate bit checking in the decision and the trigger will pass if any such matching triggers are FAIL or EXCEPTION A wildcarded negative criterion that matches more than one trigger in the trigger list("!*","!HLTx*"if it matches 2 triggers or more) will accept the event if all the matching triggers are FAIL.It will reject the event if any of the triggers are PASS or EXCEPTION(this matches the behavior of"!*"before the partial wildcard feature was incorporated).Triggers which are in the READY state are completely ignored.(READY should never be returned since the trigger paths have been run
def __lt__(self, other)
Definition: Mixins.py:78