コード例 #1
0
    def addAttribute(self, attr: Attribute):
        '''
        attr: Attribute
        '''
        # 判断要添加的attribute是否已经存在
        attrname = attr.name
        assert attrname not in self.attributes.keys(
        ), "Attribute already exists"

        # 如果attr已经有value
        if attr.getSize() > 0:
            # 如果有其它attr
            if len(self.attributes.keys()) > 0:
                if attr.getSize() != self.rowsize:
                    raise Exception(
                        "Attribute size does not match existed attributes")
                else:
                    self.attributes[attrname] = attr
            # 如果没有其它attr
            else:
                self.attributes[attrname] = attr
                self.rowsize = attr.getSize()
                return
        # 如果attr不包含value
        else:
            # 如果有其它attr并且其它attr带有value
            if len(self.attributes.keys()) > 0 and self.rowsize > 0:
                #用None来填充
                for i in range(self.rowsize):
                    attr.addValue(None)
                self.attributes[attrname] = attr
                return
            # 如果没有其它attr
            else:
                self.attributes[attrname] = attr
コード例 #2
0
 def readFile(self, path):
     lines = [line.rstrip('\n') for line in open(path)]
     for line in lines:
         tokens = line.split(' ')
         if len(tokens) < 3:
             raise Exception(
                 "There are not enough information about an certain attribute"
             )
         if tokens[0] != "@ATTRIBUTE":
             raise Exception(
                 "First token in each line must be <@ATTRIBUTE>")
         name = tokens[1]
         last_token = tokens[len(tokens) - 1]
         if tokens[2] == "NUMERIC":
             newAttribute = Attribute.Numeric(name)
         elif tokens[2][0] == '{' and last_token[len(last_token) -
                                                 1] == '}':
             categoriesLine = line.split('{')[1].split('}')[0]
             categories = []
             for x in categoriesLine.split(','):
                 categories.append(Attribute.Value(x))
             if len(categories) < 2:
                 raise Exception(
                     "Each categorical attribute must have at least 2 categories"
                 )
             newAttribute = Attribute.Category(name, categories)
         else:
             raise Exception("Invalid structure")
         if newAttribute.name != "class":
             self.attributes.append(newAttribute)
         else:
             if self.classAttribute is not None:
                 raise Exception(
                     "There can not be more than 1 class attribute")
             self.classAttribute = newAttribute
コード例 #3
0
ファイル: storage.py プロジェクト: jwnwilson/nw_maya
def storeStringArray(node, attr, data):
    """
        Store string on node
    """
    if dataExists(node, attr):
            cmds.setAttr( (node+"." + attr), type = 'stringArray', *([len(data)] + data) )
    else:
       Attribute.addStringArrayAttribute(node,attr,data)
コード例 #4
0
ファイル: storage.py プロジェクト: jwnwilson/nw_maya
def storeString(node, attr, data):
    """
        Store string on node
    """
    if dataExists(node, attr):
        cmds.setAttr((node+"." + attr), data, type="string")
    else:
        Attribute.addStringAttribute(node,attr,data)
コード例 #5
0
ファイル: Parser.py プロジェクト: visavis2k/accords-platform
    def __init__(self, files):
        '''
        Constructor
            @param files: list of files to parse
        '''
        self.files = files
        self.cats = Category.Categories()
        self.models = Model.Models()

        # Add the standard categories from OCCI Core
        self._built_in_model = Model.Model("core", "OCCI Core categories",
                                           "1.0,0")
        self.models.add(self._built_in_model)
        # Entity
        entity = Category.Category("entity",
                                   "http://schemas.ogf.org/occi/core#",
                                   "/entity/", None, "kind",
                                   self._built_in_model)
        entity.addattr(
            Attribute.Attribute("id", "string", "true", "true", None, "true"))
        entity.addattr(
            Attribute.Attribute("title", "string", "false", "false", None,
                                "false"))
        self.cats.add(entity)

        # Resource
        resource = Category.Category(
            "resource", "http://schemas.ogf.org/occi/core#", "/resource/",
            "http://schemas.ogf.org/occi/core#entity", "kind",
            self._built_in_model)
        resource.addattr(
            Attribute.Attribute("summary", "string", "false", "false", None,
                                "false"))
        self.cats.add(resource)

        # Link
        link = Category.Category("link", "http://schemas.ogf.org/occi/core#",
                                 "/link/",
                                 "http://schemas.ogf.org/occi/core#entity",
                                 "link", self._built_in_model)
        link.addattr(
            Attribute.Attribute("source", "string", "true", "false", None,
                                "false"))
        link.addattr(
            Attribute.Attribute("target", "string", "true", "false", None,
                                "false"))
        self.cats.add(link)
        self.parsers = ParserCollection()
