示例#1
0
	def set_variable_attributes(self):
		# Need to add units
		for key in self.variableNames.values():
			min_ = self.mhd_data[key].min()
			max_ = self.mhd_data[key].max()
			self.variableAttributes[key]['actual_min'] = Attribute('actual_min', float(min_))
			self.variableAttributes[key]['actual_max'] = Attribute('actual_max', float(max_))
示例#2
0
    def __init__(self):
        """default pyFileReader constructor

		This initializer calls the base class initializer.
		The variables dictionary is initialized here and is expected to be populated by the subclassing reader.
		"""
        super(pyFileReader, self).__init__()
        self.variables = {}  #created in subclass
        self.variableIDs = {}  #maps from variable string names to long ids
        self.variableNames = {}  #maps from long ids to string names
        self.globalAttributes = OrderedDict(
        )  #maps from attribute str names to global attribute objects
        self.globalAttributeNames = {}  #maps from ids to str names
        self.globalAttributeIDs = {}  #maps from str names to ids
        self.variableAttributes = {
        }  #maps from variable str names to dictionaries of variable attributes
        self.variableAttributeNames = {}  #maps from attribute IDs to name
        self.variableAttributeIDs = {}  #maps from attribute names to IDs
        self.globalAttributes['model_name'] = Attribute(
            'model_name', 'python_base_model')
        self.globalAttributes['python_model'] = Attribute('python_model', 1)
        self.debug = False
        self.missing_value = -256. * -256. * -256. * -256. * -256.  #same as ccmc::defaults::missingValue
        self.dummy_variable = pyKameleon.vectorFloat()
        self.dummy_variable.append(0)
示例#3
0
def getAttrFromIndex(list, index):
    for item in list:
        if (abs(index) == Attribute.getIndex(list[item])):
            if (index > 0):
                return Attribute.getValue(list[item])
            else:
                return Attribute.getInverseValue(list[item])
示例#4
0
 def dummyMethod_killACharacter(self):
     degenerate = Weather()
     health = Attribute("Health")
     health.setValue(-1)
     degenerate.addAttribute(health)
     ev = Events.CharacterUpdateEvent(self.characters[self.killerID].getName(), degenerate)
     self.mediator.post(ev)
	def test900_905_getmaxscore_noweights(self):
		correctError = "get_word: "
		try:
			a = Attribute()
			a.get_max_score()
			self.fail("Error: no error!")
		except ValueError, e:
			self.assertEqual(correctError, str(e)[:len(correctError)])
 def test000_000_init_blank(self):
     a = Attribute()
     correct = Attribute(name="Attribute",
                         attrWeight=1,
                         words=None,
                         weights=None,
                         sentiments=None)
     self.assertEquals(a, correct)
 def test900_905_getmaxscore_noweights(self):
     correctError = "get_word: "
     try:
         a = Attribute()
         a.get_max_score()
         self.fail("Error: no error!")
     except ValueError, e:
         self.assertEqual(correctError, str(e)[:len(correctError)])
 def test100_003_score_multiattr(self):
     attr1 = Attribute("1", 1, ["burgers"], [1], [0])
     attr2 = Attribute("2", 1, ["fries"], [2], [0])
     attr3 = Attribute("3", 1, ["tacos"], [3], [0])
     packet = SearchPacket([attr1, attr2, attr3])
     score = Scorer(packet)
     text = "I hate tacos and love fries and burgers are okay."
     self.assertEquals(score.score(text), [1, 2, 3, 0, 0])
示例#9
0
    def destroyAttribute(self, attribute: Attribute):
        try: 
            if attribute.getType() in self._pool:
                self._pool[attribute.getType()].remove(attribute)
                return True
            else:
                print("Trying to remove attribute with an unknown type:")
                print(attribute.getType())
        except ValueError:
            print("Trying to remove attribute that shouldn't exist:")
            print(attribute)

        return False
