コード例 #1
0
def build_domains(fgdb, domains):
    """Create the esri domains (picklists) for track logs and features."""
    arcpy.CreateDomain_management(
        fgdb, "YesNoBoolean", "Yes/No values", "SHORT", "CODED"
    )
    arcpy.AddCodedValueToDomain_management(fgdb, "YesNoBoolean", 0, "No")
    arcpy.AddCodedValueToDomain_management(fgdb, "YesNoBoolean", 1, "Yes")
    for domain in domains:
        name = "{0}Codes".format(domain)
        description = "Valid values for {0}".format(domain)
        arcpy.CreateDomain_management(fgdb, name, description, "SHORT", "CODED")
        items = domains[domain]
        for i, item in enumerate(items):
            arcpy.AddCodedValueToDomain_management(fgdb, name, i, item)
コード例 #2
0
def fill_domains():
    for _key in domainListDict:
        _domain_dict = domainListDict[_key]
        for _code in _domain_dict:
            if domain_val_exists(_key, _code) is False:
                arcpy.AddCodedValueToDomain_management(
                    get_workspace(), _key, _code, _domain_dict[_code]
                )
                print(
                    "Domain value added: "
                    + str(_key)
                    + ": "
                    + str(_code)
                    + " -> "
                    + str(_domain_dict[_code])
                )
            else:
                print(
                    "domain_value already there: "
                    + str(_key)
                    + ": "
                    + str(_code)
                    + " -> "
                    + str(_domain_dict[_code])
                )
コード例 #3
0
ファイル: base.py プロジェクト: CUUATS/cuuats.datamodel
    def createCodedValuesDomain(cls, name, description, field_type, values):
        """Add a coded values domain, and populate it with coded values."""

        arcpy.CreateDomain_management(cls.fixture_path, name, description,
                                      field_type, 'CODED')

        for (code, desc) in values.items():
            arcpy.AddCodedValueToDomain_management(cls.fixture_path, name,
                                                   code, desc)
コード例 #4
0
def AddCodedValueToDomain(workspace, domain_name, code, code_description):
    try:
        arcpy.AddCodedValueToDomain_management(workspace, domain_name, code,
                                               code_description)
        print u"Valor {} adicionado ao dominio {} com sucesso.".format(
            code, domain_name)
    except Exception as ex:
        print u"ERRO ao adicionar valor {} ao dominio {}:".format(
            code, domain_name), ex.message
コード例 #5
0
def create_gdb_domain(gdb, name, description, ftype, dtype, c_values):
    new_domain = arcpy.CreateDomain_management(in_workspace=gdb,
                                               domain_name=name,
                                               domain_description=description,
                                               field_type=ftype,
                                               domain_type=dtype)
    for coded_value in c_values:
        arcpy.AddCodedValueToDomain_management(gdb, name, coded_value,
                                               c_values[coded_value])
    print("Field Domain {} added to FGDB".format(name))
コード例 #6
0
 def addJson2Gdb(self):
     listJsons = [os.path.join(self.path, x) for x in os.listdir(self.path)]
     for jsonFile in listJsons:
         with open(jsonFile, "r") as f:
             jx=f.read().decode("Windows-1252")
             df = pd.read_json(jx)
         domain = arcpy.CreateDomain_management(self.gdb, df["name"][0], '', 'TEXT')
         for dom in df['codedValues']:
             val = [v for k,v in dom.items()]
             arcpy.AddCodedValueToDomain_management(self.gdb, df['name'][0], val[0], val[1])
コード例 #7
0
ファイル: json2domain.py プロジェクト: ryali93/utilitarios
def makeDomain(jsonFile):
    with open(jsonFile, "r") as f:
        jx = f.read().decode("Windows-1252")
        df = pd.read_json(jx)
    domain = arcpy.CreateDomain_management(gdb, df["name"][0], '', 'TEXT')
    for dom in df['codedValues']:
        val = [v for k, v in dom.items()]
        print val
        arcpy.AddCodedValueToDomain_management(gdb, df['name'][0], val[0],
                                               val[1])
コード例 #8
0
 def addToWorkspace(self, workspace):
     """Add this domain to the GDB workspace."""
     arcpy.CreateDomain_management(workspace, self.domainName,
                                   self.description, self.fieldType,
                                   self.domainType, self.splitPolicy,
                                   self.mergePolicy)
     for code in self.codedValues:
         print code
         arcpy.AddCodedValueToDomain_management(workspace, self.domainName,
                                                code,
                                                self.codedValues[code])
コード例 #9
0
ファイル: BuildGDB.py プロジェクト: ryali93/utilitarios
 def makeDomain(self, jsonFile):
     with open(jsonFile, "r") as f:
         jx = f.read().decode("Windows-1252")
         data = json.loads(jx)
     df = pd.DataFrame.from_dict(data)
     domain = arcpy.CreateDomain_management(self.pathGdb, df['name'][0], "",
                                            "TEXT")
     print df['name'][0]
     for dom in df['codedValues']:
         val = [v for k, v in dom.items()]
         arcpy.AddCodedValueToDomain_management(self.pathGdb, df['name'][0],
                                                val[0], val[1])
コード例 #10
0
def CreateClassDomain():
    domDict = {"AI":"Apartment Improved","C":"Commercial","CA":"Commercial Auxiliary","CI":"Commercial Improved","CV":"Commercial Vacant","I":"Industrial",\
    "IA":"Industrial Auxiliary","II":"Industrial Improved","IV":"Industrial Vacant","R":"Residential","RA":"Residential Auxiliary","RI":"Residential Improved",\
    "RV":"Residential Vacant","UI":"Utility Improved","XA":"Exempt Auxiliary","XI":"Exempt Improved","XV":"Exempt Vacant"}

    arcpy.CreateDomain_management(workspace, "Parcels_Class", "Class Code",
                                  "TEXT", "CODED", "DEFAULT", "DEFAULT")

    for code in domDict:
        arcpy.AddCodedValueToDomain_management(workspace, "Parcels_Class",
                                               code, domDict[code])

    arcpy.AssignDomainToField_management(inFeature, "Class", "Parcels_Class")
コード例 #11
0
ファイル: Utility.py プロジェクト: Kbperri/PMLDM
def AddValueToDomain(workspace, domain, code, description):
    arcpy.env.workspace = workspace
    if not arcpy.Exists(domain):
        arcpy.CreateDomain_management(in_workspace=workspace,
                                      domain_name=domain,
                                      domain_description=domain,
                                      field_type="TEXT",
                                      domain_type="CODED",
                                      split_policy="DEFAULT",
                                      merge_policy="DEFAULT")

    arcpy.AddCodedValueToDomain_management(workspace, domain, code,
                                           description)
コード例 #12
0
def recoverFields(itemfields, mdpath):

    try:
        # Get field names from image service
        isfieldsName = [field["name"].lower() for field in itemfields]

        # Get field names from mosaic dataset
        mdfields = arcpy.ListFields(mdpath)
        mdfieldsName = [field.name.lower() for field in mdfields]
        mdfieldsName.remove("raster")

        missingfieldsName = [x for x in isfieldsName if x not in mdfieldsName]

        if len(missingfieldsName) > 0:
            for fieldname in missingfieldsName:

                arcpy.AddMessage(
                    "Adding missing field %s to the output mosaic dataset..." %
                    fieldname)

                mfield = filter(
                    lambda mfield: mfield["name"].lower() == fieldname,
                    itemfields)[0]
                ftype = getfieldTypeKey(mfield["type"])
                fprecision = ""
                fscale = ""
                flength = mfield["length"] if mfield.has_key("length") else ""
                falias = mfield["alias"] if mfield.has_key("alias") else ""
                fnullable = ""
                frequire = ""
                fdomain = mfield["domain"] if mfield.has_key("domain") else ""

                # Add missing field to the mosaic dataset
                arcpy.AddField_management(mdpath, fieldname, ftype, fprecision,
                                          fscale, flength, falias, fnullable,
                                          frequire)

                # Add domain if exist
                if fdomain != "" and fdomain != None:
                    domainDict = fdomain["codedValues"]
                    for code in domainDict:
                        arcpy.AddCodedValueToDomain_management(
                            os.path.dirname(mdpath), fdomain["name"],
                            code["code"], code["name"])
                    arcpy.AssignDomainToField_management(
                        mdpath, fieldname, fdomain["name"])

        # Optional: add an extra OID field to save ids in the original image service
        arcpy.AddField_management(mdpath, "OOID", "LONG")
    except:
        arcpy.AddError("ERROR: Failure in the recoverFields function")