コード例 #6
0
ファイル: Parser.py プロジェクト: visavis2k/accords-platform
    def _addattrs(self, category, cat):
        '''
        Parse and add all attributes to a category
            @param category: a collection of XML Elements
            @param cat: the Category to add the collections to
        '''
        # Parse attributes
        for attr in category.findall("attributes/attribute"):
            name = attr.get("name")
            if name == None:
                logging.warn("Category" + cat.term + " - invalid attribute")
                continue
            logging.info("Category " + cat.term + " attribute " + name)
            try:
                cat.addattr(
                    Attribute.Attribute(name, attr.get("type"),
                                        attr.get("required"),
                                        attr.get("immutable"),
                                        attr.get("validation"),
                                        attr.get("index"), attr.get("default"),
                                        attr.get("units"),
                                        attr.get("legacytype"),
                                        attr.get("scope"), attr.get("script")))
            except:
                logging.error("Category " + cat.term +
                              "Problem processing attribute " + id)
                logging.error(sys.exc_info())

        # Parse instances
        colls = category.findall("attributes/instance")
        self._addcoll(colls, cat)

        # Parse collections
        colls = category.findall("attributes/collection")
        self._addcoll(colls, cat)
コード例 #7
0
ファイル: Tank.py プロジェクト: GreenKing/Tank_War
 def __init__(self, location, direction):
     pygame.sprite.Sprite.__init__(self)
     self.direction = direction
     self.set_image(self.direction)
     self.rect = self.image.get_rect()
     self.set_location(location)
     self.speed = 80
     self.mcontroller = MotionController(self, Vector2(StepX, StepY))
     self.att = Attribute(self)
     self.name = "TANK"
コード例 #8
0
ファイル: Archetype.py プロジェクト: hippiejesus/EntityWeb
 def __init__(self, identifier, args):
     self.identifier = identifier
     self.descriptors = Descriptor.descriptors()
     self.attributes = Attribute.attributes()
     self.stats = Stat.stats()
     for a in args:
         as1 = a.split(':')
         category = as1[0]
         as2 = as1[1].split('=')
         command = as2[0]
         args = as2[1]
         self.apply(category, command, args)
コード例 #9
0
ファイル: file.py プロジェクト: jwnwilson/nw_maya
def saveBlueprintModuleData(bluePrintFilePath, modules):
    """
        Saves blueprint module names type and parents
    """
    writeData = ""
    for module in modules:
        print module
        container = module + "_CNT"
        writeData += module + " " + Attribute.getString(container, "type") + "\n"

    FILE = open(bluePrintFilePath, "wb")
    blueprintData = FILE.write(writeData)
    FILE.close()
コード例 #10
0
    def __init__(self, string, know_final_class):
        self.final_class = None
        self.attributeList = []

        #replace all of the non attribute characters in the string read in from
        #the .txt data file
        string = string.replace("\n", "")
        string = string.replace(",", "")

        #if we know the final classification (the first character on the string)
        #remove it and store in the final_class data variable
        if know_final_class:
            self.final_class = string[0]
            l = list(string)
            l[0] = ""
            string = "".join(l)
            for char in string:
                #make attribues and add them to the entities attributeList
                self.attributeList.append(Attribute(char))
        else:
            #make attributes from string and add them to the entities attributeList
            for char in string:
                self.attributeList.append(Attribute(char))
