CMS 3D CMS Logo

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