コード例 #13
0
ファイル: db.py プロジェクト: mahdirajabi96/hsmpy3
 def AddDomains(self):
     ListDomains = [
         getattr(fields.domains, domain) for domain in dir(fields.domains)
         if not domain[0:2] == '__'
     ]
     for domain in ListDomains:
         print(domain['name'])
         arcpy.CreateDomain_management(self.gdb, domain['name'],
                                       domain['alias'], domain['type'],
                                       "CODED")
         for code in domain['codes'].keys():
             arcpy.AddCodedValueToDomain_management(self.gdb,
                                                    domain['name'], code,
                                                    domain['codes'][code])
コード例 #14
0
def create_player_domain(gdb, fc, line_fc, player_dict):
    domName = "Players"
    inField = "PLAYER_ID"

    # Process: Create the coded value domain
    arcpy.CreateDomain_management(gdb, domName, "Player Names", "TEXT",
                                  "CODED")

    # Process: Add valid material types to the domain
    #use a for loop to cycle through all the domain codes in the dictionary
    for code in player_dict:
        arcpy.AddCodedValueToDomain_management(gdb, domName, code,
                                               player_dict[code])

    # Process: Constrain the material value of distribution mains
    arcpy.AssignDomainToField_management(fc, inField, domName)
コード例 #15
0
def alter_domain_name():
    soucedomain = domain_dictionary('SPDM2_201803.gdb','Short')
    for dmname, alias_codesc in soucedomain.items():
        new_dmname = dmname[0:2]+'_' + dmname[2:]
        #if del_nm == dmname:
        if dmname[2] != '_':
            arcpy.CreateDomain_management(outdataset, new_dmname, alias_codesc[0], 'Short', 'CODED')
            print "创建域值"
            for cod, desc in alias_codesc[1].items():
                try:
                    arcpy.AddCodedValueToDomain_management(outdataset, new_dmname, int(cod), desc)
                except arcpy.ExecuteError:
                    print arcpy.GetMessages()
                    print cod, desc
                    print type(cod)
            arcpy.DeleteDomain_management(outdataset,dmname)
コード例 #16
0
def _json_to_domain(output_target, out_gdb, x):

    if output_target == OUTPUT_GDB:

        # Process: Create the coded value domain
        arcpy.CreateDomain_management(
            out_gdb,
            x['name'],
            field_type=_json_type_to_gdb_type(x['fieldType']),
            domain_type='CODED' if x['subType'] == 'CodedValue' else 'RANGE',
            domain_description=x['description'])

        for kv in x['values']:
            arcpy.AddCodedValueToDomain_management(out_gdb, x['name'], kv['k'],
                                                   kv['v'])

    elif output_target == OUTPUT_XML:

        template = """<Domain xsi:type='esri:CodedValueDomain'>
                <DomainName>%(name)s</DomainName>
                <FieldType>%(type)s</FieldType>
                <MergePolicy>esriMPTDefaultValue</MergePolicy>
                <SplitPolicy>esriSPTDefaultValue</SplitPolicy>
                <Description></Description>
                <Owner></Owner>
                <CodedValues xsi:type='esri:ArrayOfCodedValue'>
                    %(domains)s
                </CodedValues>
            </Domain>"""

        domains = list(
            map(
                lambda kv: """<CodedValue xsi:type='esri:CodedValue'>
                <Name>%(v)s</Name>
                <Code xsi:type='xs:%(type)s'>%(k)s</Code>
            </CodedValue>""" % {
                    'type': _json_type_to_xml_attr_type(x['fieldType']),
                    'k': kv['k'],
                    'v': kv['v']
                }, x['values']))

        return template % {
            'name': x['name'],
            'type': _json_type_to_xml_type(x['fieldType']),
            'domains': "\n".join(domains)
        }
コード例 #17
0
def CreateLUCDomain():
    domDict = {"10":"Residential Condo","11":"Single Family","12":"Two Family","13":"Three Family","14":"Four Family","15":"5-10 Family",\
                "16":"11-20 Family","17":"21+ Family","18":"Seasonal","19":"Garage & Sheds","20":"Commercial Condos",\
                "21":"Retail","22":"Office","23":"Hotel & Motel","24":"Wholesale","25":"Parking Lots","26":"Private Clubs","27":"Multi Use Commercial",\
                "31":"Manufacturing","32":"Warehouse & Storage","33":"Transportation","34":"Communication","35":"Extraction","36":"Multi Use Industrial",\
                "04":"Bed & Breakfast","40":"Vacant Land","41":"Parking Space Condo","42":"Boat Slips","05":"Parking Condos","53":"Exempt Religious",\
                "54":"Exempt Benevolent & Charitable","55":"Exempt Literary & Scientific","56":"Exempt Governmental","57":"Exempt by Law",\
                "58":"Land Bank","06":"Multi Use Residential","07":"Residential Hotels","08":"Apartment & Rooms","09":"Rooming Houses"}

    arcpy.CreateDomain_management(workspace, "Parcels_LUC", "Land Use Code",
                                  "TEXT", "CODED", "DEFAULT", "DEFAULT")

    for code in domDict:
        arcpy.AddCodedValueToDomain_management(workspace, "Parcels_LUC", code,
                                               domDict[code])

    arcpy.AssignDomainToField_management(inFeature, "LUC", "Parcels_LUC")
コード例 #18
0
ファイル: main.py プロジェクト: ryali93/utilitarios
 def addJson2Gdb(self):
     """
     Agregar Dominios a Geodatabase
     :return: 
     """
     listJsons = [
         os.path.join(pathDomain, x) for x in os.listdir(pathDomain)
     ]
     print listJsons
     for jsonFile in listJsons:
         with open(jsonFile, "r") as f:
             jx = f.read().decode("Windows-1252")
         df = pd.read_json(jx)
         print df
         arcpy.CreateDomain_management(self.gdb, df["name"][0], '', 'TEXT')
         for dom in df['codedValues']:
             val = [v for k, v in dom.items()]
             arcpy.AddCodedValueToDomain_management(self.gdb, df['name'][0],
                                                    val[0], val[1])
コード例 #19
0
def alter_domiantype_single():

    outdataset = r'D:\智能化管线项目\新气\新气数据处理\新气数据入库_0916\新库0910.gdb'

    save_domain = domain_dictionary(outdataset, 'LONG')  #
    print save_domain

    arcpy.DeleteDomain_management(outdataset, "gn_Reportstatus")
    for dmname, alias_codesc in save_domain.items():
        # if del_nm == dmname:
            arcpy.CreateDomain_management(outdataset, "gn_Reportstatus", alias_codesc[0], 'Short', 'CODED')
            print "创建域值"
            for cod, desc in alias_codesc[1].items():
                try:
                    arcpy.AddCodedValueToDomain_management(outdataset, "gn_Reportstatus", int(cod), desc)
                except arcpy.ExecuteError:
                    print arcpy.GetMessages()
                    print cod, desc
                    print type(cod)