コード例 #11
0
ファイル: Blueprint.py プロジェクト: jwnwilson/nw_rig
def createBlueprinter( name, args ):
        'Creates a default blueprinters'
        ret = {}
        sctl = []
        jnt = ""
        functArgs = {"shape":"cube", "size":1, "t":0, "r":0, "s":0}
        functArgs =  dict(functArgs.items() + args.items())
        
        #create Control
        if(functArgs["shape"] == "cube"):
                sctl = Control.cubeCtl( name, functArgs )
        elif(functArgs["shape"] == "sphere"):
                sctl = Control.sphereCtl( name, functArgs )
        elif(functArgs["shape"] == "arrow"):
                sctl = Control.arrowCtl( name , functArgs )
        elif(functArgs["shape"] == "locator"):
                sctl = Control.locatorCtl( name , functArgs )
        else:
                print "Shape not supported...\n"
                return 0
                
        #lock hide unwanted Attribute
        if functArgs["t"] == 1:
            Attribute.lockHide(sctl[0], {"t":1, "h":1, "l":1})
        if functArgs["r"] == 1:
            Attribute.lockHide(sctl[0], {"r":1, "h":1, "l":1})
        if functArgs["s"] == 1:
            Attribute.lockHide(sctl[0], {"s":1, "h":1, "l":1})
            
        #add blueprinter joint
        jnt = cmds.joint( n = ( name + "_SJNT" ), p= (0, 0, 0 ) )
        Constraint.constrain(sctl[0], jnt, args={ "t":1, "mo":0, "name":(name)} )
        #matrixConstraint(sctl[0] , jnt, 0, {})
        #template(jnt)
        
        #parent to root
        cmds.parent(jnt,sctl[0])
        #cmds.parent(ret["sctl"][1],rootGrp)
        
        #rename suffix
        newName = sctl[0].replace("_CTL","_SCTL")
        cmds.rename(sctl[0],newName)
        sctl[0] = newName
        newName = sctl[1].replace("Ctl_GRP","Sctl_GRP")
        cmds.rename(sctl[1],newName)
        sctl[1] = newName
        
        #create blueprinter variable
        """for blueprinter in sctl:
            storeString(blueprinter, "blueprinter", "")
        storeString(jnt, "sjoint", "")"""
        
        ret["sctl"] = sctl
        ret["jnt"] = jnt
        
        return ret
コード例 #12
0
class IVersionFolder(Interface):
    """
    Interface for version container in the repository
    """

    latest = Attribute('latest', 'The latest revision of this object.  Must implement the IVersionedObject interface')
    
    def url():
        """Return the URL to access the last version of the object"""

    def createVersion(object, submitter, submitlog):
        """Commit a new version of the object to the repository

           object      : the new object
           submitter   : the user creating the new version
           submitlog   : a string describing the changes
        """

    def getHistory():
        """Return the version history of the object as a list.  Each item in the list will implement the **** interface"""
コード例 #13
0
ファイル: file.py プロジェクト: jwnwilson/nw_maya
def loadTransforms(filePath):
    """
        Loads Transforms from file
    """
    if not os.path.isfile(filePath):
        print ("No data found from : " + filePath)
        return
    FILE = open(filePath, "rU")

    for line in FILE:
        blueprintDataLine = line.split()
        blueprintObject = blueprintDataLine[0]
        translate = [float(blueprintDataLine[1]), float(blueprintDataLine[2]), float(blueprintDataLine[3])]
        rotate = [float(blueprintDataLine[4]), float(blueprintDataLine[5]), float(blueprintDataLine[6])]
        scale = [float(blueprintDataLine[7]), float(blueprintDataLine[8]), float(blueprintDataLine[9])]
        if cmds.objExists(blueprintObject):
            Attribute.checkSetCompoundAttr((blueprintObject + ".t"), translate)
            Attribute.checkSetCompoundAttr((blueprintObject + ".r"), rotate)
            Attribute.checkSetCompoundAttr((blueprintObject + ".s"), scale)
    FILE.close()
    print ("Loaded transfrom data from : " + filePath)
