|
POST
|
Hi, the website seems to have killed your code formatting, I have just tidied it up for use myself, thought I would re-post for anyone else that may stumble upon this thread: # Import necessary modules.
import arcpy, datetime
# Set the admin connection -> this user needs to have privilegs to disconnect users.
adminConnection = r'Database Connections\dbo@testDB@testServer.sde'
# Get a list of connected users.
uList = arcpy.ListUsers(adminConnection)
# Print the number of connected users
count = len(uList)
print 'There are currently {0} users connected\n'.format(count)
# Exception lists -> these are used to determine machine names or users
# which will not be disconnected. Leave blank if there are no exceptions
machines = ['devinci','rocky']
users = ['samhill', 'stevepeat', 'stevesmith']
# Get current time.
now = datetime.datetime.now()
# Get time a week ago
weekAgo = now - arcpy.time.EsriTimeDelta(7, 'days')
# Iterate through users for u in uList:
if u.ConnectionTime < weekAgo:
if u.ClientName.lower() in machines:
print "Skipping user: {0} on machine: {1}".format(u.Name, u.ClientName)
print "Machine name is on exception list.\n"
elif u.Name.lower() in users:
print "Skipping user: {0} on machine: {1}".format(u.Name, u.ClientName)
print "User's name is on exception list.\n"
else:
try:
arcpy.DisconnectUser(adminConnection, u.ID)
print "Successfully disconnected user: {0}\n".format(u.Name)
except:
print arcpy.GetMessages()
else:
print "User ({0}) connection time did not exceed the set limit.\n".format(u.Name)
# Get a list of connected users.
uList = arcpy.ListUsers(adminConnection)
# Print the number of connected users
count = len(uList)
print 'There are currently {0} users connected'.format(count)
print 'Done'
... View more
12-12-2016
02:21 PM
|
1
|
0
|
2467
|
|
POST
|
Hi All, I have been using the Traverse tool (see screenshot) and I notice that when I finish that the Explode Multipart Feature button will not work on this output. I am wondering if there is any other way I can 'explode' this traverse so I am left with each of the segments as individual lines? Just like the burst command in AutoCAD. Thanks for your help.
... View more
10-30-2016
10:50 PM
|
0
|
1
|
1313
|
|
POST
|
So I am entering in Subdivision linework... see screenshot below:
... View more
10-27-2016
06:31 PM
|
0
|
1
|
908
|
|
POST
|
Hey All, I do many traverses using the Traverse window in ArcMap. I am wondering if anyone can tell me how to 'adjust' this traverse by a scale factor? The surveyor has noted the plan is scaled to 0.999568, I am unsure how to apply this. Thanks heaps!
... View more
10-27-2016
06:07 PM
|
0
|
3
|
1643
|
|
POST
|
That will work. The output is: First part = [Incandescent ], second part = [200 250] So a minor tweak to strip the space (last character) from the first part: print "First part = [%s], second part = [%s]" % (str1[:pos-1], str1[pos:len(str1)]) I just needed to add the -1 to achieve this. Looks good, thanks.
... View more
10-05-2016
10:08 PM
|
1
|
0
|
1415
|
|
POST
|
Hi All, Sorry for the poorly worded heading, I can't quite find the words to summarise what im trying to say. So basically I have been given a table with thousands of rows, and I need to split one of the fields, moving the first part of the field into a string column, and the right half of the split to a numeric column. Here is a Pivot table (grouped) #view of what I need to split: Incandescent 200 250
Incandescent 300
Incandescent 500
Incandescent 60
Incandescent 75
Low Pressure Sodium 135
Low Pressure Sodium 150
Low Pressure Sodium 310
Low Pressure Sodium 55
Low Pressure Sodium 90 100
Mercury Vapour 1000
Mercury Vapour 125
Mercury Vapour 175
Mercury Vapour 250
Mercury Vapour 400
Mercury Vapour 50
Mercury Vapour 500
Mercury Vapour 700
Mercury Vapour 80
Metal Hallide (Reactor Control Gear) 1000
Metal Hallide (Reactor Control Gear) 150
Metal Hallide (Reactor Control Gear) 250
Metal Hallide (Reactor Control Gear) 400
Metal Hallide (Reactor Control Gear) 70 So with the first row as an example I would like to end up with a column called STRING with 'Incandescent' in it, and a second column called WATTS with '200 250'. I am trying to use field calculator, I understand I will need to run it twice, once to calculate the STRING and once for WATTS. Python is my preference, but in this instance im unsure where to start the split. Cheers! (Nathan Duncan any ideas?)
... View more
10-05-2016
09:32 PM
|
0
|
3
|
2328
|
|
POST
|
So after many hours of trial and error, then implementing most of the changes as suggested in this thread, I contacted esri australia tech support. They pointed out the errors of my ways. A few misunderstandings from me as to how JSON works, and other simple code tweaks, the end result is below, works a treat! service = 'Service Name'
# A function to generate a token given username, password and the adminURL.
def getToken():
portalAdminName = 'gisadmin' # Gisserver login
portalAdminPassword = 'xxxxxxx' # gisserver password
serverName = 'gisserver' # Server Name
serverPort = 6080 # Port number of the server
# Token URL is typically http://server[:port]/arcgis/admin/generateToken
tokenURL = "/arcgis/admin/generateToken"
params = urllib.urlencode({
'username': portalAdminName,
'password': portalAdminPassword,
'client': 'requestip',
'f': 'json'
})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
# Connect to URL and post parameters
httpConn = httplib.HTTPConnection(serverName, serverPort)
httpConn.request("POST", tokenURL, params, headers)
# Read response
response = httpConn.getresponse()
if response.status != 200:
httpConn.close()
print "Error while fetching tokens from admin URL. Please check the URL and try again."
return
else:
data = response.read()
httpConn.close()
# Extract the token from it
token = json.loads(data)
return token.get('token')
# Generate Token
token = getToken()
# Add token to service URL to authenticate access.
params = {'token': token, 'f': 'json'}
# build the URL used to connect to the web form
fUrl = 'http://gisserver:6080/arcgis/admin/services/' + service + '.MapServer?' + urllib.urlencode(params)
# Open service URL to access parameters
openUrl = urllib2.urlopen(fUrl, '').read()
# Load json response in string serviceJson to access later
servicePython = json.loads(openUrl)
# Change the maxImage size properties in the python dictionary
servicePython['properties']['maxImageHeight'] = 5200
servicePython['properties']['maxImageWidth'] = 6600
servicePython['maxInstancesPerNode'] = 15
# Convert python dictionary back into a JSON string
serviceJson = json.dumps(servicePython)
# Define params dictionary
params = {"service": serviceJson, "f": "json", "token": token}
# REST endpoint for editing the service
finalUrl = 'http://gisserver:6080/arcgis/admin/services/' + service + '.MapServer/edit?'
# URLencoded paramaters dictionary can be included as a parameter of the call to urllib2.urlopen
openUrl = urllib2.urlopen(finalUrl, urllib.urlencode(params))
... View more
08-18-2016
08:39 PM
|
0
|
0
|
3058
|
|
POST
|
Thanks very much for the reply David, I have tweaked what you have provided and been able to work out how to connect and generate a token. That works nicely. I am now trying to connect back to the server and publish my new parameters, and I am getting this error: Traceback (most recent call last): File "U:/Automated/editMapServiceParameters.py", line 62, in <module> raise Exception('Service access error, response = {}'.format(json.dumps(serviceJson))) Exception: Service access error, response = {"status": "error", "code": 500, "messages": ["1"]} I am unsure how to progress from here. Did you hit this hurdle in your travels by any chance? Here is the code which causes the above error: import json
import urllib
import urllib2
import httplib
adminUrl = 'http://gisserver:6080/arcgis/admin/services'
portalAdminName = 'gisadmin'
portalAdminPassword = PASSWORD
portalUrl = "/arcgis/admin/generateToken"
serverName = 'gisserver'
serverPort = 6080
# A function to generate a token given username, password and the adminURL.
def getToken(username, password, serverName, serverPort):
# Token URL is typically http://server[:port]/arcgis/admin/generateToken
tokenURL = "/arcgis/admin/generateToken"
params = urllib.urlencode({'username': username, 'password': password, 'client': 'requestip', 'f': 'json'})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
# Connect to URL and post parameters
httpConn = httplib.HTTPConnection(serverName, serverPort)
httpConn.request("POST", tokenURL, params, headers)
# Read response
response = httpConn.getresponse()
if response.status != 200:
httpConn.close()
print "Error while fetching tokens from admin URL. Please check the URL and try again."
return
else:
data = response.read()
httpConn.close()
# Extract the token from it
token = json.loads(data)
return token.get('token')
# Generate Token
token = getToken(portalAdminName, portalAdminPassword, serverName, serverPort)
print 'token:: %s' % token
# Add token to service URL to authenticate access.
params = {'token': token, 'f': 'json'}
fUrl = 'http://gisserver:6080/arcgis/admin/services/Maps/Weave_Inset.MapServer?' + urllib.urlencode(params)
print fUrl
# Open service URL to access parameters
openUrl = urllib2.urlopen(fUrl, '').read()
# Load json response in string serviceJson to access later
serviceJson = json.loads(openUrl)
# Check response for valid service
if '{"serviceName":' not in serviceJson:
raise Exception('Service access error, response = {}'.format(json.dumps(serviceJson))) Thanks again.
... View more
08-07-2016
10:05 PM
|
0
|
1
|
3058
|
|
POST
|
Hi Everyone for your suggestions. I have looked through each of the links provided, unfortunately I am yet to see an example to help me set the MaxImageWidth and MaxImageHeight... back to the drawing board, I may have to continue to do this manually 😕 Thanks anyways.
... View more
07-14-2016
06:28 AM
|
0
|
0
|
3058
|
|
POST
|
I don't need to create a script, this is me running it (just using the sample code on the page you provided me)... By removing the try: and except components (converting from a script to a run once type setup as Dan suggested) I got a more accurate Error Message saying: Traceback (most recent call last): File "F:/Ben VK/Conver LatLong DD to LatLong DMS.py", line 19, in <module> output_coordinate_format=output_format File "C:\Program Files (x86)\ArcGIS\Desktop10.3\ArcPy\arcpy\management.py", line 8663, in ConvertCoordinateNotation raise e arcgisscripting.ExecuteError: ERROR 999999: Error executing function. Failed to execute (ConvertCoordinateNotation). Upon closer inspection, it seems I was using output_format = "DDM_2" instead of the correct output_format = "DMS_2", now works like a charm. Thanks for your help Dan, that tool is perfect for my scenario. Cheers Final working code for all those playing along at home: input_table = r'F:\Nathan Duncan\Assets & Planning\2015-2016\Sewer Sample Points\TempSampSite.shp'
output_points = r'F:\Nathan Duncan\Assets & Planning\2015-2016\Sewer Sample Points\SewerSamplePoints.gdb\CoordConversion\DMS'
x_field = "Longitude"
y_field = "Latitude"
input_format = "DD_2"
output_format = "DMS_2"
spatial_ref = arcpy.SpatialReference('WGS 1984')
arcpy.ConvertCoordinateNotation_management(
in_table=input_table,
out_featureclass=output_points,
x_field=x_field,
y_field=y_field,
input_coordinate_format=input_format,
output_coordinate_format=output_format
)
... View more
07-11-2016
07:23 PM
|
1
|
0
|
3462
|
|
POST
|
Great suggestion, looks like it will do exactly what I want, but im getting the error every GIS User wants to see 'Error 999999' with the below code # imports
import arcpy
arcpy.env.workspace = r"F:\Nathan Duncan\Assets & Planning\2015-2016\Sewer Sample Points\SewerSamplePoints.gdb"
# set parameter values
input_table = r'F:\Nathan Duncan\Assets & Planning\2015-2016\Sewer Sample Points\TempSampSite.shp'
output_points = r'F:\Nathan Duncan\Assets & Planning\2015-2016\
Sewer Sample Points\SewerSamplePoints.gdb\CoordConversion\DMS'
x_field = "Longitude"
y_field = "Latitude"
input_format = "DD_2"
output_format = "DDM_2"
spatial_ref = arcpy.SpatialReference('WGS 1984')
try:
arcpy.ConvertCoordinateNotation_management(in_table=input_table, out_featureclass=output_points,
x_field=x_field, y_field=y_field,
input_coordinate_format=input_format,
output_coordinate_format=output_format
)
print(arcpy.GetMessages(0))
except arcpy.ExecuteError:
print(arcpy.GetMessages(2))
except Exception as ex:
print(ex.args[0]) ERROR 999999: Error executing function. Failed to execute (ConvertCoordinateNotation).
... View more
07-11-2016
07:10 PM
|
0
|
2
|
3462
|
|
POST
|
Hi All, I have never worked with coordinates other than Easting Northings, and today I have been given a table that contains Eastings and Northings, and another two columns with Lat Long (DD). Unfortunately my client requires a table with Lat Long shown in Degrees Minutes and Seconds, and this is not something I have ever had to do so I have some questions. When I create the fields which will hold the Lat Long data in DMS, what type (format) should the field be? I am assuming a double is not sufficient? Is there a simple field calculator tool that takes a column (Easting) for example, and spits out the Latitude in DMS format? I am very new to coordinate conversion, so any tips are appreciated. Thanks for your help.
... View more
07-11-2016
06:12 PM
|
1
|
4
|
5042
|
|
POST
|
Hey, So I might have found something useful here, it may work - Example: Edit service properties—Documentation (10.3 and 10.3.1) | ArcGIS for Server This section of the code may do part of what I require: # Edit desired properties of the service
dataObj["minInstancesPerNode"] = minInstancesNum
dataObj["maxInstancesPerNode"] = maxInstancesNum My secondary question is, how do I find what all the options are called? The above example exactly answers part of my question, as one of the items I want to update is max instances, but how do i find out what the syntax would be for the Max image Width and height will be? How does one go about searching for this?? Thanks in advance. Cheers
... View more
07-06-2016
02:25 AM
|
1
|
2
|
3059
|
|
POST
|
Hi All, I currently have a Python script which does 98% of what I require. Currently, it picks up a local MXD file that has been modified in the last 3 days, then uses arcpy.mapping.CreateMapSDDraft() to create the Draft Service Definition, then stages the service using arcpy.StageService_server() and finally arcpy.UploadServiceDefinition_server() Each time this file is uploaded, it is overwriting an existing map service, and these services all have Advanced Properties modified, for example the maxImageWidth and Height are modified, along with Max Number of Instanced modified to be 15. The problem I have is that each time this script runs, it reverts those three settings back to the default, so then I have to manually set them to what we require, which in turn defeats the purpose of automating this process... I have pasted my working code below, its not pretty, but seems to do most of what I require.... Any ideas on how to set those additional parameters in python?
def publish_services(service):
log.write_log(python_file, 'Updating Services (' + service + ') to GISServer')
err = False
# Define Local Variables
wrkspc = r'\\gisserver\weave projects\Project_Files'
doc = os.path.join(wrkspc, service + '.mxd')
log.write_log(python_file, 'Publishing File to Service:')
log.write_log(python_file, ' %s [doc]' % doc)
is_edited = check_edit_date(service, doc)
if is_edited is True:
mapDoc = arcpy.mapping.MapDocument(doc)
# Provide path to connection file
# To create this file, right-click a folder in the Catalog window and
# click New > ArcGIS Server Connection
con = 'GIS Servers\GisServer (Administration)'
# Provide other service details
sddraft = os.path.join(wrkspc, service + '.sddraft')
sd = os.path.join(wrkspc, service + '.sd')
summary = 'Map document displayed by the Weave Mapping System'
tags = 'Weave, python, automated, MXD, Map Service Automation, No Man Hours Used'
def del_sd():
try:
os.remove(sd)
log.write_log(python_file, 'Removed the existing sd file - %s' % str(sd))
except OSError:
pass
log.write_log(python_file, 'Creating .sddraft file')
# Create service definition draft (.sddraft)
arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, service, 'ARCGIS_SERVER',
con, True, None, summary, tags)
log.write_log(python_file, 'Analyzing the .sddraft file for errors')
# Analyze the service definition draft
analysis = arcpy.mapping.AnalyzeForSD(sddraft)
# Print errors, warnings, and messages returned from the analysis
try:
for key in 'errors': # 'messages', 'warnings'): # This is commented out for clarity
log.write_log(python_file, "--------" + key.upper() + "--------")
vars = analysis[key]
for ((message, code), layerlist) in vars.iteritems():
log_message = " ", message, " (CODE %i)" % code
log.write_log(python_file, log_message)
log.write_log(python_file, " applies to:", )
for layer in layerlist:
log.write_log(python_file, '\n ' + str(layer.name), )
log.write_log(python_file, "")
except:
log.write_log(python_file, 'Ironically, there was an error printing the errors')
print 'Ironically, there was an error printing the errors in the publish_services() module'
err = True
# remove file if it already exists,
# need the folder to be cleared before creating again
del_sd()
# Stage and upload the service if the sddraft analysis did not contain errors
if analysis['errors'] == {} or err is False:
# Execute StageService
arcpy.StageService_server(sddraft, sd)
# Execute UploadServiceDefinition
arcpy.UploadServiceDefinition_server(sd, con)
log.write_log(python_file, "Service %s successfully published" % service)
else:
# if the sddraft analysis contained errors, display them
log.write_log(python_file, str(analysis['errors']))
log.write_log(python_file, "Service %s could not be published because errors were found during analysis."
% service
)
# remove the temporary file once tasks complete
del_sd()
else:
pass
... View more
07-06-2016
01:38 AM
|
0
|
11
|
8946
|
|
POST
|
You are correct, I can delete these files and recreate (time consuming and annoying), and I can script this, but that can be time consuming and that defeats the purpose of me using model builder for 'quick' processes like this. The shape files are being referenced in AutoCAD files by people in other departments, they are not continually being used, and the chances of someone referencing them and locking them when I run the tool are slim.
... View more
06-28-2016
06:00 PM
|
1
|
0
|
1502
|
| Title | Kudos | Posted |
|---|---|---|
| 1 | 10-17-2018 08:51 PM | |
| 1 | 09-23-2018 07:38 PM | |
| 1 | 04-08-2019 10:05 PM | |
| 1 | 02-03-2019 03:06 PM | |
| 1 | 12-20-2019 07:16 PM |
| Online Status |
Offline
|
| Date Last Visited |
11-11-2020
02:24 AM
|