コード例 #20
0
def create_domains(gdb):

    domain_definitions = [[
        'Status', 'STATUS_DOMAIN',
        ['Poor', 'Fair', 'Good', 'Very good', 'Excellent']
    ], ['Color', 'COLOR_DOMAIN', ['Red', 'Green', 'Yellow', 'Blue']]]

    for domain_definition in domain_definitions:
        arcpy.CreateDomain_management(in_workspace=gdb,
                                      domain_name=domain_definition[1],
                                      domain_description=domain_definition[0],
                                      field_type="TEXT",
                                      domain_type="CODED",
                                      split_policy="DEFAULT",
                                      merge_policy="DEFAULT")
        for value in domain_definition[2]:
            arcpy.AddCodedValueToDomain_management(
                in_workspace=gdb,
                domain_name=domain_definition[1],
                code=value,
                code_description=value)
コード例 #21
0
def main(thisDB, coordSystem, nCrossSections):
    # create feature dataset GeologicMap
    addMsgAndPrint('  Creating feature dataset GeologicMap...')
    try:
        arcpy.CreateFeatureDataset_management(thisDB, 'GeologicMap',
                                              coordSystem)
    except:
        addMsgAndPrint(arcpy.GetMessages(2))

    # create feature classes in GeologicMap
    # poly feature classes
    featureClasses = ['MapUnitPolys']
    for fc in ['DataSourcePolys', 'MapUnitOverlayPolys', 'OverlayPolys']:
        if fc in OptionalElements:
            featureClasses.append(fc)
    for featureClass in featureClasses:
        fieldDefs = tableDict[featureClass]
        if addLTYPE and fc <> 'DataSourcePolys':
            fieldDefs.append(['PTYPE', 'String', 'NullsOK', 50])
        createFeatureClass(thisDB, 'GeologicMap', featureClass, 'POLYGON',
                           fieldDefs)

    # line feature classes
    featureClasses = ['ContactsAndFaults']
    for fc in ['GeologicLines', 'CartographicLines', 'IsoValueLines']:
        if fc in OptionalElements:
            featureClasses.append(fc)
    if debug:
        addMsgAndPrint('Feature classes = ' + str(featureClasses))
    for featureClass in featureClasses:
        fieldDefs = tableDict[featureClass]
        if featureClass in ['ContactsAndFaults', 'GeologicLines'] and addLTYPE:
            fieldDefs.append(['LTYPE', 'String', 'NullsOK', 50])
        createFeatureClass(thisDB, 'GeologicMap', featureClass, 'POLYLINE',
                           fieldDefs)

    # point feature classes
    featureClasses = []
    for fc in [
            'OrientationPoints', 'GeochronPoints', 'FossilPoints', 'Stations',
            'GenericSamples', 'GenericPoints'
    ]:
        if fc in OptionalElements:
            featureClasses.append(fc)
    for featureClass in featureClasses:
        fieldDefs = tableDict[featureClass]
        if addLTYPE:
            fieldDefs.append(['PTTYPE', 'String', 'NullsOK', 50])
        createFeatureClass(thisDB, 'GeologicMap', featureClass, 'POINT',
                           fieldDefs)

    # create feature dataset CorrelationOfMapUnits
    if 'CorrelationOfMapUnits' in OptionalElements:
        addMsgAndPrint('  Creating feature dataset CorrelationOfMapUnits...')
        arcpy.CreateFeatureDataset_management(thisDB, 'CorrelationOfMapUnits')
        fieldDefs = tableDict['CMUMapUnitPolys']
        createFeatureClass(thisDB, 'CorrelationOfMapUnits', 'CMUMapUnitPolys',
                           'POLYGON', fieldDefs)
        fieldDefs = tableDict['CMULines']
        createFeatureClass(thisDB, 'CorrelationOfMapUnits', 'CMULines',
                           'POLYLINE', fieldDefs)
        fieldDefs = tableDict['CMUPoints']
        createFeatureClass(thisDB, 'CorrelationOfMapUnits', 'CMUPoints',
                           'POINT', fieldDefs)

    # create CrossSections
    if nCrossSections > 26:
        nCrossSections = 26
    if nCrossSections < 0:
        nCrossSections = 0
    # note space in position 0
    alphabet = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'

    for n in range(1, nCrossSections + 1):
        xsLetter = alphabet[n]
        xsName = 'CrossSection' + xsLetter
        xsN = 'CS' + xsLetter
        #create feature dataset CrossSectionA
        addMsgAndPrint('  Creating feature data set CrossSection' + xsLetter +
                       '...')
        arcpy.CreateFeatureDataset_management(thisDB, xsName)
        fieldDefs = tableDict['MapUnitPolys']
        if addLTYPE:
            fieldDefs.append(['PTYPE', 'String', 'NullsOK', 100])
        fieldDefs[0][0] = xsN + 'MapUnitPolys_ID'
        createFeatureClass(thisDB, xsName, xsN + 'MapUnitPolys', 'POLYGON',
                           fieldDefs)
        fieldDefs = tableDict['ContactsAndFaults']
        if addLTYPE:
            fieldDefs.append(['LTYPE', 'String', 'NullsOK', 100])
        fieldDefs[0][0] = xsN + 'ContactsAndFaults_ID'
        createFeatureClass(thisDB, xsName, xsN + 'ContactsAndFaults',
                           'POLYLINE', fieldDefs)
        fieldDefs = tableDict['OrientationPoints']
        if addLTYPE:
            fieldDefs.append(['PTTYPE', 'String', 'NullsOK', 100])
        fieldDefs[0][0] = xsN + 'OrientationPoints_ID'
        createFeatureClass(thisDB, xsName, xsN + 'OrientationPoints', 'POINT',
                           fieldDefs)

    # create tables
    tables = ['DescriptionOfMapUnits', 'DataSources', 'Glossary']
    for tb in [
            'RepurposedSymbols', 'StandardLithology', 'GeologicEvents',
            'MiscellaneousMapInformation'
    ]:
        if tb in OptionalElements:
            tables.append(tb)
    for table in tables:
        addMsgAndPrint('  Creating table ' + table + '...')
        try:
            arcpy.CreateTable_management(thisDB, table)
            fieldDefs = tableDict[table]
            for fDef in fieldDefs:
                try:
                    if fDef[1] == 'String':
                        arcpy.AddField_management(thisDB + '/' + table,
                                                  fDef[0], transDict[fDef[1]],
                                                  '#', '#', fDef[3], '#',
                                                  transDict[fDef[2]])
                    else:
                        arcpy.AddField_management(thisDB + '/' + table,
                                                  fDef[0], transDict[fDef[1]],
                                                  '#', '#', '#', '#',
                                                  transDict[fDef[2]])
                except:
                    addMsgAndPrint('Failed to add field ' + fDef[0] +
                                   ' to table ' + table)
                    addMsgAndPrint(arcpy.GetMessages(2))
        except:
            addMsgAndPrint(arcpy.GetMessages())

    ### GeoMaterials
    addMsgAndPrint('  Setting up GeoMaterials table and domains...')
    #  Copy GeoMaterials table
    arcpy.Copy_management(
        os.path.dirname(sys.argv[0]) +
        '/../Resources/GeMS_lib.gdb/GeoMaterialDict',
        thisDB + '/GeoMaterialDict')
    #   make GeoMaterials domain
    arcpy.TableToDomain_management(thisDB + '/GeoMaterialDict', 'GeoMaterial',
                                   'IndentedName', thisDB, 'GeoMaterials')
    #   attach it to DMU field GeoMaterial
    arcpy.AssignDomainToField_management(thisDB + '/DescriptionOfMapUnits',
                                         'GeoMaterial', 'GeoMaterials')
    #  Make GeoMaterialConfs domain, attach it to DMU field GeoMaterialConf
    arcpy.CreateDomain_management(thisDB, 'GeoMaterialConfidenceValues', '',
                                  'TEXT', 'CODED')
    for val in GeoMaterialConfidenceValues:
        arcpy.AddCodedValueToDomain_management(thisDB,
                                               'GeoMaterialConfidenceValues',
                                               val, val)
    arcpy.AssignDomainToField_management(thisDB + '/DescriptionOfMapUnits',
                                         'GeoMaterialConfidence',
                                         'GeoMaterialConfidenceValues')

    #Confidence domains, Glossary entries, and DataSources entry
    if addConfs:
        addMsgAndPrint(
            '  Adding standard ExistenceConfidence and IdentityConfidence domains'
        )
        #  create domain, add domain values, and link domain to appropriate fields
        addMsgAndPrint(
            '    Creating domain, linking domain to appropriate fields')
        arcpy.CreateDomain_management(thisDB, 'ExIDConfidenceValues', '',
                                      'TEXT', 'CODED')
        for item in DefaultExIDConfidenceValues:  # items are [term, definition, source]
            code = item[0]
            arcpy.AddCodedValueToDomain_management(thisDB,
                                                   'ExIDConfidenceValues',
                                                   code, code)
        arcpy.env.workspace = thisDB
        dataSets = arcpy.ListDatasets()
        for ds in dataSets:
            arcpy.env.workspace = thisDB + '/' + ds
            fcs = arcpy.ListFeatureClasses()
            for fc in fcs:
                fieldNames = fieldNameList(fc)
                for fn in fieldNames:
                    if fn in ('ExistenceConfidence', 'IdentityConfidence',
                              'ScientificConfidence'):
                        #addMsgAndPrint('    '+ds+'/'+fc+':'+fn)
                        arcpy.AssignDomainToField_management(
                            thisDB + '/' + ds + '/' + fc, fn,
                            'ExIDConfidenceValues')
        # add definitions of domain values to Glossary
        addMsgAndPrint('    Adding domain values to Glossary')
        ## create insert cursor on Glossary
        cursor = arcpy.da.InsertCursor(
            thisDB + '/Glossary', ['Term', 'Definition', 'DefinitionSourceID'])
        for item in DefaultExIDConfidenceValues:
            cursor.insertRow((item[0], item[1], item[2]))
        del cursor
        # add definitionsource to DataSources
        addMsgAndPrint('    Adding definition source to DataSources')
        ## create insert cursor on DataSources
        cursor = arcpy.da.InsertCursor(thisDB + '/DataSources',
                                       ['DataSources_ID', 'Source', 'URL'])
        cursor.insertRow((
            'FGDC-STD-013-2006',
            'Federal Geographic Data Committee [prepared for the Federal Geographic Data Committee by the U.S. Geological Survey], 2006, FGDC Digital Cartographic Standard for Geologic Map Symbolization: Reston, Va., Federal Geographic Data Committee Document Number FGDC-STD-013-2006, 290 p., 2 plates.',
            'https://ngmdb.usgs.gov/fgdc_gds/geolsymstd.php'))
        del cursor

    # if cartoReps, add cartographic representations to all feature classes
    # trackEdits, add editor tracking to all feature classes and tables
    if cartoReps or trackEdits:
        arcpy.env.workspace = thisDB
        tables = arcpy.ListTables()
        datasets = arcpy.ListDatasets()
        for dataset in datasets:
            addMsgAndPrint('  Dataset ' + dataset)
            arcpy.env.workspace = thisDB + '/' + dataset
            fcs = arcpy.ListFeatureClasses()
            for fc in fcs:
                hasReps, repLyr = cartoRepsExistAndLayer(fc)
                if cartoReps and hasReps:
                    addMsgAndPrint(
                        '    Adding cartographic representations to ' + fc)
                    try:
                        arcpy.AddRepresentation_cartography(
                            fc, fc + '_rep1', 'RuleID1', 'Override1', default,
                            repLyr, 'NO_ASSIGN')
                        """
                            Note the 1 suffix on the representation name (fc+'_rep1') and the RuleID1 and Override1 fields.
                        If at some later time we wish to add additional representations to a feature class, each will
                        require it's own RuleID and Override fields which may be identified, and tied to the appropriate
                        representation, by suffixes 2, 3, ...
                            Naming representations fc+'_rep'+str(n) should be sufficient to identify each representation in a 
                        geodatabase uniquely, and allow for multiple representations within a single feature class.
                            It appears that ArcGIS provides no means of scripting an inventory of representations within
                        feature class or geodatabase. So, the convenience of establishing a coded-value domain that ties
                        representation rule IDs (consecutive integers) to some sort of useful text identifier becomes a
                        necessity for flagging the presence of a representation: One CAN script the inventory of domains
                        in a geodatabase. Run arcpy.da.ListDomains. Check the result for names of the form
                        <featureClassName>_rep??_Rule and voila, you've got a list of representations (and their associated
                        feature classes) in the geodatabase.
                            Moral: If you add a representation, be sure to add an associated coded-value domain and name
                        it appropriately!
                        """
                    except:
                        addMsgAndPrint(arcpy.GetMessages(2))
                if trackEdits:
                    addTracking(fc)
        if trackEdits:
            addMsgAndPrint('  Tables ')
            arcpy.env.workspace = thisDB
            for aTable in tables:
                if aTable <> 'GeoMaterialDict':
                    addTracking(aTable)
