I have been tasked with making a tool, that when you open it you can choose from a list in a dropdown box, which then populates the second dropdown box with a sublist, like so:    However I only have a basic understanding of Python and I barely understand GIS, so this is a giant learning experience for me. I have tried using ESRI's site and this community, but alas I am still horribly stuck.  Where it goes wrong is at "self.params.filter.list =" I can make it work with if I give it a list like ["Option 1", "Option 2"], however i already have the list "mergedList" where I have the values I want, but I cannot for the life of me make it work.   I have tried with: self.params.filter.list = mergedList  and  self.params.filter.list = sorted(mergedList.keys()) and one other which eludes my brain right now.  Current code, it only has one of the params, since I can't get that to work I haven't done the other one.  import arcpy  class ToolValidator(object):   """Class for validating a tool's parameter values and controlling   the behavior of the tool's dialog."""    def __init__(self):     """Setup arcpy and the list of tool parameters."""     self.params = arcpy.GetParameterInfo()    def initializeParameters(self):     """Refine the properties of a tool's parameters.  This method is     called when the tool is opened."""      # Variables for Cursor     featureClassName = r'ArcGIS_Drift_Grundkort_DB.GISGRUNDKORT.Jordstykke'     cursorNavn = "ELAVSNAVN"     cursorNr = "MATRNR"      #Generate empty Lists     listNavn = []     listNr = []      #Populate lists     with arcpy.da.SearchCursor(featureClassName, (cursorNavn,)) as cursor:         for row in cursor:             listNavn.append(row)      with arcpy.da.SearchCursor(featureClassName, (cursorNr,)) as cursor:         for row in cursor:             listNr.append(row)      #Merge lists into a single list with keys     mergedList = {}     for i, v in enumerate(listNavn):         mergedList[v] = mergedList.get(v, []) + [listNr[i]]      #toolbox stuff     self.params[1].filter.list = mergedList      return    def updateParameters(self):     """Modify the values and properties of parameters before internal     validation is performed.  This method is called whenever a parameter     has been changed."""     return    def updateMessages(self):     """Modify the messages created by internal validation for each tool     parameter.  This method is called after internal validation."""     return   It is very likely there is a better way of doing this, I just need the unique data from column A (ELAVSNAVN) which is like companies and then a sublist with the numbers (MATRNR) that goes with that.  The tool itself is incomplete since i am stuck on just the list part, just need some pointers / tips for that.
66910
I have a python script that checks file path names for corresponding files in a drive location. All of the inputs were originally hard coded, and it works well enough:      import arcpy     import os     shp = r"C:\Users\dotwell\Desktop\Locations.shp"     fields = ["ZdriveLoc"]     f = open (r"C:\Users\dotwell\Desktop\ValMapsTest.txt", "w")     cursor = arcpy.da.SearchCursor (shp, fields)         for row in cursor:             Roll=str(row[0])             if not os.path.exists(Roll):             f.write(Roll + os.linesep)       f.close()   I'm trying to create an ArcGIS script tool from this, and I've only had partial success. I can use   shp = arcpy.GetParameterAsText(0)   to allow the user to select the shapefile. I'd like to then have a drop down list of the fields in that shapefile for the user to select the field that contains the path names, but I can't get it to work. Can someone show me how to generate the drop down? Here's my latest try. It works, but requires the user to type in the field name. It would also be nice for the user to designate the output text file name and location.   import arcpy import os shapefile = arcpy.GetParameterAsText(0) field = arcpy.GetParameterAsText(1) f = open (r"C:\Users\dotwell\Desktop\ValMapsTemp.txt", "w") cursor = arcpy.da.SearchCursor (shapefile, field) for row in cursor:     Roll=str(row[0])     if not os.path.exists(Roll):         f.write(Roll + os.linesep)   f.close()   Here are the parameters in my ArcGIS script tool:
18041
I used python add in to make a tool bar in Arcmap that edits features on a map. It works on a file geodatabase, but not on an ArcSDE version one. I've been getting an FDO error: 0. The solutions that I've found all involve opening a workspace, but I'm getting an error doing that as well. Here is the relevant portion of my code:          outFolderPath = r"U:\tempStuff"         outName = "Stuff.sde"         databasePlatform = "SQL_Server"         instance = "SQL Server"         arcpy.CreateDatabaseConnection_management(outFolderPath, outName,                                                   databasePlatform,                                                   instance)         print "Centroid of buidling:(%r,%r) Side length: %r" % (xCoordinate,                                                                 yCoordinate,                                                                 bob)         print "workspace is %r" % outName #outName is workspace          #Start edit session with an undo/redo stack then start         #edit operation         print "Starting editing"         edit = arcpy.da.Editor(outName) #outName is workspace Line 86         edit.startEditing(True, True)         edit.startOperation()          #stuff happens          cursor = arcpy.da.InsertCursor( fc, ["SHAPE@"])         cursor.insertRow([stuff])             #stop the edit operation and then save changes         edit.stopOperation()         edit.stopEditing(True)          del cursor         print "Building should be drawn"   This is the exact error I've been getting:  Traceback (most recent call last):   File "C:\Users\153289\AppData\Local\ESRI\Desktop10.3\AssemblyCache\{0BEF4E61-6332-4BCA-A908-959CA3C0B4E7}\leetScripts_addin.py", line 86, in onClick     edit = arcpy.da.Editor(outName)#outName is workspace RuntimeError: cannot open workspace   What's am I doing wrong in my code?
119738
In the attached screenshot, the attributes contain two field of interest "a" and "b".  I want to write a script to access the adjacent rows in order to make some calculations.  To access a single row, I would use the following UpdateCursor:  fc = r'C:\path\to\fc'  with arcpy.da.UpdateCursor(fc, ["a", "b"]) as cursor:      for row in cursor:           # Do something   For example, with OBJECTID 4, I am interested in calculating the sum of the row values in field "a" adjacent to OBJECTID 4 row (i.e. 1 + 3) and adding that value to the OBJECTID 4 row in the "b" field.  How can I access adjacent rows with the cursor to make these sort of calculations?
43888
The expression box has a handy &quot;select from selection&quot; button. Is there a way to emulate this with Python? I have the basic expressions down, but can't find a way to do this.
87622
There is plenty of documentation on how to add parameters to a category in a Python Toolbox i.e. see the bottom of )  But I haven't found a way to do this for a Python Script Tool. Can this be done?
44998
I have two shapefiles, Point and Polyline. I'm trying to populate my polyline layer with the point data ID (systemID) where the lines start to where they end; eg. create two columns (from and to). The lines already have flow direction assigned to them. I am using ArcHydro tools but Arcpy is also fine.  In ArcHydro I have tried using Attribute Tools > Generate From/To Nodes for lines but it creates values for To and From that are not from my point data. My other alternative was using Feature to Vertices and joining the result to my point data table to get the systemID. But then I would have to update the polyline layer as well. I am sure there is a easier way of doing it.  Note: not all the lines have points at the vertices, blank values are fine for them.
63419
I'm working with ArcGIS 10.2 for Desktop and OS Windows 7.   I need to set numeric vales from Zero back to NULL, but I can't from the field calculator.  I'm working with  a vector file and I need to display NULL in one column that shows 0 (Zero) as default value.  -------- Edit------- I am adding the error messages that he received  Translation:  An error occurred during the process.  Please consult the Geoprocessing Results Window to obtain more details.  Error at bottom, translation:  The values ​​of the selected column can not be set to null because the field in the database is defined as "Not Null".
84561
I would like to feed a list of feature classes (only one polygon per feature class, but up to 150 feature classes) into the Union tool in ModelBuilder by using a Feature Class Iterator and the Collect Values Tool.   Unfortunately, it does not work since "Collect Values" only works with Merge, Append, etc.   Does anyone know a workaround or another way to do this?
63011
I have a few shapefiles where some of the attributes contain the non-English characters ÅÄÖ. Since some queries doesn't work with these characters (specifically ), I tried to change them in advance with a simple script and add the new strings to another field.  However, change in characters works fine but not updating the field with arcpy.UpdateCursor.   What is an appropriate way of solving this?  I have also tried to do this via the Field Calculator while posting "code" to the codeblock, with the same error.  Error message: Runtime error  Traceback (most recent call last):   File "", line 1, in    File "c:/gis/python/teststring.py", line 28, in      val = code(str(prow.Typkod)) UnicodeEncodeError: 'ascii' codec can't encode character u'\xc4' in position 3: ordinal not in range(128)  Code:  # -*- coding: cp1252 -*- def code(infield):     data = ''     for i in infield: ##        print i         if i == 'Ä':             data = data + 'AE'         elif i == 'ä':             data = data + 'ae'         elif i == 'Å':             data = data + 'AA'         elif i == 'å':             data = data + 'aa'         elif i == 'Ö':             data = data + 'OE'         elif i == 'ö':             data = data + 'oe'         else:             data = data + i     return data   shp = r'O:\XXX\250000\DB\ArcView\shape.shp'  prows = arcpy.UpdateCursor(shp)  for prow in prows:     val = code(unicode(str(prow.Typkod), "utf-8"))     prow.Typkod_U = val     print val     prows.updateRow(prow)   The values of Typkod are of the type: [D, D, S, DDRÄ, TRÄ] etc.  I use ArcMap Basic (10.1) on Windows 7.    New Error message:  Runtime error  Traceback (most recent call last):   File "", line 1, in    File "c:/gis/python/teststring.py", line 29, in      val = code(unicode(str(row.Typkod), "utf-8")) UnicodeEncodeError: 'ascii' codec can't encode character u'\xc4' in position 3: ordinal not in range(128)  &gt;&gt;&gt; val 'DDRÄ' &gt;&gt;&gt; type(val) type 'str'      It appears as if the output from the function is wrong somehow. When there's ÅÄÖ involved it returns data = u'DDR\xc4' and not (as was my intention) data = 'DDRAE'. Any suggestions on what might cause this?
13824
I developed one tool  in arcgis using python code, in the process i used Describe(feature class) function to know the coordinate system of input feature class. I got success while compiling code, But i couldn't get how to set parameters for this function in tool(arcgis 10.0) designing.  I tried parameters as follow  Display  name:input feature class Data type : coordinate system. Type   : optional Direction : input.   My problem is  while i'm selecting input feature class, i didn't get coordinate system of that feature class.  Please Suggest..
45302
In looking at , it occurred to me that I am not sure how one would go about using geoprocessing tools in ArcGIS to split a polygon with a line programatically.  Manually, you would use the  or the , but how would you accomplish the same task using modelbuilder or python groprocessing scripting tools?  Right off the bat I think of all of the tools in the  like Union, Identity, etc, but those are all Polygon-Polygon tools, NOT Polygon-Line tools.  Even the  is Polygon-Polygon.  Any ideas?
43643
Using arcpy I'm trying to get the results of a selection, or what is currently selected as a list.  Basically I'm attempting to build an addin which on click will either perform an operation where I invoke SelectLayerByAttribute_management (or ByLocation) to select some features, or the user performs a selection ByAttribute (or ByLocation), and while they have their selection hightlighted executes my snippet by pressing a button on the toolbar.  In each  case I want to get a list of results to perform a specific task on only certain selected features.  I can't find out how to get a list of the currently selected features, or find a listener for  selection having been made so I can enable the button, and ensure I can perform my operation on an existing selection.
76742
Shapefile: "table1.shp"   Field name: "Name" Field name: "Result"   Flat file: "referenceTable"   Field name: "STREET" Field name: "AKA"   I need to compare the value "Name" in "table1.shp" to the value "STREET" in "referenceTable"  If the values are the same then put the "AKA" value into the "Result" in "table1.shp"     Here is my code.  I got stuck on accessing the elements from the array  import arcpy, os, sys, string from array import *   table1 = "G:\\xStreetNew\\table1.shp" table1_column = ['Name', 'Result'] referenceTable = "G:\\xStreetNew\\Test.gdb\\referenceTable" referenceTable_column = ['STREET', 'AKA']  referenceTable_List = [] with arcpy.da.SearchCursor(referenceTable, referenceTable_column) as rCur: for r_row in rCur:     reference_row = r_row[0].split(",")     referenceTable_List.insert(0,reference_row) ##print sorted(referenceTable_List)  Table1_Update_Cursor = arcpy.da.UpdateCursor(table1, "Name") for row in Table1_Update_Cursor:   if row[0] == None:   row[0] = row[0] else:   row[0] = row[0].replace(";",",")   Table1_Update_Cursor.updateRow(row)  table1_List = [] with arcpy.da.SearchCursor(table1, table1_column) as tCur: for t_row in tCur:     row = t_row[0].split(",")     table1_List.insert(0,row) ##print sorted(table1_List)  Table1_row = len(table1_List) Table1_column = len([table1_List]) ref_row = len(referenceTable_List) for i in range(0,Table1_row):  #Table Row   for ii in range(0,Table1_column):   #Table Column     print table1_List[i][ii]   Below was my old post.  Sorry for the confusion.  I have a shapefile named "table1.shp".     I would like to get all values from fielname "Name" from this table and put them into a list. Able to output each element from the list     So far, I'm able to create a list but not too sure how to get to value "AVENUE 33" or "CHAPMAN ST"  This is my code:  import arcpy, os, sys, string from array import *   table1 = "G:\\xStreetNew\\table1.shp" referenceTable = "G:\\xStreetNew\\Test.gdb\\referenceTable" cursor = arcpy.da.UpdateCursor(table1, "Name") for row in cursor: if row[0] == None:     row[0] = row[0] else:     row[0] = row[0].replace(";",",") cursor.updateRow(row) table1_column = ['Name'] table1_curObj = arcpy.da.SearchCursor(table1, table1_column) table1_List = [] for row in table1_curObj:    table1_row = row[0].split(",")    table1_List.insert(0,table1_row)    print table1_List[0]
62595
i am writing script which uses different Tools of arcgis and implementing different functionalities .. My script consists in different Functions running in an order. Each function is connected to each other , and works on layers and performs   functions like(update cursor, search cursor ) When function1 finishes execution funciton2 starts and works on the same layer on which first one was working.   The problem is here function2 generates wrong results or works wrong.  works wrong means if a loop is defined to 5 iterations it will runs more then 5 times. like 20, 30 times and generates different results of one value.  When i run each function separately it will works fine. but when i run function in one script it will create problems.  My findings of this are LOCKS which are creating the problem.  Sample Structure of my script:  import arcpy   import math   import sys     import traceback     from arcpy import env    class test:       def __init__(self, workSpace):          self.workSpace = workSpace        # Add Fields       def function1(self):             # Script               return;           # Generate Report       def function2(self):              # Script            rows = arcpy.SearchCursor(self.mapLayerFinal,"","","Shape_Area")           row = rows.next()           while row:                   area = row.Shape_Area                     print "function2"                         destination_cursor = arcpy.UpdateCursor(self.censusLayer, '"DISTRICT_ID" = '+ str(district_id))                   row1 = destination_cursor.next()                   while row1:                           row1.setValue("District_Area",area)                           destination_cursor.updateRow(row1)                            row1 = destination_cursor.next()                    row = rows.next()             return;        t = test(workSpace)   t.function1()   t2 = test(workSpace)   t2.function2()     NOTE: code is tested and working correct if each function is executed separately
12623
I ran across an issue the other day when I tried to use ArcPy's mapping module to edit rectangle text elements with newlines (\n) in an ArcMap document.  Here's what the output looked like:    Here's the code I used to generate that output.  The first column are rectangle text elements Text1, Text2, Text3 going down; the second column are "plain" text elements Text4, Text5, and Text6 going down.  import os import arcpy  HomeDir = r"C:\Desktop" arcpy.env.workspace = HomeDir  CurrentMXD = arcpy.mapping.MapDocument(r"C:\Desktop\TextTest.mxd") OutputFilename = r"C:\Desktop\TextTest.pdf" if os.path.exists(OutputFilename):     os.remove(OutputFilename)  for TextElement in arcpy.mapping.ListLayoutElements(CurrentMXD, "TEXT_ELEMENT"):     TextElementName = TextElement.name      String1 = "The quick brown fox jumped over the lazy dog.\nShe sells sea shells by the sea shore."     String2 = "The quick brown fox \njumped over the lazy dog.\nShe sells sea shells by the sea shore."     String3 = "The quick brown fox jumped \nover the lazy dog.\nShe sells sea shells by the sea shore."      if TextElementName == "Text1":         TextElement.text = String1     if TextElementName == "Text2":         TextElement.text = String2      if TextElementName == "Text3":         TextElement.text = String3     if TextElementName == "Text4":         TextElement.text = String1     if TextElementName == "Text5":         TextElement.text = String2     if TextElementName == "Text6":         TextElement.text = String3  arcpy.mapping.ExportToPDF(CurrentMXD, OutputFilename)   So far, it looks like the presence of the messed up text depends on whether the line is longer enough to wrap, and whether the line before the newline is longer than the line after the newline.  Any ideas about what could be going wrong?  Is there a workaround?  I could use plain text elements and worry about wrapping lines using Python, but I'm hoping I can figure something out.
29741
I've written a few Python Toolboxes (which are new at ArcGIS 10.1), but am yet to decide whether/when I should write them rather than Python Script Tools in a standard toolbox.  I thought the  might enlighten me when it prefaces some dot points with:     Once created, tools in a Python toolbox provide many advantages   However, the five advantages listed all seem to be over not being able to use Python to write tools, and none seem to specify an advantage of Python Toolboxes over Python Script Tools.  The two advantages that I can think of are:   I can now write a "pure" Python tool in a single Python script without having to hook it up to a separately authored dialog with its Tool Validation looking like it was tacked on but I'm happy to be pragmatic rather than pure in this regard I could now use code (Python or any language capable of writing text files) to automate the writing of Python toolboxes but I am yet to come across a requirement to do this   Am I overlooking the compelling case that led Esri to provide the Python Toolbox capability and, if so, what is it?
5179
I can’t use the tool arcpy.CreateFishnet_management because define the parameter “templateExtent” with a shapefile it is not filling automatically the  parameters “originCoordinate” and “yAxisCoordinate”.   import arcpy from arcpy import env env.overwriteOutput = True env.workspace = r"D:\Users\julia\erste_aufg"  #Process: Create Fishnet outFeatureClass = r"D:\Users\julia\erste_aufg\at001l_wien\at001l_wien\wien.shp" cellSizeWidth = '200' cellSizeHeight = '200' templateExtent = r"D:\Users\julia\erste_aufg\at001l_wien\at001l_wien\at001l_wien.shp"  arcpy.CreateFishnet_management(outFeatureClass, "", "", cellSizeWidth, cellSizeHeight, '0', '0', "", "NO_LABELS", templateExtent, "POLYGON")     It is working in the ModelBulider, so something is running in the background of the ModelBulider that it could create the parameters “originCoordinate” and “yAxisCoordinate” when it has a “templateExtent”.  How can I get this tool running in ArcPy by having just the parameter “templateExtent”?  I would be really happy if someone has a solution because I need the Fishnet in a scripttool and cannot go one without because in the end there is a loop so the values of the extent are always different.