示例#10
0
    def _load(self, config):
        """Initialise deidentification methods
        """
        if config.RetainPatientCharacteristicsOption:
            # TODO: later this will be replaced with real loading
            method = DeidentMethod(
                "Retain Patient Characteristics Option",
                "Retention of information that would otherwise be removed during de-identification according to an option defined in PS 3.15 that requires that any physical characteristics of the patient, which are descriptive rather than identifying information per se, be retained. E.g., Patient's Age, Sex, Size (height) and Weight.",
                "113108", DeidentMethodType.OPTION)
            method.Attributes.append(
                Attribute("Ethnic Group", "0010", "2160",
                          KeepAttributeAction()))
            method.Attributes.append(
                Attribute("Patient Sex Neutered", "0010", "2203",
                          KeepAttributeAction()))
            method.Attributes.append(
                Attribute("Patient's Age", "0010", "1010",
                          KeepAttributeAction()))
            method.Attributes.append(
                Attribute("Patient's Sex", "0010", "0040",
                          KeepAttributeAction()))
            method.Attributes.append(
                Attribute("Patient's Size", "0010", "1020",
                          KeepAttributeAction()))
            method.Attributes.append(
                Attribute("Patient's Weight", "0010", "1030",
                          KeepAttributeAction()))
            method.Attributes.append(
                Attribute("Pregnancy Status", "0010", "21C0",
                          KeepAttributeAction()))
            method.Attributes.append(
                Attribute("Smoking Status", "0010", "21A0",
                          KeepAttributeAction()))

            self._methods.append(method)
示例#11
0
def GetAttributes(text):
    from settings import AttributeDefinition,FinalDefinition
    from settings import PrivateDefinition,PublicDefinition
    from settings import ProtectedDefinition,StaticDefinition
    text = CleanUnusedLogicalBlocks(text)
    Attributes = []
    for attributedef in AttributeDefinition:
        lines = text.split(attributedef[1])
        for line in lines:
            type = ""
            tmp_line = line.replace("\n","").replace("  "," ")
            if tmp_line.replace(" ","") =="":
                break
            for attribute in tmp_line.split(','):
                a = Attribute()
                atr = attribute
                if atr.find("=")>-1:
                    a.Value=atr[atr.find("=")+1:]
                    atr = atr[:atr.find("=")]
                for word in atr.split():
                    if (word==PrivateDefinition.replace(" ","")):
                        a.Private=True
                        atr= atr.replace(word,"")
                    elif (word==PublicDefinition.replace(" ","")):
                        a.Public =True
                        atr= atr.replace(word,"")
                    elif (word==ProtectedDefinition.replace(" ","")):
                        a.Protected=True
                        atr= atr.replace(word,"")
                    elif (word==FinalDefinition.replace(" ","")):
                        a.Final = True
                        atr=atr.replace(word,"")
                    elif (word==StaticDefinition.replace(" ","")):
                        a.Static=True
                        atr= atr.replace(word,"")
                    elif (word in DataTypes):
                        type=word
                        atr= atr.replace(word,"")
                        
                if len(atr.split())==1:
                    a.Name=atr.split()[0]
                elif len(atr.split())==2:
                    type = atr.split()[0]
                    a.Name=atr.split()[1]
                else:
                    raise ValueError("nerozpoznane paramtre v nazve atributu v pocte "+str(len(atr.split()))+" text: ",atr)
                a.Type = type
                Attributes.append(a)
        text = text.replace(line,"")
    return Attributes,text
示例#12
0
    def setUp(self):
        self.attr1 = Attribute()
        self.attr1.name = "one"
        self.attr1.set_words(["one", "two", "three"])
        self.attr1.set_weights([1, 2, 3])
        self.attr1.set_sentiments([1, 1, 1])

        self.attr2 = Attribute()
        self.attr2.name = "two"
        self.attr2.set_words(["four", "five", "six"])
        self.attr2.set_weights([3, 2, 1])
        self.attr2.set_sentiments([-1, 1, -1])

        self.attrs = [self.attr1, self.attr2]
        self.packet = SearchPacket(self.attrs)