コード例 #22
0
arcpy.AddIndex_management(workspace + '\\'
                          "SAPOLYGON", ["AREASYMBOL"], "SA_INDEX", "UNIQUE",
                          "ASCENDING")
#arcpy.AddIndex_management(workspace+'\\'"SAPOLYGON", "AREASYMBOL", "AREASYMBOL", "UNIQUE", "ASCENDING")

doname = "RECERT_NEEDED"  #Domain Name

#Create Domain

#arcpy.CreateDomain_management(in_workspace, doname, "No or Yes", "TEXT", "CODED")
arcpy.CreateDomain_management(workspace, doname, "No or Yes", "TEXT", "CODED")

# Add Coded Value to Domain

#arcpy.AddCodedValueToDomain_management (in_workspace, doname, "Yes", "Yes")
arcpy.AddCodedValueToDomain_management(workspace, doname, "Yes", "Yes")

#arcpy.AddCodedValueToDomain_management (in_workspace, doname, "No", "No")
arcpy.AddCodedValueToDomain_management(workspace, doname, "No", "No")

#Assign Domain To Field

#arcpy.AssignDomainToField_management (inFC, "RECERT_NEEDED", doname)
arcpy.AssignDomainToField_management(workspace + '\\'
                                     "Project_Record", "RECERT_NEEDED", doname)

arcpy.EnableEditorTracking_management(workspace + '\\'
                                      "MUPOLYGON", "Creator_Field",
                                      "Creation_Date_Field", "Editor_Field",
                                      "Last_Edit_Date_Field", "ADD_FIELDS",
                                      "UTC")
