test
CMS 3D CMS Logo

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