コード例 #14
0
ファイル: Blueprint.py プロジェクト: jwnwilson/nw_rig
def createAxisContols(name, args):
        """
            creates a Control with sub Controls limited to move only in one axis each
        """
        ret = {}
        X=[]
        Y=[]
        Z=[]
        functArgs = {"axis":"xyz", "size":1}
        functArgs =  dict(functArgs.items() + args.items())
        child=None
        
        xName = String.removeSuffix(name) + "X"
        yName = String.removeSuffix(name) + "Y"
        zName = String.removeSuffix(name) + "Z"
        
        topGrp = cmds.group(name=(name+"_GRP"),em=True)
        ctlGrp = cmds.group(name=(name+"Ctl_GRP"),em=True)
        
        if "x" in functArgs["axis"]:
            X = Control.arrowCtl( xName, functArgs )
            Attribute.lockHide(X[0], {"all":1, "h":1, "l":1})
            Attribute.setColour(X[0], "red")
            cmds.setAttr(( X[0] + ".tx"), lock=False, cb = True , k = True )
            child = Transform.getShape(X[0])
            cmds.rotate(0,-90,0, (child+".cv[0:7]"))
        if "y" in functArgs["axis"]:
            Y = Control.arrowCtl( yName, functArgs )
            Attribute.lockHide(Y[0], {"all":1, "h":1, "l":1})
            Attribute.setColour(Y[0], "green")
            cmds.setAttr(( Y[0] + ".ty"), lock=False, cb = True , k = True )
            child = Transform.getShape(Y[0])
            cmds.rotate(90,0,0, (child+".cv[0:7]"))
        if "z" in functArgs["axis"]:
            Z = Control.arrowCtl( zName, functArgs )
            Attribute.lockHide(Z[0], {"all":1, "h":1, "l":1})
            Attribute.setColour(Z[0], "blue")
            cmds.setAttr(( Z[0] + ".tz"), lock=False, cb = True , k = True )
            child = Transform.getShape(Z[0])
            cmds.rotate(180,0,0, (child+".cv[0:7]"))        
            
        #connect Control to group to negate movement
        XNeg = cmds.createNode("multDoubleLinear", n=(name+"X_PMA"))
        cmds.setAttr((XNeg + ".input2"), -1)
        YNeg = cmds.createNode("multDoubleLinear", n=(name+"Y_PMA"))
        cmds.setAttr((YNeg + ".input2"), -1)
        ZNeg = cmds.createNode("multDoubleLinear", n=(name+"Z_PMA"))
        cmds.setAttr((ZNeg + ".input2"), -1)
        
        cmds.connectAttr((X[0]+".tx"),(XNeg+".input1"), f=True)
        cmds.connectAttr((Y[0]+".ty"),(YNeg+".input1"), f=True)
        cmds.connectAttr((Z[0]+".tz"),(ZNeg+".input1"), f=True)
        
        cmds.connectAttr((XNeg+".output"),(X[1]+".tx"), f=True)
        cmds.connectAttr((YNeg+".output"),(Y[1]+".ty"), f=True)
        cmds.connectAttr((ZNeg+".output"),(Z[1]+".tz"), f=True)
        
        #connect Control to ctls to top grp
        cmds.connectAttr((X[0]+".tx"),(ctlGrp+".tx"), f=True)
        cmds.connectAttr((Y[0]+".ty"),(ctlGrp+".ty"), f=True)
        cmds.connectAttr((Z[0]+".tz"),(ctlGrp+".tz"), f=True)
        
        cmds.parent(ctlGrp, topGrp)
        
        if "x" in functArgs["axis"]:
            cmds.parent(X[1], ctlGrp)
        if "y" in functArgs["axis"]:
            cmds.parent(Y[1], ctlGrp)
        if "z" in functArgs["axis"]:
            cmds.parent(Z[1], ctlGrp)
            
        ret["xctl"] = X
        ret["yctl"] = Y
        ret["zctl"] = Z  
        ret["grp"] = [topGrp, ctlGrp]
        return ret