コード例 #23
0
def create_domain(nrows):
    # global flg
    flg = ''
    flg_bk = ''
    item_flg = ''
    for k in range(nrows):
        domains = arcpy.da.ListDomains(arcpy.env.workspace)
        domname_lst = [domain.name for domain in domains]
        if table.cell(k, 0).value == '':
            continue
        # print table.row_values(k)
        alst = table.row_values(k)
        if '' in alst:
            alst = list(set(alst))
            alst.remove('')
        # print alst

        if len(alst) > 2:  # 注意截取的字符串

            # item_flg = table.cell(k, 2).value

            # print flg+"1"
            try:
                if table.cell(k, 0).value not in domname_lst:
                    arcpy.CreateDomain_management(
                        arcpy.env.workspace,
                        table.cell(k, 0).value,
                        table.cell(k, 1).value,
                        table.cell(k, 2).value.upper(), "CODED")
                    flg = table.cell(k, 0).value
                    # print flg
                    item_flg = table.cell(k, 2).value.upper()
                    # print item_flg
                    flg_bk = ''

                else:
                    print "{} 该阈值名称已经存在!".format(table.cell(k, 0).value)
                    flg_bk = table.cell(k, 0).value
                    flg = ''

            except RuntimeError, arcpy.ExecuteError:
                print arcpy.GetMessages()
            # except arcpy.ExecuteError as err:
            #     print err
        elif len(alst) == 2:
            # print 10*"#"
            # print flg
            # print flg_bk
            # print 10 * "#"
            if flg_bk:
                # print flg_bk
                # print "因为阈值{}已存在,无需再为其添加阈值项!".format(flg_bk)
                continue
            elif flg:
                # print 222
                try:
                    # print 112
                    # print item_flg
                    # print 113
                    if item_flg == 'SHORT':
                        arcpy.AddCodedValueToDomain_management(
                            arcpy.env.workspace, flg,
                            int(table.cell(k, 0).value),
                            table.cell(k, 1).value)
                        print int(table.cell(k, 0).value)
                        print type(int(table.cell(k, 0).value)), table.cell(
                            k, 1).value
                    else:
                        arcpy.AddCodedValueToDomain_management(
                            arcpy.env.workspace, flg,
                            table.cell(k, 0).value,
                            table.cell(k, 1).value)
                except RuntimeError:
                    print arcpy.GetMessages()
コード例 #24
0
oDS = workspace + "/SRFLINE_SDATA"
arcpy.AddMessage("Uitvoer Dataset:  " + oDS + "\n")
if not arcpy.Exists(oDS):
    arcpy.CreateFeatureDataset_management(workspace, "SRFLINE_SDATA")
    arcpy.AddMessage("Uitvoer Dataset:  SRFLINE_SDATA aangemaakt!")
else:
    arcpy.AddMessage("Bestaande uitvoer Dataset:  SRFLINE_SDATA gebruiken!")
#---------------------------------------------------------
# Om de mogelijkheid te hebben om na het genereren van de dwarsprofielen per vak verkeerder profielen uit te kunnen
# zetten wordt er een kolom aan het basis profiellijnen en punten bestand(PWK_DWARSPROFIEL_POINT en PWK_DWARSPROFIEL_LINE)
# toegevoegd incl een domein met ja/nee
try:
    arcpy.AddMessage("Domein aanmaken: ")
    arcpy.CreateDomain_management(workspace, 'Meenemen', 'Meenemen', "TEXT",
                                  "CODED")
    arcpy.AddCodedValueToDomain_management(workspace, 'Meenemen', 'ja', 'ja')
    arcpy.AddCodedValueToDomain_management(workspace, 'Meenemen', 'nee', 'nee')
except:
    arcpy.AddWarning("Domein al toegevoegd!")
# Kolom toevoegen incl. domein
try:
    arcpy.AddField_management(ppFC, "meenemen", "TEXT", "", "", 3, "",
                              "NULLABLE", "NON_REQUIRED", "Meenemen")
    #arcpy.AssignDefaultToField_management(in_table=ppFC, field_name="meenemen", default_value="ja", subtype_code="", clear_value="false")
    arcpy.AddField_management(plFC, "meenemen", "TEXT", "", "", 3, "",
                              "NULLABLE", "NON_REQUIRED", "Meenemen")
    #arcpy.AssignDefaultToField_management(in_table=plFC, field_name="meenemen", default_value="ja", subtype_code="", clear_value="false")
    # ff alles op ja zetten
    arcpy.CalculateField_management(in_table=ppFC,
                                    field="meenemen",
                                    expression='"ja"',
コード例 #25
0
def check_and_create_domains(geodatabase):
    """
    Checks if the domains already exist, if they do
    then it checks the values and ranges

    If the domains do not exist, they are created

    :param geodatabase: (string) the path to the geodatabase to check
    :return:
    """
    domains = arcpy.da.ListDomains(geodatabase)
    domain_names = [domain.name for domain in domains]
    if 'Yes_No' in domain_names:
        for domain in domains:
            if domain.name == 'Yes_No':
                # check if cvs 0,1,2,4,5 are in the codedValues
                values = [cv for cv in domain.codedValues]
                if not set(set([0, 1, 2, 4, 5])).issubset(values):
                    arcpy.AddIDMessage("ERROR This domain already exists")
                    return
    else:
        # Add the domain and values
        arcpy.CreateDomain_management(in_workspace=geodatabase,
                                      domain_name="Yes_No",
                                      domain_description="Yes or No",
                                      field_type="TEXT",
                                      domain_type="CODED",
                                      split_policy="DEFAULT",
                                      merge_policy="DEFAULT")

        arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                               domain_name="Yes_No",
                                               code="Yes",
                                               code_description="Yes")
        arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                               domain_name="Yes_No",
                                               code="No",
                                               code_description="No")
        arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                               domain_name="Yes_No",
                                               code="N/A",
                                               code_description="N/A")

    # Check if 'Inspector" is a domain, if so check the range
    if 'Inspector' in domain_names:
        for domain in domains:
            if domain.name == 'Inspector':
                # check if cvs 0,1,2,4,5 are in the codedValues
                values = [cv for cv in domain.codedValues]
                if not set(set([0, 1, 2, 4, 5])).issubset(values):
                    arcpy.AddIDMessage("ERROR This domain already exists")
                    return
    else:
        # Add the domain and set the range
        arcpy.CreateDomain_management(in_workspace=geodatabase,
                                      domain_name="Inspector",
                                      domain_description="Inspector",
                                      field_type="TEXT",
                                      domain_type="CODED",
                                      split_policy="DEFAULT",
                                      merge_policy="DEFAULT")

    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Inspector",
                                           code="ALA",
                                           code_description="ALA")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Inspector",
                                           code="BAR",
                                           code_description="BAR")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Inspector",
                                           code="BUR",
                                           code_description="BUR")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Inspector",
                                           code="CAS",
                                           code_description="CAS")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Inspector",
                                           code="JJH",
                                           code_description="JJH")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Inspector",
                                           code="JLK",
                                           code_description="JLK")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Inspector",
                                           code="JWN",
                                           code_description="JWN")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Inspector",
                                           code="MJT",
                                           code_description="MJT")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Inspector",
                                           code="REM",
                                           code_description="REM")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Inspector",
                                           code="RWG",
                                           code_description="RWG")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Inspector",
                                           code="SAB",
                                           code_description="SAB")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Inspector",
                                           code="SJS",
                                           code_description="SJS")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Inspector",
                                           code="SUB",
                                           code_description="SUB")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Inspector",
                                           code="WBH",
                                           code_description="WBH")

    #  Check if Flow Percentage is a domain
    if 'Flow_Percent' in domain_names:
        for domain in domains:
            if domain.name == 'Flow_Percent':
                # check if cvs 0,1,2,4,5 are in the codedValues
                values = [cv for cv in domain.codedValues]
                if not set(set([0, 1, 2, 4, 5])).issubset(values):
                    arcpy.AddIDMessage("ERROR This domain already exists")
                    return
    else:
        # Add the domain and set the range
        arcpy.CreateDomain_management(in_workspace=geodatabase,
                                      domain_name="Flow_Percent",
                                      domain_description="Flow Percentage",
                                      field_type="TEXT",
                                      domain_type="CODED",
                                      split_policy="DEFAULT",
                                      merge_policy="DEFAULT")

    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Flow_Percent",
                                           code="0",
                                           code_description="0% (No Flow)")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Flow_Percent",
                                           code="25",
                                           code_description="25%")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Flow_Percent",
                                           code="50",
                                           code_description="50%")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Flow_Percent",
                                           code="75",
                                           code_description="75%")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Flow_Percent",
                                           code="100",
                                           code_description="100%")

    #  Check if Clock Position is a domain
    if 'Clock_Pos' in domain_names:
        for domain in domains:
            if domain.name == 'Clock_Pos':
                # check if cvs 0,1,2,4,5 are in the codedValues
                values = [cv for cv in domain.codedValues]
                if not set(set([0, 1, 2, 4, 5])).issubset(values):
                    arcpy.AddIDMessage("ERROR This domain already exists")
                    return
    else:
        # Add the domain and set the range
        arcpy.CreateDomain_management(in_workspace=geodatabase,
                                      domain_name="Clock_Pos",
                                      domain_description="Clock Position",
                                      field_type="TEXT",
                                      domain_type="CODED",
                                      split_policy="DEFAULT",
                                      merge_policy="DEFAULT")

    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Clock_Pos",
                                           code="1",
                                           code_description="1 o'clock")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Clock_Pos",
                                           code="10",
                                           code_description="10 o'clock")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Clock_Pos",
                                           code="11",
                                           code_description="11 o'clock")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Clock_Pos",
                                           code="12",
                                           code_description="12 o'clock")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Clock_Pos",
                                           code="2",
                                           code_description="2 o'clock")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Clock_Pos",
                                           code="3",
                                           code_description="3 o'clock")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Clock_Pos",
                                           code="4",
                                           code_description="4 o'clock")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Clock_Pos",
                                           code="5",
                                           code_description="5 o'clock")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Clock_Pos",
                                           code="6",
                                           code_description="6 o'clock")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Clock_Pos",
                                           code="7",
                                           code_description="7 o'clock")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Clock_Pos",
                                           code="8",
                                           code_description="8 o'clock")
    arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase,
                                           domain_name="Clock_Pos",
                                           code="9",
                                           code_description="9 o'clock")