示例#13
0
 def setUp(self):
     print 'Variable Attribute test:'
     self.testReader = pyFileReader()
     self.testReader.variables['power'] = fillRandom()
     self.testReader.variables['money'] = fillRandom('int')
     self.testReader.initializeVariableIDs()
     self.unitsAttr = Attribute('unit', '[J/s]')
     self.testReader.variableAttributes['power']['units'] = self.unitsAttr
     self.testReader.variableAttributes['power']['amount'] = Attribute(
         'value', 9001.)
     self.testReader.variableAttributes['money']['units'] = Attribute(
         'unit', 'pesos')
     self.testReader.variableAttributes['money']['amount'] = Attribute(
         'value', 'over 9000!!')
     self.testReader.initializeVariableAttributeIDs()
	def setUp(self):    
		self.attr1 = Attribute()
		self.attr1.name = "one"
		self.attr1.set_words(["one", "two", "three"])
		self.attr1.set_weights_nums([1,2,3])
		self.attr1.set_sentiments_nums([1,1,1])
		
		self.attr2 = Attribute()
		self.attr2.name = "two"
		self.attr2.set_words(["four", "five", "six"])
		self.attr2.set_weights_nums([3,2,1])
		self.attr2.set_sentiments_nums([-1,1,-1])
		
		self.attrs = [self.attr1, self.attr2]
		self.packet = SearchPacket(self.attrs)
 def setUp(self):
     self.words = ['pizza', 'tacos', 'burgers', 'fries']
     weights = [1, 3, 2, 2]
     sentiments = [1, 1, 1, 1]
     attribute = Attribute("Attribute1", 1, self.words, weights, sentiments)
     self.packet = SearchPacket([attribute])
     self.scorer = Scorer(self.packet)
示例#16
0
def dtree_booster(training_set, iterations, attributes):
    num_exs = np.size(training_set, 0)
    w = (1.0 / float(num_exs)) * np.ones((1, num_exs))
    classifiers = {}
    epsilons = {}
    alphas = {}

    # We treat our decision tree as a special case, because we end up
    # sorting our training set so many times (anytime we are finding a contin-
    # uous split). Thus, we tack on the weight as an extra attribute, and
    # add it to the list of attributes
    weight_index = len(attributes) - 1
    # insert column of weights
    training_set = np.insert(training_set, weight_index, w, 1)

    # update attributes dictionary
    attributes['WEIGHTS'] = Attribute('weights', 'WEIGHTS', '0', weight_index)
    attributes['CLASS'].index = weight_index + 1

    for i in xrange(iterations):
        classifiers[i] = get_classifier(training_set, attributes)
        epsilons[i] = calc_epsilon(training_set, classifiers[i])
        alphas[i] = calc_alpha(epsilons[i])
        update_weights(training_set, classifiers[i], alphas[i])
    return classifiers, alphas
 def test110_900_generatename_Unbalanced(self):
     correctError = "generate_name: "
     try:
         Attribute().generate_name(["word"], [1, 2])
         self.fail("Error: no error!")
     except ValueError, e:
         self.assertEqual(correctError, str(e)[:len(correctError)])
 def test110_900_generatename_None(self):
     correctError = "generate_name: "
     try:
         Attribute().generate_name(None, None)
         self.fail("Error: no error!")
     except ValueError, e:
         self.assertEqual(correctError, str(e)[:len(correctError)])
 def test000_001_init_notBlank(self):
     a = Attribute("test", 2, ["test"], [1], [3])
     self.assertEquals(a.name, "test")
     self.assertEquals(a.attrWeight, 2)
     self.assertEquals(a.words, ["test"])
     self.assertEquals(a.weights, [1])
     self.assertEquals(a.sentiments, [3])
示例#20
0
def sumOp(attr: Attribute):
    assert attr.type in [AttrTypes.INT,
                         AttrTypes.FLOAT], "wrong attribute type"
    res = 0
    for i in range(attr.getSize()):
        res += attr[i]
    return res
    def build(self, data=None, attributeSet=None):

        if attributeSet is None:
            # build an attribute set.

            aa = AttributeSet()

            for line in data:
                if line[0] == '@':
                    aa.add(Attribute(line[1:].split('\t')))

            return aa

        else:
            # build an example set.

            ee = ExampleSet()

            for line in data:
                if type(line) == type(str()):
                    if line[0] == '#':
                        ee.add(Example(line[1:], attributeSet))
                #elif type(line) == type(ExampleSet()):
                #	ee.add(line)
                else:
                    ee.add(line)

            return ee