コード例 #15
0
    # d1.addTable(t2)

    # statement = "t1, t2 on t1.a1 = t2.a3"
    # p = parseJoins([statement])
    # print(d1)
    # print(d1.join(p))
    # join_table = d1.join(p)
    # select_table = join_table.select("*", [[['a1',condition('inside', (1, 2))]]])
    # print(select_table)

    # d1.addForeignKey("t1", "a1", "t2", "a3")
    # d1.addForeignKey("t2", "a3", "t1", "a2")
    # print(d1.showForeignKeys())

    # ===============================test join time===================================
    a1 = Attribute(name="a1", type=AttrTypes.INT, key=[AttrKeys.NOT_NULL])
    for i in range(1, 1001):
        a1.addValue(i)
    a2 = Attribute(name="a2", type=AttrTypes.INT, key=[AttrKeys.NOT_NULL])
    for i in range(1, 1001):
        a2.addValue(1)
    a3 = Attribute(name="a3", type=AttrTypes.INT, key=[AttrKeys.PRIMARY])
    for i in range(1, 10001):
        a3.addValue(i)
    a4 = Attribute(name="a4", type=AttrTypes.INT, key=[AttrKeys.NOT_NULL])
    for i in range(1, 10001):
        a4.addValue(1)

    t1 = Table('t1', [a1, a2])
    t2 = Table('t2', [a3, a4])
コード例 #16
0
    def readSchemeFile(self, schemeFile):

        #Variable to hold each read line from the file
        fileLine = ""

        try:

            #The number of attributes read from the scheme file
            numSchemeAttributes = 0

            #Variables to hold information associated with each attribute
            attributeName = ""
            attributeNumValues = ""
            attributeValues = ""

            #Read the entire scheme file
            with open(schemeFile, "r") as fp:

                #Read the initial line as the number of attributes in the scheme file
                fileLine = fp.readline()
                numSchemeAttributes = int(fileLine)
                fileLine = fp.readline()

                #Read in all of the non-function value attributes
                for i in range(numSchemeAttributes - 1):
                    attributeName = fp.readline()
                    attributeName = attributeName.strip()
                    attributeNumValues = fp.readline()
                    attributeNumValues = attributeNumValues.strip()
                    attributeValues = fp.readline()
                    attributeValues = attributeValues.strip()
                    fp.readline()

                    #Attempt to create a new attribute
                    readAttribute = Attribute(attributeName,
                                              int(attributeNumValues),
                                              attributeValues)

                    #If the attribute was invalid, inform the user and exit the system
                    if (readAttribute.getValues() == None):
                        print(
                            "One or more of the attributes in the SchemeFile was invalid.\nPlease ensure all of the attributes specified are present."
                        )
                        fp.close()
                        sys.exit(1)

                    #Add the attribute to the list of read attributes
                    self.attributes.append(readAttribute)

                #Read in the function value information
                attributeName = fp.readline()
                attributeName = attributeName.strip()
                attributeNumValues = fp.readline()
                attributeNumValues = attributeNumValues.strip()
                attributeValues = fp.readline()
                attributeValues = attributeValues.strip()

                #Create the function value attribute and add it to the list of attributes
                functionAttribute = Attribute(attributeName,
                                              int(attributeNumValues),
                                              attributeValues)
                self.functionValue = functionAttribute

                fp.close()

        #Inform the user if the file couldn't be found
        except FileNotFoundError:
            print("The scheme file \'" + schemeFile + "\' could not be found.")
            sys.exit(1)

        #Inform the user if an error occurred while reading the file
        except IOError:
            print("An error occurred while reading the scheme file \'" +
                  schemeFile + "\'")
            sys.exit(1)

        #Inform the user if an error occurred while reading the file
        except ValueError:
            print("An error occurred while reading the scheme file \'" +
                  schemeFile + "\'")
            sys.exit(1)
コード例 #17
0
ファイル: JRIDataSet.py プロジェクト: krismz/Delv
 def __init__(self, r_engine, name, attr_type, color_map, data_range):
   Attribute.__init__(self, name, attr_type, color_map, data_range)
   self.engine = r_engine