コード例 #26
0
def check_and_create_domains(geodatabase):
    """
    Checks if the domains already exist, if they do
    then it checks the values and ranges

    If the domains do not exist, they are created

    :param geodatabase: (string) the path to the geodatabase to check
    :return:
    """
    domains = arcpy.da.ListDomains(geodatabase)
    domain_names = [domain.name for domain in domains]
    if 'ESRI_FIX_TYPE_DOMAIN' in domain_names:
        for domain in domains:
            if domain.name == 'ESRI_FIX_TYPE_DOMAIN':
                # check if cvs 0,1,2,4,5 are in the codedValues
                values = [cv for cv in domain.codedValues]
                if not set(set([0, 1, 2, 4, 5])).issubset(values):
                    arcpy.AddError(
                        "ESRI_FIX_TYPE_DOMAIN is missing a coded value pair.")
                    return
    else:
        # Add the domain and values
        arcpy.AddMessage(
            'Adding ESRI_FIX_TYPE_DOMAIN domain to parent geodatabase...')

        arcpy.CreateDomain_management(in_workspace=geodatabase,
                                      domain_name="ESRI_FIX_TYPE_DOMAIN",
                                      domain_description="Fix Type",
                                      field_type="SHORT",
                                      domain_type="CODED",
                                      split_policy="DEFAULT",
                                      merge_policy="DEFAULT")

        arcpy.AddCodedValueToDomain_management(
            in_workspace=geodatabase,
            domain_name="ESRI_FIX_TYPE_DOMAIN",
            code="0",
            code_description="Fix not valid")
        arcpy.AddCodedValueToDomain_management(
            in_workspace=geodatabase,
            domain_name="ESRI_FIX_TYPE_DOMAIN",
            code="1",
            code_description="GPS")
        arcpy.AddCodedValueToDomain_management(
            in_workspace=geodatabase,
            domain_name="ESRI_FIX_TYPE_DOMAIN",
            code="2",
            code_description="Differential GPS")
        arcpy.AddCodedValueToDomain_management(
            in_workspace=geodatabase,
            domain_name="ESRI_FIX_TYPE_DOMAIN",
            code="4",
            code_description="RTK Fixed")
        arcpy.AddCodedValueToDomain_management(
            in_workspace=geodatabase,
            domain_name="ESRI_FIX_TYPE_DOMAIN",
            code="5",
            code_description="RTK Float")
    # Check if 'NumSats" is a domain, if so check the range
    if 'ESRI_NUM_SATS_DOMAIN' in domain_names:
        if domain.name == "ESRI_NUM_SATS_DOMAIN":
            if domain.range[0] != 0 or domain.range[1] != 99:
                arcpy.AddError("ESRI_NUM_SATS_DOMAIN domain has invalid range")
                return
    else:
        # Add the domain and set the range
        arcpy.AddMessage("Adding ESRI_NUM_SATS_DOMAIN to parent database...")
        arcpy.CreateDomain_management(
            in_workspace=geodatabase,
            domain_name="ESRI_NUM_SATS_DOMAIN",
            domain_description="Number of Satellites",
            field_type="SHORT",
            domain_type="RANGE",
            split_policy="DEFAULT",
            merge_policy="DEFAULT")
        arcpy.SetValueForRangeDomain_management(geodatabase,
                                                "ESRI_NUM_SATS_DOMAIN", 0, 99)
    if 'ESRI_POSITIONSOURCETYPE_DOMAIN' in domain_names:
        for domain in domains:
            if domain.name == 'ESRI_POSITIONSOURCETYPE_DOMAIN':
                # check if cvs 0,1,2,3,4 are in the codedValues
                values = [cv for cv in domain.codedValues]
                if not set(set([0, 1, 2, 3, 4])).issubset(values):
                    arcpy.AddError(
                        "ESRI_POSITIONSOURCETYPE_DOMAIN is missing a coded value pair."
                    )
                    return
    else:
        # Add the domain and values
        arcpy.AddMessage(
            'Adding ESRI_POSITIONSOURCETYPE_DOMAIN domain to parent geodatabase...'
        )

        arcpy.CreateDomain_management(
            in_workspace=geodatabase,
            domain_name="ESRI_POSITIONSOURCETYPE_DOMAIN",
            domain_description="Position Source Type",
            field_type="SHORT",
            domain_type="CODED",
            split_policy="DEFAULT",
            merge_policy="DEFAULT")

        arcpy.AddCodedValueToDomain_management(
            in_workspace=geodatabase,
            domain_name="ESRI_POSITIONSOURCETYPE_DOMAIN",
            code="0",
            code_description="Unknown")
        arcpy.AddCodedValueToDomain_management(
            in_workspace=geodatabase,
            domain_name="ESRI_POSITIONSOURCETYPE_DOMAIN",
            code="1",
            code_description="User defined")
        arcpy.AddCodedValueToDomain_management(
            in_workspace=geodatabase,
            domain_name="ESRI_POSITIONSOURCETYPE_DOMAIN",
            code="2",
            code_description="Integrated (System) Location Provider")
        arcpy.AddCodedValueToDomain_management(
            in_workspace=geodatabase,
            domain_name="ESRI_POSITIONSOURCETYPE_DOMAIN",
            code="3",
            code_description="External GNSS Receiver")
        arcpy.AddCodedValueToDomain_management(
            in_workspace=geodatabase,
            domain_name="ESRI_POSITIONSOURCETYPE_DOMAIN",
            code="4",
            code_description="Network Location Provider")