示例#22
0
	def sanitizeAttribute(self, attr):
		if attr.get_name() is None or attr.get_name() == "":
			raise ValueError("sanitizeAttribute: Invalid name for attribute.")
		if attr.get_name() in [a.get_name() for a in self.attributes]:
			raise ValueError("sanitizeAttribute: Duplicate name for an attribute.")
		if attr.get_attr_weight_num() < 1 or attr.get_attr_weight_num() > 3:
			raise ValueError("sanitizeAttribute: Bad attribute weight.")
			
		dirtyWords = attr.get_words()
		dirtyWeights = attr.get_weights()
		dirtySents = attr.get_sentiments()
		
		if dirtyWords is None or dirtyWeights is None or dirtySents is None:
			raise ValueError("sanitizeAttribute: Unassigned values in attribute.")
		elif len(dirtyWords) != len(dirtyWeights) or len(dirtyWords) != len(dirtySents):
			raise ValueError("sanitizeAttribute: list length mismatch.")
			
		cleanWords,	cleanWeights, cleanSents = self.cleanInfoLists(dirtyWords, 
			dirtyWeights, dirtySents)
			
		if len(cleanWords) < 1:
			raise ValueError("sanitizeAttribute: no valid words in attribute.")
			
		return Attribute(attr.get_name(), attr.get_attr_weight_num(),
			cleanWords, cleanWeights, cleanSents)
示例#23
0
    def get_attrib(self, s_attrib):
        """
    TODO : perform all dict gets in the right way. No more check if None
            etc; instead find the recommended access method and replace
    NOTE :
     - attribute is a string, get the particular attribute object
        and pass the symbol's object to it; it will get the prices
        and compute the attribute's values
    """
        existing_attrib = self.attrib_dict.get(s_attrib)

        if existing_attrib is None:
            attrib_root_name = s_attrib[0:s_attrib.index('_')]
            attrib_options = s_attrib[s_attrib.index('_') + 1:]
            new_attrib = Attribute.get_attrib_dict().get(attrib_root_name)()

            if new_attrib is None:
                raise Exception('This attribute hasn\'t been defined yet')

            new_attrib.options_from_str(attrib_options)
            existing_attrib = self.attrib_dict[s_attrib] = new_attrib

        existing_attrib.calculate(symbol=self)

        return existing_attrib
示例#24
0
class AttributeContainer(
        with_metaclass(AttributeNotary, AbstractAttributeContainer)):

    from Attribute import Attribute
    name = Attribute('name')

    def set(self, name, value):
        exec("self.%s = value" % name)
        return

    def get(self, name):
        exec("value = self.%s" % name)
        return value

    def __iter__(self):
        attributes = list(self.__dict__.keys())
        return attributes.__iter__()

    def copy(self):
        ret = self.__class__(self.name)
        for k in self:
            ret.set(k, self.get(k))
        return ret

    def __setattr__(self, name, value):
        if name not in self._attributes:
            raise AttributeError("Unknown attribute %s" % name)
        return object.__setattr__(self, name, value)

        pass
示例#25
0
  def get_attrib(self, s_attrib):
    """
    TODO : perform all dict gets in the right way. No more check if None
            etc; instead find the recommended access method and replace
    NOTE :
     - attribute is a string, get the particular attribute object
        and pass the symbol's object to it; it will get the prices
        and compute the attribute's values
    """
    existing_attrib = self.attrib_dict.get(s_attrib)

    if existing_attrib is None:
      attrib_root_name  = s_attrib[0:s_attrib.index('_')]
      attrib_options    = s_attrib[s_attrib.index('_')+1:]
      new_attrib        = Attribute.get_attrib_dict().get(attrib_root_name)()

      if new_attrib is None:
        raise Exception('This attribute hasn\'t been defined yet')

      new_attrib.options_from_str(attrib_options)
      existing_attrib = self.attrib_dict[s_attrib] = new_attrib

    existing_attrib.calculate(symbol=self)

    return existing_attrib
