CMS 3D CMS Logo

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