コード例 #27
0
                "Ulmus_americana": "Ulmus americana", \
                "Ulmus_glabra": "Ulmus glabra", \
                "Ulmus_pumila": "Ulmus pumila", \
                "Ulmus_rubra": "Ulmus rubra", \
                "Ulmus_thomasii": "Ulmus thomasii", \
                "Viburnum_acerifolia": "Viburnum acerifolia", \
                "Viburnum_alnifolia": "Viburnum alnifolia", \
                "Viburnum_lentago": "Viburnum lentago", \
                "Viburnum_trilobum": "Viburnum trilobum", \
                "Vitis_riparia": "Vitis riparia", \
                "Xanthocyparis_nootkatensis": "Xanthocyparis nootkatensis", \
                "Zanthoxylum_americanum": "Zanthoxylum americanum", \
                "Zelkova_serrata": "Zelkova serrata", }

    for code in domDict:
        arcpy.AddCodedValueToDomain_management(gdb, domName, code,
                                               domDict[code])

        arcpy.SortCodedValueDomain_management(gdb, domName, "CODE",
                                              "ASCENDING")


    domDict2 = {"02": "02", \
                "04": "04", \
                "06": "06", \
                "08": "08", \
                "10": "10", \
                "12": "12", \
                "14": "14", \
                "16": "16", \
                "18": "18", \
                "20": "20", \
コード例 #28
0
                              "TEXT", "CODED")

# Store all the domain values in a dictionary with the domain code as the "key" and the
# domain description as the "value" (domDict[code])
domDict = {
    "100": "Reubicación",
    "200": "Rescate",
    "300": "Traslado",
    "400": "Compensación",
    "500": "Otro"
}

# Process: Add valid material types to the domain
# use a for loop to cycle through all the domain codes in the dictionary
for code in domDict:
    arcpy.AddCodedValueToDomain_management(gdb_1, domName, code, domDict[code])

# Process: Constrain the material value of distribution mains
arcpy.AssignDomainToField_management(FC, inField, domName)

out_name = "MuestreoVedaTB"
# Execute CreateTable
arcpy.CreateTable_management(gdb_1, out_name)
FC = r'\\atlantico2\Consultores Asociados\Biblioteca\SIG\RES2182_2016\Test_Veda\BD_ANLA_3116.gdb\MuestreoVedaTB'
arcpy.AddField_management(FC, "EXPEDIENTE", "TEXT", field_precision=20)
arcpy.AddField_management(FC, "ID_VEDA", "TEXT", field_precision=10)
arcpy.AddField_management(FC, "DIVISION", "TEXT", field_precision=50)
arcpy.AddField_management(FC, "CLASE", "TEXT", field_precision=50)
arcpy.AddField_management(FC, "ORDEN", "TEXT", field_precision=50)
arcpy.AddField_management(FC, "FAMILIA", "TEXT", field_precision=50)
arcpy.AddField_management(FC, "GENERO", "TEXT", field_precision=50)
コード例 #29
0
try:
        PUBLICDISPLAYDict = {"No Public Map Display":"No Public Map Display", "Public Map Display": "Public Map Display"}
        #Get a list of domains
        domains = arcpy.da.ListDomains(gdb_location+"\\"+gdb_name+".gdb")
        domain_names = [domain.name for domain in domains]
        #Check if domain exists in the list
        if 'DOM_PUBLICDISPLAY_NPS2016' in domain_names :
                arcpy.AddWarning("DOM_PUBLICDISPLAY_NPS2016 already exists")
                #Check if domain has required values
                for domain in domains:
                        if domain.name == 'DOM_PUBLICDISPLAY_NPS2016':
                                values = [cv for cv in domain.codedValues]
                                if not set(set(["No Public Map Display", "Public Map Display"])).issubset(values):
                                        arcpy.AddWarning("DOM_PUBLICDISPLAY_NPS2016 is missing a coded value pair.")
                                        for code in DATAACCESSDict:
                                                arcpy.AddCodedValueToDomain_management(gdb_location+"\\"+gdb_name+".gdb", "DOM_PUBLICDISPLAY_NPS2016", code, DATAACCESSDict[code])
                                        arcpy.AddWarning("But Sasquatch took care of it.")
        #Create the domain if it doesn't exist
        else:
                arcpy.CreateDomain_management(gdb_location+"\\"+gdb_name+".gdb", "DOM_PUBLICDISPLAY_NPS2016", "Public Map Display Yes/No", "TEXT", "CODED")
                arcpy.AddMessage ("Sasquatch created the DOM_PUBLICDISPLAY_NPS2016 domain")
                for code in PUBLICDISPLAYDict:        
                        arcpy.AddCodedValueToDomain_management(gdb_location+"\\"+gdb_name+".gdb", "DOM_PUBLICDISPLAY_NPS2016", code, PUBLICDISPLAYDict[code])
                arcpy.AddMessage ("Sasquatch added coded domain values to the DOM_PUBLICDISPLAY_NPS2016 domain")
except arcpy.ExecuteError:
        msgs = arcpy.GetMessages(2)
        arcpy.AddError(msgs)