示例#26
0
 def test000_902_sanitize_badWeight(self):
     correctError = "sanitizeAttribute: "
     try:
         test = Attribute("test", 0, ["one", "two"], [1, 1], [1, 1])
         self.packet.sanitizeAttribute(test)
         self.fail("Error: no error!")
     except ValueError, e:
         self.assertEqual(correctError, str(e)[:len(correctError)])
示例#27
0
 def test000_903_sanitize_noWords(self):
     correctError = "sanitizeAttribute: "
     try:
         test = Attribute("one", 1, None, [1, 1], [1, 1])
         self.packet.sanitizeAttribute(test)
         self.fail("Error: no error!")
     except ValueError, e:
         self.assertEqual(correctError, str(e)[:len(correctError)])
示例#28
0
 def createAttribute(self, attributeName : str = None):
     if attributeName not in self._names:
         print("No AttributeType named " + attributeName + " exists in the pool")
         return None
     else:
         currentType = self._names[attributeName]
         self._pool[currentType].append(Attribute(currentType))
         return self._pool[currentType][-1]
示例#29
0
 def test000_905_sanitize_NoSents(self):
     correctError = "sanitizeAttribute: "
     try:
         test = Attribute("one", 1, ["one", "two"], [1, 1], None)
         self.packet.sanitizeAttribute(test)
         self.fail("Error: no error!")
     except ValueError, e:
         self.assertEqual(correctError, str(e)[:len(correctError)])
 def setUpClass(self):
     self.interface = SearchInterface()
     attribute = Attribute("Test Attribute",
                           attrWeight=1,
                           words=['pizza'],
                           weights=[3],
                           sentiments=[1])
     self.attributes = [attribute]
     self.que = Queue.Queue()
示例#31
0
 def setUpClass(self):
     words = ['pizza', 'tacos', 'burgers', 'fries']
     weights = [1, 3, 2, 2]
     sentiments = [1, 1, 1, 1]
     self.args = {'location': None, 'since': None, 'until': None}
     attribute = Attribute("Attribute1", 1, words, weights, sentiments)
     attributes = [attribute]
     search_packet = SearchPacket(attributes)
     self.scorer = Scorer(search_packet)
 def test100_002_score_mixed(self):
     weights = [1, 3, 2, 2]
     sentiments = [0, 0, 0, 0]
     attribute = Attribute("Attribute1", 1, self.words, weights, sentiments)
     packet = SearchPacket([attribute])
     score = Scorer(packet)
     text = "I hate tacos and love fries."
     #tacos has weight 3, fries 2
     self.assertEquals(score.score(text), [5, 0, 0, 0, 0])
示例#33
0
 def setGlobalAttributes(self):
     if self.file_tree.has_key('global_attributes'):
         for k, v in self.file_tree['global_attributes'].items():
             self.globalAttributes[str(k)] = Attribute(str(k), v)
     else:
         error_str = "Could not find 'global_attributes' in asdf file"
         if self.debug: print error_str
         raise NameError(error_str)
     self.initializeGlobalAttributeIDs()  #after all global attributes set
示例#34
0
    def getFunctionalDependencies(self, relation):
        FDs=[]
        for dependencies in relation.iter('dependencies'):
            for fd in dependencies:
                fdObj=FunctionalDependency.FunctionalDependency()

                for lhs in fd.iter('lhs'):
                    for attribute in lhs:
                        attribute_object = Attribute(attribute.text)
                        fdObj.leftHandSide.append(attribute_object)

                for rhs in fd.iter('rhs'):
                    for attribute in rhs:
                        attribute_object = Attribute(attribute.text)
                        fdObj.rightHandSide.append(attribute_object)

                FDs.append(fdObj)
        return FDs
	def setUpClass(self):
		words = ['pizza', 'tacos', 'burgers', 'fries']
		weights = [1, 3, 2, 2]
		sentiments = [1, 1, 1, 1]
		self.query = "pizza OR tacos OR burgers OR fries"
		attribute = Attribute("Attribute1", 1, words, weights, sentiments)
		attributes = [attribute]
		search_packet = SearchPacket(attributes)
		self.scorer = Scorer(search_packet)

		self.db = dbFacade()
