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 hasattr(self, "_nPerLine"):
593  nPerLine = self._nPerLine
594  else:
595  nPerLine = 5
596  if n>nPerLine: options.indent()
597  if n>=256:
598  #wrap in a tuple since they don't have a size constraint
599  result+=" ("
600  for i, v in enumerate(self):
601  if i == 0:
602  if n>nPerLine: result += '\n'+options.indentation()
603  else:
604  result += ', '
605  if i % nPerLine == 0:
606  result += '\n'+options.indentation()
607  result += self.pythonValueForItem(v,options)
608  if n>nPerLine:
609  options.unindent()
610  result += '\n'+options.indentation()
611  if n>=256:
612  result +=' ) '
613  result += ')'
614  return result
615  @staticmethod
616  def _itemsFromStrings(strings,converter):
617  return (converter(x).value() for x in strings)
618 
619 def saveOrigin(obj, level):
620  #frame = inspect.stack()[level+1]
621  frame = inspect.getframeinfo(inspect.currentframe(level+1))
622  # not safe under old python versions
623  #obj._filename = frame.filename
624  #obj._lineNumber = frame.lineno
625  obj._filename = frame[0]
626  obj._lineNumber = frame[1]
627 
628 def _modifyParametersFromDict(params, newParams, errorRaiser, keyDepth=""):
629  if len(newParams):
630  #need to treat items both in params and myparams specially
631  for key,value in newParams.iteritems():
632  if key in params:
633  if value is None:
634  del params[key]
635  elif isinstance(value, dict):
636  if isinstance(params[key],_Parameterizable):
637  pset = params[key]
638  p =pset.parameters_()
639  oldkeys = set(p.keys())
641  value,errorRaiser,
642  ("%s.%s" if type(key)==str else "%s[%s]")%(keyDepth,key))
643  for k,v in p.iteritems():
644  setattr(pset,k,v)
645  oldkeys.discard(k)
646  for k in oldkeys:
647  delattr(pset,k)
648  elif isinstance(params[key],_ValidatingParameterListBase):
649  if any(type(k) != int for k in value.keys()):
650  raise TypeError("Attempted to change a list using a dict whose keys are not integers")
651  plist = params[key]
652  if any((k < 0 or k >= len(plist)) for k in value.keys()):
653  raise IndexError("Attempted to set an index which is not in the list")
654  p = dict(enumerate(plist))
656  value,errorRaiser,
657  ("%s.%s" if type(key)==str else "%s[%s]")%(keyDepth,key))
658  for k,v in p.iteritems():
659  plist[k] = v
660  else:
661  raise ValueError("Attempted to change non PSet value "+keyDepth+" using a dictionary")
662  elif isinstance(value,_ParameterTypeBase) or (type(key) == int):
663  params[key] = value
664  else:
665  params[key].setValue(value)
666  else:
667  if isinstance(value,_ParameterTypeBase):
668  params[key]=value
669  else:
670  errorRaiser(key)
671 
672 
673 if __name__ == "__main__":
674 
675  import unittest
677  def _itemIsValid(self,item):
678  return True
679  class testMixins(unittest.TestCase):
681  t = TestList(1)
682  self.assertEqual(t,[1])
683  t = TestList((1,))
684  self.assertEqual(t,[1])
685  t = TestList("one")
686  self.assertEqual(t,["one"])
687  t = TestList( [1,])
688  self.assertEqual(t,[1])
689  t = TestList( (x for x in [1]) )
690  self.assertEqual(t,[1])
691 
692  t = TestList(1,2)
693  self.assertEqual(t,[1,2])
694  t = TestList((1,2))
695  self.assertEqual(t,[1,2])
696  t = TestList("one","two")
697  self.assertEqual(t,["one","two"])
698  t = TestList(("one","two"))
699  self.assertEqual(t,["one","two"])
700  t = TestList( [1,2])
701  self.assertEqual(t,[1,2])
702  t = TestList( (x for x in [1,2]) )
703  self.assertEqual(t,[1,2])
704  t = TestList( iter((1,2)) )
705  self.assertEqual(t,[1,2])
706 
707 
708  def testLargeList(self):
709  #lists larger than 255 entries can not be initialized
710  #using the constructor
711  args = [i for i in xrange(0,300)]
712 
713  t = TestList(*args)
714  pdump= t.dumpPython()
715  class cms(object):
716  def __init__(self):
717  self.TestList = TestList
718  pythonized = eval( pdump, globals(),{'cms':cms()} )
719  self.assertEqual(t,pythonized)
720  def testUsingBlock(self):
721  a = UsingBlock("a")
722  self.assert_(isinstance(a, _ParameterTypeBase))
723  def testCopy(self):
724  class __Test(_TypedParameterizable):
725  pass
726  class __TestType(_SimpleParameterTypeBase):
727  def _isValid(self,value):
728  return True
729  a = __Test("MyType",t=__TestType(1), u=__TestType(2))
730  b = a.copy()
731  self.assertEqual(b.t.value(),1)
732  self.assertEqual(b.u.value(),2)
733  def testClone(self):
734  class __Test(_TypedParameterizable):
735  pass
736  class __TestType(_SimpleParameterTypeBase):
737  def _isValid(self,value):
738  return True
739  class __PSet(_ParameterTypeBase,_Parameterizable):
740  def __init__(self,*arg,**args):
741  #need to call the inits separately
742  _ParameterTypeBase.__init__(self)
743  _Parameterizable.__init__(self,*arg,**args)
744  a = __Test("MyType",
745  t=__TestType(1),
746  u=__TestType(2),
747  w = __TestType(3),
748  x = __PSet(a = __TestType(4),
749  b = __TestType(6),
750  c = __PSet(gamma = __TestType(5))))
751  b = a.clone(t=3,
752  v=__TestType(4),
753  w= None,
754  x = dict(a = 7,
755  c = dict(gamma = 8),
756  d = __TestType(9)))
757  c = a.clone(x = dict(a=None, c=None))
758  self.assertEqual(a.t.value(),1)
759  self.assertEqual(a.u.value(),2)
760  self.assertEqual(b.t.value(),3)
761  self.assertEqual(b.u.value(),2)
762  self.assertEqual(b.v.value(),4)
763  self.assertEqual(b.x.a.value(),7)
764  self.assertEqual(b.x.b.value(),6)
765  self.assertEqual(b.x.c.gamma.value(),8)
766  self.assertEqual(b.x.d.value(),9)
767  self.assertEqual(hasattr(b,"w"), False)
768  self.assertEqual(hasattr(c.x,"a"), False)
769  self.assertEqual(hasattr(c.x,"c"), False)
770  self.assertRaises(TypeError,a.clone,None,**{"v":1})
771  def testModified(self):
772  class __TestType(_SimpleParameterTypeBase):
773  def _isValid(self,value):
774  return True
775  a = __TestType(1)
776  self.assertEqual(a.isModified(),False)
777  a.setValue(1)
778  self.assertEqual(a.isModified(),False)
779  a.setValue(2)
780  self.assertEqual(a.isModified(),True)
781  a.resetModified()
782  self.assertEqual(a.isModified(),False)
785  pass
787  def _isValid(self,value):
788  return True
789  class __DummyModule(object):
790  def __init__(self):
791  self.tLPTest = tLPTest
792  self.tLPTestType = tLPTestType
793  p = tLPTest("MyType",** dict( [ ("a"+str(x), tLPTestType(x)) for x in xrange(0,300) ] ) )
794  #check they are the same
795  self.assertEqual(p.dumpPython(), eval(p.dumpPython(),{"cms": __DummyModule()}).dumpPython())
796  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:771
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:628
def __setParameters(self, parameters)
Definition: Mixins.py:207
def _findDependencies(self, knownDeps, presentDeps)
Definition: Mixins.py:486
def testClone(self)
Definition: Mixins.py:733
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:723
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:680
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:616
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:783
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:619
def __raiseBadSetAttr(name)
Definition: Mixins.py:246
def testUsingBlock(self)
Definition: Mixins.py:720
def configValue(self, options=PrintOptions())
Definition: Mixins.py:66
def _itemIsValid(self, item)
Definition: Mixins.py:677
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:708
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