except:
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
コード例 #30
0
def create_fc_fields_with_domains(fgdb_path):
    """
    :param  fgdb_path: file path to the file geodatabase
    :type fgdb_path: basestring
    """
    arcpy.env.workspace = fgdb_path
    arcpy.env.overwriteOutput = True

    # ---------------------------------------------------------------
    # define domains
    #
    # pattern:
    #
    #    for coded domains
    #        create a domain object _in the GDB_ (not as a Python object)
    #        create a dictionary of domain code:description pairs
    #        load the dictionary into the domain
    #        use the domain when creating a feature class or use
    #            arcpy.AssignDomainToField_management()
    #
    #    for range domains
    #        create a domain object _in the GDB_ (not as a Python object)
    #        set SetValueForRangeDomain_management
    #        use the domain when creating a feature class or use
    #            arcpy.AssignDomainToField_management()
    #
    # --------------------------------------------------------------

    log.info("Creating feature class")
    fc_name = "GDA94_fields_with_domains_polyline"
    fc_path = os.path.join(fgdb_path, fc_name)

    arcpy.CreateFeatureclass_management(
        out_path=fgdb_path,
        out_name=fc_name,
        geometry_type="POLYLINE",
        spatial_reference=arcpy.SpatialReference(4283))  # GDA94 lat/long)

    log.info("Creating domains")
    # --------------------------------------
    domain_name = "text_field_coded_domain"
    arcpy.CreateDomain_management(
        in_workspace=fgdb_path,
        domain_name=domain_name,
        domain_description="uses a coded TEXT domain",
        field_type="TEXT",
        domain_type="CODED")

    text_field_coded_domain_dict = {"R": "Red", "G": "Green", "B": "Blue"}

    for code in text_field_coded_domain_dict:
        arcpy.AddCodedValueToDomain_management(
            in_workspace=fgdb_path,
            domain_name=domain_name,
            code=code,
            code_description=text_field_coded_domain_dict[code])

    arcpy.AddField_management(in_table=fc_path,
                              field_name="text_field_with_coded_domain",
                              field_type="TEXT",
                              field_length=50,
                              field_alias="has a TEXT coded domain",
                              field_domain="text_field_coded_domain")

    # -----------------------------------------------------------------------------------

    domain_name = "float_field_coded_domain"
    arcpy.CreateDomain_management(
        in_workspace=fgdb_path,
        domain_name=domain_name,
        domain_description="uses a coded FLOAT domain",
        field_type="FLOAT",
        domain_type="CODED")

    float_field_coded_domain_dict = {
        1.1: "one decimal place",
        1.01: "two decimal places",
        1.001: "three decimal places"
    }

    for code in float_field_coded_domain_dict:
        arcpy.AddCodedValueToDomain_management(
            in_workspace=fgdb_path,
            domain_name=domain_name,
            code=code,
            code_description=float_field_coded_domain_dict[code])

    arcpy.AddField_management(in_table=fc_path,
                              field_name="float_field_with_coded_domain",
                              field_type="FLOAT",
                              field_alias="has a FLOAT coded domain",
                              field_domain="float_field_coded_domain")

    # -----------------------------------------------------------------------------------

    domain_name = "float_field_range_domain"
    arcpy.CreateDomain_management(
        in_workspace=fgdb_path,
        domain_name=domain_name,
        domain_description="uses a FLOAT range domain",
        field_type="FLOAT",
        domain_type="RANGE")

    arcpy.SetValueForRangeDomain_management(in_workspace=fgdb_path,
                                            domain_name=domain_name,
                                            min_value=1.1,
                                            max_value=2.2)

    arcpy.AddField_management(in_table=fc_path,
                              field_name="float_field_with_range_domain",
                              field_type="FLOAT",
                              field_alias="has a FLOAT range domain",
                              field_domain="float_field_range_domain")

    # -----------------------------------------------------------------------------------

    domain_name = "double_field_coded_domain"
    arcpy.CreateDomain_management(
        in_workspace=fgdb_path,
        domain_name=domain_name,
        domain_description="uses a coded DOUBLE domain",
        field_type="DOUBLE",
        domain_type="CODED")

    double_field_coded_domain_dict = {
        2.2: "one decimal place",
        2.00000000001: "10 decimal places",
        2.00000000000000000002: "20 decimal places"
    }

    for code in double_field_coded_domain_dict:
        arcpy.AddCodedValueToDomain_management(
            in_workspace=fgdb_path,
            domain_name=domain_name,
            code=code,
            code_description=double_field_coded_domain_dict[code])

    arcpy.AddField_management(in_table=fc_path,
                              field_name="double_field_with_coded_domain",
                              field_type="DOUBLE",
                              field_alias="has a DOUBLE coded domain",
                              field_domain="double_field_coded_domain")

    # -----------------------------------------------------------------------------------

    domain_name = "double_field_range_domain"
    arcpy.CreateDomain_management(
        in_workspace=fgdb_path,
        domain_name=domain_name,
        domain_description="uses a DOUBLE range domain",
        field_type="DOUBLE",
        domain_type="RANGE")

    arcpy.SetValueForRangeDomain_management(in_workspace=fgdb_path,
                                            domain_name=domain_name,
                                            min_value=1.00000000000000000001,
                                            max_value=20000000000000000000.2)

    arcpy.AddField_management(in_table=fc_path,
                              field_name="double_field_with_range_domain",
                              field_type="DOUBLE",
                              field_alias="has a DOUBLE range domain",
                              field_domain="double_field_range_domain")

    # -----------------------------------------------------------------------------------

    domain_name = "short_field_coded_domain"
    arcpy.CreateDomain_management(
        in_workspace=fgdb_path,
        domain_name=domain_name,
        domain_description="uses a coded SHORT domain",
        field_type="SHORT",
        domain_type="CODED")

    short_field_coded_domain_dict = {
        101: "one O one",
        102: "one O two",
        103: "one O three"
    }

    for code in short_field_coded_domain_dict:
        arcpy.AddCodedValueToDomain_management(
            in_workspace=fgdb_path,
            domain_name=domain_name,
            code=code,
            code_description=short_field_coded_domain_dict[code])

    arcpy.AddField_management(in_table=fc_path,
                              field_name="short_field_with_coded_domain",
                              field_type="SHORT",
                              field_alias="has a SHORT coded domain",
                              field_domain="short_field_coded_domain")

    # -----------------------------------------------------------------------------------

    domain_name = "short_field_range_domain"
    arcpy.CreateDomain_management(
        in_workspace=fgdb_path,
        domain_name=domain_name,
        domain_description="uses a SHORT range domain",
        field_type="SHORT",
        domain_type="RANGE")

    arcpy.SetValueForRangeDomain_management(in_workspace=fgdb_path,
                                            domain_name=domain_name,
                                            min_value=1000,
                                            max_value=2000)

    arcpy.AddField_management(in_table=fc_path,
                              field_name="short_field_with_range_domain",
                              field_type="SHORT",
                              field_alias="has a SHORT range domain",
                              field_domain="short_field_range_domain")

    # -----------------------------------------------------------------------------------

    domain_name = "long_field_coded_domain"
    arcpy.CreateDomain_management(
        in_workspace=fgdb_path,
        domain_name=domain_name,
        domain_description="uses a coded LONG domain",
        field_type="LONG",
        domain_type="CODED")

    long_field_coded_domain_dict = {
        40000: "forty thousand",
        400000: "four hundred thousand",
        4000000: "four million"
    }

    for code in long_field_coded_domain_dict:
        arcpy.AddCodedValueToDomain_management(
            in_workspace=fgdb_path,
            domain_name=domain_name,
            code=code,
            code_description=long_field_coded_domain_dict[code])

    arcpy.AddField_management(in_table=fc_path,
                              field_name="long_field_with_coded_domain",
                              field_type="LONG",
                              field_alias="has a LONG coded domain",
                              field_domain="long_field_coded_domain")

    # -----------------------------------------------------------------------------------

    domain_name = "long_field_range_domain"
    arcpy.CreateDomain_management(
        in_workspace=fgdb_path,
        domain_name=domain_name,
        domain_description="uses a LONG range domain",
        field_type="LONG",
        domain_type="RANGE")

    arcpy.SetValueForRangeDomain_management(in_workspace=fgdb_path,
                                            domain_name=domain_name,
                                            min_value=12000000,
                                            max_value=120000000)

    arcpy.AddField_management(in_table=fc_path,
                              field_name="long_field_with_range_domain",
                              field_type="LONG",
                              field_alias="has a LONG range domain",
                              field_domain="long_field_range_domain")

    # -----------------------------------------------------------------------------------

    domain_name = "date_field_coded_domain"
    arcpy.CreateDomain_management(
        in_workspace=fgdb_path,
        domain_name=domain_name,
        domain_description="uses a coded DATE domain",
        field_type="DATE",
        domain_type="CODED")

    date_field_coded_domain_dict = {
        "01-02-1972": "Mic's Birthday",
        "09-08-1969": "Donna's Birthday",
        "22-04-2002": "Annie's Birthday"
    }

    for code in date_field_coded_domain_dict:
        arcpy.AddCodedValueToDomain_management(
            in_workspace=fgdb_path,
            domain_name=domain_name,
            code=code,
            code_description=date_field_coded_domain_dict[code])

    arcpy.AddField_management(in_table=fc_path,
                              field_name="date_field_with_coded_domain",
                              field_type="DATE",
                              field_alias="has a DATE coded domain",
                              field_domain="date_field_coded_domain")

    # -----------------------------------------------------------------------------------

    domain_name = "date_field_range_domain"
    arcpy.CreateDomain_management(
        in_workspace=fgdb_path,
        domain_name=domain_name,
        domain_description="uses a DATE range domain",
        field_type="DATE",
        domain_type="RANGE")

    arcpy.SetValueForRangeDomain_management(in_workspace=fgdb_path,
                                            domain_name=domain_name,
                                            min_value="01-01-1972",
                                            max_value="22-04-2002")

    arcpy.AddField_management(in_table=fc_path,
                              field_name="date_field_with_range_domain",
                              field_type="DATE",
                              field_alias="has a DATE range domain",
                              field_domain="date_field_range_domain")