示例#36
0
    def parse(self, inStream):
        newStream = inStream.split( )
        newAttribute = Attribute.factory(newStream[2])
        newAttribute.setName(newStream[1])

        for num in range(2, len(newStream)):
            if type(newAttribute) == NominalAttribute:
                newAttribute.addValue(newStream[num])
            else:
                pass
        self.add(newAttribute)
        self.setClassIndex(self.getSize()-1)
示例#37
0
    def add_attribute(self,attribute):
        attr_varname     = attribute.getAttribute('varname')
        attr_name        = attribute.getAttribute('name')
        attr_type        = attribute.getAttribute('type')
        attr_description = attribute.getAttribute('description')
        attr_label       = attribute.getAttribute('label')
        attr_fixed       = attribute.getAttribute('fixed')

        allowed_values = []
        allowed_default = ""
        if attr_fixed == "choice":
            for allowed in attribute.getElementsByTagName('allowed'):
                allowed_value = allowed.getAttribute("value")
                allowed_label = allowed.getAttribute("label")
                if allowed.getAttribute("default") == "default":
                    allowed_default = allowed_value
                allowed_values.append((allowed_value,allowed_label))
            if allowed_default == "":
                allowed_default = allowed_values[0][0]
        
        typefunc = str
        if (attr_type == "float"):
            typefunc = float
        elif (attr_type == "int" or attr_type == "integer"):
            typefunc = int

        attr_default = typefunc(attribute.getAttribute('default'))
        if attr_fixed == "choice":
            attr_default = allowed_default
            
        attr_min     = typefunc(attribute.getAttribute('min'))
        attr_max     = typefunc(attribute.getAttribute('max'))
        
        attr         = Attribute(attr_name,attr_varname,attr_type,attr_default,
                                 attr_min,attr_max,attr_label,attr_description,
                                 allowed_values)
        attr.order = self.attr_idx
        self.attr_idx += 1
        self.attributes[attr_varname] = attr
        setattr(self,attr_varname,attr.get())
示例#38
0
 def parse(self, parserContext):
     assembly = Assembly()
     
     token = parserContext.get_next_token()
     if token != '.assembly':
         raise ParseException('Expected .assembly, found ' . token)
     token = parserContext.get_next_token()
     if token == 'extern':
         assembly.extern = True
         token = parserContext.get_next_token()
     
     assembly.name = token
             
     while True:
         token = parserContext.get_next_token()
       
         if token == '.ver':
             assembly.version = parserContext.get_next_token()
         elif token == '.hash':
             if parserContext.get_next_token() != 'algorithm':
                 raise ParseException('Expected token "algorithm"')
             assembly.hashAlgorithm = int(parserContext.get_next_token(), 16)
         elif token == '.custom':
             if parserContext.get_next_token() != 'instance':
                 raise ParseException('Expected token "instance"')
             if parserContext.get_next_token() != 'void':
                 raise ParseException('Expected token "void"')
             attribute = Attribute()
             attribute.name = parserContext.get_next_token() + '(' + parserContext.get_next_token() + ')'
             assembly.customAttributes.append(attribute)
         elif token == '{':
             pass
         elif token == '}':
             break
     #fixme public key token
     return assembly
示例#39
0
 def nominalToBinary(self):
     newDataSet = DataSet()
     newAttributes = Attributes()
     for items in self.attributes.attributes:
         if len(items.domain) > 2:
             binaryDomain = bin(len(items.domain))
             for index, char in enumerate(str(binaryDomain)):
                 if index >= len(str(binaryDomain))-2:
                     pass
                 else:
                     newAttribute = Attribute.factory("nominal")
                     newAttribute.setName(items.name + str(index))
                     newAttribute.addValue(str(0))
                     newAttribute.addValue(str(1))
                     newAttributes.add(newAttribute)
         else:
             newAttributes.add(items)
     newDataSet.setAttributes(newAttributes)
     newDataSet.attributes.setClassIndex(len(newAttributes.attributes)-1)
     #ADJUST EXAMPLES NEXT
     return newDataSet