コード例 #18
0
ファイル: Tank.py プロジェクト: GreenKing/Tank_War
class Tank(pygame.sprite.Sprite):
    images = {}
    delta = [Vector2(0, 0), Vector2(0.5, 0), Vector2(0, 0.375), Vector2(0.5, 1), Vector2(1, 0.375)]

    def __init__(self, location, direction):
        pygame.sprite.Sprite.__init__(self)
        self.direction = direction
        self.set_image(self.direction)
        self.rect = self.image.get_rect()
        self.set_location(location)
        self.speed = 80
        self.mcontroller = MotionController(self, Vector2(StepX, StepY))
        self.att = Attribute(self)
        self.name = "TANK"

    def shoot(self, shoot):
        if len(self.bullets.sprites()) > 0:
            return
        if shoot == 1:
            x, y, w, h = self.rect
            # print x,y,w,h
            pos = self.location + Tank.delta[self.direction] * Vector2(w, h)
            bullet = SBullet(self, pos, self.direction)
            bullet.add(self.bullets_group)
            bullet.add(self.bullets)
            bullet.shoot()
            SoundPlayer.play_shoot_sound()

    def set_image(self, direction):
        self.image = Tank.images[direction]

    def set_direction(self, direction):
        self.direction = direction
        self.set_image(self.direction)

    def set_location(self, location):
        self.rect.topleft = self.location = location

    def set_bullets(self, bullets):
        self.bullets_group = bullets
        self.bullets = pygame.sprite.RenderUpdates()

    def step_back(self):
        self.set_location(self.mcontroller.step_back())

    def moved(self):
        dx, dy = self.location - self.mcontroller.lastlocation
        dx = abs(dx)
        dy = abs(dy)
        if (dx + dy) <= 0.00001:
            return False
        else:
            return True

    def on_attacked(self, atk):
        self.att.on_attacked(atk)

    def on_collision_with(self, mover):
        if not self.moved():
            # print "not moved, return"
            return False
        # print "direction", self.direction
        if abs(self.direction - mover.direction) == 2:
            # self.step_back()
            # print "facing each other, step back"
            return True
        rect = self.rect.copy()
        # print "self.rect before", self.rect
        rect.topleft = self.mcontroller.step_back()
        # print "self.rect", self.rect
        # print "rect", rect
        if not rect.colliderect(mover.rect):
            # self.step_back()
            # print "initiative"
            return True
        # else:
        # print "passive"
        return False

    def blocked(self, rect):
        self.set_location(self.mcontroller.backwards(rect))

    def collision_update(self):
        # collide_arr = sprite.spritecollide(self, enemy_tanks, 0)
        spritecollide = self.rect.colliderect

        for group in [enemy_tanks.sprites(), players.sprites()]:
            for s in group:
                if spritecollide(s.rect):
                    if self.on_collision_with(s):
                        self.step_back()
                        return

        for group in [stones.sprites(), rivers.sprites(), bricks.sprites()]:
            for s in group:
                if spritecollide(s.rect):
                    self.blocked(s.rect)
                    return

    def update_control(self, timepased, direction, shoot):
        location, direction = self.mcontroller.update_state(timepased, direction)
        self.set_direction(direction)
        self.set_location(location)
        self.shoot(shoot)
        self.collision_update()
        self.att.update_att()
        return None

    def toString(self):
        return '\n'.join(
            [self.attributes[a].toString() for a in self.attributes])


if __name__ == "__main__":
    import Attribute

    a1 = ["att", "n", "this is a test"]
    a2 = ["avd", "n", "this was a test"]
    a3 = ["avs", "c", "this will be a test"]
    a4 = ["kmn", "c", "this could be a test"]

    d1 = Attribute.Attribute(a1)
    d2 = Attribute.Attribute(a2)
    d3 = Attribute.Attribute(a3)
    d4 = Attribute.Attribute(a4)

    aa = AttributeSet()

    aa.add(d1)
    aa.add(d2)
    aa.add(d3)
    aa.add(d4)

    print aa.get(0).getValues()

    for a in aa:
        print a
コード例 #20
0
    def __setitem__(self, name, value):
        """
        """

        self.attr[name] = Attribute(name, value)