class test_SearchPacket(unittest.TestCase):
	def setUp(self):    
		self.attr1 = Attribute()
		self.attr1.name = "one"
		self.attr1.set_words(["one", "two", "three"])
		self.attr1.set_weights_nums([1,2,3])
		self.attr1.set_sentiments_nums([1,1,1])
		
		self.attr2 = Attribute()
		self.attr2.name = "two"
		self.attr2.set_words(["four", "five", "six"])
		self.attr2.set_weights_nums([3,2,1])
		self.attr2.set_sentiments_nums([-1,1,-1])
		
		self.attrs = [self.attr1, self.attr2]
		self.packet = SearchPacket(self.attrs)
		
#sanitize
	#pass
	def test000_000_sanitizeAttribute(self):
		test = Attribute("test", 1, ["one", "two"], [1,1], [1,1])
		sanitize = self.packet.sanitizeAttribute(test)
		self.assertEquals(sanitize, test)
		
	def test000_001_sanitize_oneBadWord(self):
		test = Attribute("test", 1, ["one", ""], [1,1], [1,1])
		correct = Attribute("test", 1, ["one"], [1], [1])
		self.assertEquals(self.packet.sanitizeAttribute(test), correct)
		
	def test000_002_sanitize_oneBadWeight(self):
		test = Attribute("test", 1, ["one", "two"], [1,0], [1,1])
		correct = Attribute("test", 1, ["one"], [1], [1])
		self.assertEquals(self.packet.sanitizeAttribute(test), correct)
		
	def test000_003_sanitize_oneBadSent(self):
		test = Attribute("test", 1, ["one", "two", "three"], [1,1, 1], [1, 0, 2])
		correct = Attribute("test", 1, ["one", "two"], [1,1], [1,0])
		self.assertEquals(self.packet.sanitizeAttribute(test), correct)
		
	def test000_004_sanitize_oneDupWord(self):
		test = Attribute("test", 1, ["one", "one"], [1,1], [1,1])
		correct = Attribute("test", 1, ["one"], [1], [1])
		self.assertEquals(self.packet.sanitizeAttribute(test), correct)
		
	#fail
	def test000_900_sanitize_badName(self):
		correctError = "sanitizeAttribute: "
		try:
			test = Attribute("", 1, ["one", "two"], [1,1], [1,1])
			self.packet.sanitizeAttribute(test)
			self.fail("Error: no error!")
		except ValueError, e:
			self.assertEqual(correctError, str(e)[:len(correctError)])
		except Exception, e:
			self.fail(str(e))
示例#41
0
    def weather(self):
        # Create Weather Class as a container to what will happen during time
        # THIS NEEDS TO BE SET TO PRACTICAL DEGENERATIVE PARAMETERS
        time = Weather()
        # Add Attributes this Weather will help
        morale = Attribute("Morale")
        morale.setValue(-1)
        time.addAttribute(morale)

        hygiene = Attribute("Hygiene")
        hygiene.setValue(-1)
        time.addAttribute(hygiene)

        hunger = Attribute("Hunger")
        hunger.setValue(-1)
        time.addAttribute(hunger)

        fatigue = Attribute("Fatigue")
        fatigue.setValue(-1)
        time.addAttribute(fatigue)

        health = Attribute("Health")
        health.setValue(-100)
        time.addAttribute(health)

        # Post as a Cluster Weather Event
        ev = Events.ClusterWeatherEvent(0, time)
        self.mediator.post(ev)
	def test110_001_generatename_blank(self):
		words = []
		weights = []
		test = Attribute()
		self.assertEquals(test.generate_name(words, weights), "")
class test_Attribute(unittest.TestCase):
	def setUp(self):
		self.test = Attribute("test", 1, ["tests"], [1], [-1])

#__init__
	#pass
	def test000_000_init_blank(self):
		a = Attribute()
		correct = Attribute(name = "Attribute", attrWeight = 1,
			words = None, weights = None, sentiments = None)
		self.assertEquals(a, correct)
		
	def test000_001_init_notBlank(self):
		a = Attribute("test", 2, ["test"], [1], [3])
		self.assertEquals(a.name, "test")
		self.assertEquals(a.attrWeight, 2)
		self.assertEquals(a.words, ["test"])
		self.assertEquals(a.weights, [1])
		self.assertEquals(a.sentiments, [3])
		
#__eq__
	def test100_000_eq(self):
		one = Attribute("test", 2, ["test"], [1], [1])
		two = Attribute("test", 2, ["test"], [1], [1])
		self.assertEquals(one, two)
		
	def test100_001_eq_noteq_name(self):
		one = Attribute("test", 2, ["test"], [1], [1])
		two = Attribute("test1", 2, ["test"], [1], [1])
		self.assertNotEquals(one, two)
		
	def test100_002_eq_noteq_weight(self):
		one = Attribute("test", 2, ["test"], [1], [1])
		two = Attribute("test", 3, ["test"], [1], [1])
		self.assertNotEquals(one, two)
		
	def test100_003_eq_noteq_words(self):
		one = Attribute("test", 2, ["test"], [1], [1])
		two = Attribute("test", 2, ["test", "test2"], [1], [1])
		self.assertNotEquals(one, two)
		
	def test100_004_eq_noteq_weights(self):
		one = Attribute("test", 2, ["test"], [1], [1])
		two = Attribute("test", 2, ["test"], [1,2], [1])
		self.assertNotEquals(one, two)
		
	def test100_005_eq_noteq_sent(self):
		one = Attribute("test", 2, ["test"], [1], [3])
		two = Attribute("test", 2, ["test"], [1], [1, -1])
		self.assertNotEquals(one, two)
		
#set_name
	def test200_000_setname(self):
		self.test.set_name("realname")
		correct = Attribute("realname", 1, ["tests"], [1], [-1])
		self.assertEquals(self.test, correct)
		
	def test200_001_setname_Attribute(self):
		self.test.set_name("Attribute")
		correct = Attribute("tests", 1, ["tests"], [1], [-1])
		self.assertEquals(self.test, correct)
		
	def test200_002_setname_withNone(self):
		test = Attribute("name", 1, ["test"])
		test.set_name("realname")
		correct = Attribute("realname", 1, ["test"])
		self.assertEquals(test, correct)
		
#set_attr_weight
	def test300_000_setattrweight(self):
		self.test.set_attr_weight(3)
		correct = Attribute("test", 1, ["tests"], [1], [-1])
		self.assertEquals(self.test, correct)
		
#set_words
	def test400_000_setwords(self):
		self.test.set_words(["real", "words"])
		correct = Attribute("test",1, ["real", "words"], [1], [-1])
		self.assertEquals(self.test, correct)
		
#set_weight
	def test500_000_setweights(self):
		self.test.set_weights(["High", "Low", "Blah", "Medium"])
		correct = Attribute("test", 1, ["tests"], [3,1,1,2], [-1])
		self.assertEquals(self.test, correct)
		
	def test500_001_setweights_blank(self):
		self.test.set_weights([])
		correct = Attribute("test", 1, ["tests"], [], [-1])
		self.assertEquals(self.test, correct)
		
	def test500_900_setweights_notstring(self):
		correctError = "set_weights: "
		try:
			self.test.set_weights([1])
			self.fail("Error: no error!")
		except ValueError, e:
			self.assertEqual(correctError, str(e)[:len(correctError)])
		except Exception, e:
			self.fail(str(e))
	def test900_006_getsize_none(self):
		a = Attribute()
		self.assertEquals(a.get_size(), 0)
	def setUp(self):
		self.test = Attribute("test", 1, ["tests"], [1], [-1])
	def test200_002_setname_withNone(self):
		test = Attribute("name", 1, ["test"])
		test.set_name("realname")
		correct = Attribute("realname", 1, ["test"])
		self.assertEquals(test, correct)
	def test900_012_getweights_none(self):
		a = Attribute()
		self.assertIsNone(a.get_words())
	def test110_000_generatename(self):
		words = ["not this", "not this", "this", "not this"]
		weights = [1,2,3,3]
		test = Attribute()
		self.assertEquals(test.generate_name(words, weights), "this")
	def test900_014_getsentiments_none(self):
		a = Attribute()
		self.assertIsNone(a.get_sentiments())
示例#50
0
文件: Class.py 项目: Jazzuell/parser
 def ConvertParameterToAttribute(self,param):
     atr = Attribute()
     atr.Name=param.Name
     atr.Type = param.Type
     self.Attributes.append(atr)