|
POST
|
Hello Kelly Hutchins and anyone who made this work, I have a similar problem. I'm trying to Geocoder widget to search for places in the United Kingdom but the suggestions include results from other countries. This is how I configured the Geocoder widget: // create geocoder widget
var geocoder = new Geocoder({
map: map,
autoComplete: true,
esriGeocoder: {
name: "Esri World Geocoder",
placeholder: "Search places...",
searchExtent: new geometry.Extent(-10.0, 50.0, 5.0, 62.0, { "wkid": 4326 }),
sourceCountry: "GBR"
}
}, node.attr('id'));
geocoder.startup(); And this is what I see in the map: I tried searchExtent: map.extent too but it made no difference. I tried adding suffix: ", United Kingdom" but it had no effect either. Any advice will be much appreciated. Filip.
... View more
01-13-2015
07:27 AM
|
0
|
4
|
5938
|
|
POST
|
Hi Cameron, We had a situation when services turned off and didn't restart (even though all relevant settings seemed fine). To get a warning that something was wrong, we set up a cron job (i.e. scheduled task) on one of our linux machines. Every hour, the job runs a python script which pokes the services and see if they are running. The python script requires a list of expected services of course. If any services don't respond, the script sends an email with the list of services that did not respond to our ArcGIS Server admin who can investigate further. I believe there are more elegant solutions but this is how we dealt with it at least for now. Filip.
... View more
01-09-2015
02:49 PM
|
0
|
1
|
781
|
|
POST
|
Hi, you should be able to do create simple line features from multi-line features using the Dissolve tool. provided that the vertices are close enough (tweak cluster tolerance environment setting if necessary). Select the object ID field to dissolve by and tick the dissolve lines box. Regards, Filip.
... View more
01-09-2015
02:30 PM
|
1
|
0
|
998
|
|
POST
|
Hi John, I am glad you made it work. To insert syntax highlighted code into this forum you have to use the advanced editor when you are editing the message. The advanced editor is available only if you are writing answer on the page dedicated to the thread (in this case that is https://community.esri.com/thread/119510 . After you click "Reply" or "Reply to original post", click "Use advanced editor" in the top right corner of the simple editor. In the advanced editor, paste in your code, select it and click on the insert button (looks like this: ">>"), then click "Syntax Highlighting" and choose the appropriate language. You may need to delete some extra empty rows once the code is highlighted. So... yes, it is a pretty convoluted process. Perhaps it will be more straightforward in some future versions of GeoNet. I am sure there is a thread dedicated to this topic. Filip.
... View more
01-09-2015
02:18 PM
|
0
|
0
|
1195
|
|
POST
|
I am not aware of any ArcGIS Geoprocessing tool that does that but if you know little bit of Python, the following answer should help: How do I download a file over HTTP using Python? - Stack Overflow In any case, try to be gentle with automated download so you don't take the service down or deny the service to other people by accident. If the information you need is already in the RSS feed, writing a new shapefile based on the RSS feed might be a more elegant option.
... View more
01-08-2015
04:30 PM
|
0
|
1
|
877
|
|
POST
|
Hi, it does indeed suggest that the problem may be in the sql statement. Maybe you can print(sql) before arcpy.analysis.Select to see if it is correct. Try to paste some of the print outs here so we can try to spot some problems. Filip.
... View more
01-08-2015
01:16 PM
|
0
|
0
|
4238
|
|
POST
|
Hi John, It seems to me that whatever you are trying to achieve with this, there might be an easier way. If you give it one more round of thought and still want to get on with what you described, perhaps the code below can help. I didn't test it because I had no sample data so it may contain some typos or glitches. If you understand the code though, you should be able get the job done. Hope this helps. Filip. # Given that species number is unique for each row in the table: import arcpy
# parameters
in_table = r'c:\full\path\to\table'
in_fc = r'c:\full\path\to\polygon_fc'
out_folder = r'c:\full\path\to\output\folder'
polygon_code_field = "Code"
# list all fields from the table
all_fields = [f.name for f in arcpy.ListFields(in_table)]
# loop through all rows in table
with arcpy.da.SearchCursor(in_table, '*') as sc:
for row in sc:
item = dict(zip(all_fields, row)) # represent row as a dictionary
species_number = item.get('SpeciesNum', 0)
species_name = item.get('Sci_Name', 'Uknown')
# get list of polygon codes that should be selected
polygons_to_select = []
for field_name, value in item.iteritems():
field_name_lower = field_name.lower() # to make comparison case insensitive
if field_name_lower.startswith('sum_') and value == 1:
polygon_code = field_name_lower.replace('sum_', '')
polygons_to_select.append(polygon_code)
if polygons_to_select:
# create a string like "'A1','B2',..."
codes = ",".join(["'" + str(pg) + "'" for pg in polygons_to_select])
# build an SQL expression
sql = '"%s" IN (%s)' % (polygon_code_field, codes)
# export as a new shapefile with species_name in the file name
out_fc = os.path.join(out_folder, "spp_" + species_name)
out_fc = arcpy.analysis.Select(in_fc, out_fc, sql).getOutput(0)
# add the column with species number as string
arcpy.management.AddField(out_fc, "SpeciesNum", "TEXT")
arcpy.management.CalculateField(out_fc, "SpeciesNum", "'" + str(species_number) + "'")
# It seems to me it would be better to use species number in file name
# and to add column with species name though.
else:
# no Sum_* column contains 1 for this species, skip this species
pass
# or you may want to create an empty shapefile
... View more
01-07-2015
04:01 PM
|
2
|
3
|
4238
|
|
POST
|
Did you try geoprocessing tools like "Spatial Join" or "Intersect" from the Analysis tool box?
... View more
01-07-2015
03:17 PM
|
0
|
0
|
695
|
|
POST
|
Hi Larry, Thanks for the tip about urllib2. It is true that working with urllib2 is a bit awkward but exactly this awkwardness is removed if you use my arrest.py. More serious issues I've had with urllib2 were related to requesting data from https with self signed certificate. I would prefer the requests package but I didn't want to add a dependency on an external package. Is requests part of core Python in 3.x? I also looked at the script to collect stats of all services you referred to and translated it into a function below. I could not test it because I don't have admin credentials to any server I can reach at the moment. Can you check if it works? Filip. """Queries the logs and writes statistics on map service activity.
Modified version of script available on ArcGIS Help:
http://resources.arcgis.com/en/help/main/10.2/index.html#/Example_Derive_map_service_statistics_from_the_ArcGIS_Server_logs/0154000005vw000000/
To try this example, follow these steps:
1) Publish several map services (without defining tile caches for them).
2) Set the ArcGIS Server log level to FINE.
3) Make some draw requests of your services by adding them to ArcMap etc.
4) Run this script and examine the resulting text file.
"""
import httplib, urllib, json
import sys, time
def collect_services_statistics(server_name, output_file, username, password, hours=24, port=6080):
"""Query ArcGIS Server logs and write a summary of all map service draws.
server_name -- e.g.
output_file -- path of the text file where the statistics should be written
username, password -- credentials for the server admin rest interface
hours=24 -- result will include summary for this number of the last hours
port=6080 -- arcgis server port number
"""
def assertJsonSuccess(data):
"""Check that the input JSON object is not an error object."""
obj = json.loads(data)
if 'status' in obj and obj['status'] == "error":
print "Error: JSON object returns an error. " + str(obj)
return False
else:
return True
def getToken(username, password, server_name, port):
"""Generate a token given username, password and the adminURL."""
# Token URL is typically http://server[:port]/arcgis/admin/generateToken
tokenURL = "/arcgis/admin/generateToken"
# URL-encode the token parameters
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(server_name, port)
httpConn.request("POST", tokenURL, params, headers)
# Read response
response = httpConn.getresponse()
if (response.status != 200):
httpConn.close()
raise Exception("Unable to fetch token, check the URL and try again.")
else:
data = response.read()
httpConn.close()
# Check that data returned is not an error object
if not assertJsonSuccess(data):
return
# Extract the toke from it
token = json.loads(data)
return token['token']
millisecondsToQuery = hours * 60 * 60 * 100 # 86400000 is 1 day
hitDict = {}
# Get a token
token = getToken(username, password, server_name, port)
if token == "":
raise Exception("Could not generate a token using the credentials.")
# Construct URL to query the logs
logQueryURL = "/arcgis/admin/logs/query" # is this going to work in future?
startTime = int(round(time.time() * 1000))
endTime = startTime - millisecondsToQuery
logFilter = "{'services':'*','server':'*','machines':'*'}"
params = urllib.urlencode({
'level': 'FINE',
'startTime': startTime,
'endTime': endTime,
'filter':logFilter,
'token': token,
'f': 'json'
})
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"
}
# Connect to URL and post parameters
httpConn = httplib.HTTPConnection(server_name, port)
httpConn.request("POST", logQueryURL, params, headers)
# Read response
response = httpConn.getresponse()
if (response.status != 200):
httpConn.close()
raise Exception("Error while querying logs.")
else:
data = response.read()
# Check that data returned is not an error object
if not assertJsonSuccess(data):
raise Exception("Error returned by operation. " + data)
# Deserialize response into Python object
dataObj = json.loads(data)
httpConn.close()
# Need these to calculate average draw time for an ExportMapImage call
mapDraws = 0
totalDrawTime = 0
# Iterate over messages
for item in dataObj["logMessages"]:
if item["message"] == "End ExportMapImage":
elapsed = float(item["elapsed"])
keyCheck = item["source"]
if keyCheck in hitDict:
stats = hitDict[keyCheck]
stats[0] += 1 # Add 1 to tally of hits
stats[1] += elapsed # Add elapsed time to total elapsed time
else:
# Add key with one hit and total elapsed time
hitDict[keyCheck] = [1, elapsed]
# Open text file and write header line
with open(output_file, "w") as summaryFile:
header = "Service,Number of hits,Average seconds per draw\n"
summaryFile.write(header)
# Read through dictionary and write totals into file
for key in hitDict:
# Calculate average elapsed time
totalDraws = hitDict[key][0]
totalElapsed = hitDict[key][1]
avgElapsed = 0
if totalDraws > 0:
#Elapsed time divided by hits
avgElapsed = (1.0 * (totalElapsed / totalDraws))
# Construct and write the comma-separated line
line = key + "," + str(totalDraws) + "," + str(avgElapsed) + "\n"
summaryFile.write(line)
return summaryFile
if __name__ == "__main__":
server_name = 'http://sampleserver5.arcgisonline.com'
output_file = 'c:/temp/summary.csv'
username, password = "that_is_what", "i_do_not_know"
collect_services_statistics(server_name, output_file, username, password, hours=24, port=6080)
... View more
11-29-2014
11:41 AM
|
0
|
0
|
2831
|
|
POST
|
Thank you both ever so much! The problem in the example I posted was indeed in the spatial reference definition. In fact, my original problem was that I created a new graphics layer and added my graphics into it. But I forgot to add this new graphics layer to the map! So I explored more and more with no success and ended up completely lost. Many thanks again! Filip.
... View more
10-29-2014
09:42 AM
|
0
|
0
|
2104
|
|
POST
|
Hello, I cannot figure out what am I doing wrong while adding a point graphic to a map. I have searched fora, samples, and help, but still cannot crack it. Below is code for an elementary example of adding a single point graphic. The graphic ends up in map.graphics.graphics.array, but it is not visible on the map. Can you see what is wrong with it? I am guessing the symbol is not right but nothing I tried worked. Many thanks, Filip.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>
<title>Add Graphic to a Map</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.11/esri/css/esri.css">
<style type="text/css" media="screen">
#map{
height: 500px;
width: 100%;
}
</style>
script src="http://js.arcgis.com/3.11/"></script>
</head>
<body>
<div id="map"></div>
<script>
var map;
require([
"esri/map",
"esri/symbols/SimpleMarkerSymbol",
"esri/graphic",
"esri/dijit/Popup",
"esri/Color",
"esri/InfoTemplate",
"esri/geometry/Point",
"dojo/dom-construct",
"dojo/domReady!"
], function (
Map,
SimpleMarkerSymbol,
Graphic,
Popup,
Color,
InfoTemplate,
Point,
domConstruct
) {
map = new Map("map", { basemap: "topo", center: [-120.45, 45.75], zoom: 7 });
map.on("load", function () {
var pt = new Point(-120.0, 45.4, { wkid: 4326 });
var sms = new SimpleMarkerSymbol().setStyle(SimpleMarkerSymbol.STYLE_CIRCLE).setColor(new Color([255, 0, 0]));
var attr = { "Plant": "Mesa Mint" };
var infoTemplate = new InfoTemplate("Vernal Pool Locations", "$(Plant)");
var graphic = new Graphic(pt, sms, attr, infoTemplate);
map.graphics.add(graphic);
});
});
</script>
</body>
</html>
... View more
10-29-2014
08:50 AM
|
1
|
4
|
2559
|
|
POST
|
Hi larry zhang, you seem to be able to use the code you referred to but I couldn't make it work. What version of ArcGIS Server did you use? I thought the /arcgis/admin end point has been changed. Anyhow, I suppose general users don't have credentials for it anyway. I tried to experiment with the following 10.2.x servers. http://sampleserver5.arcgisonline.com/arcgis/rest/ (I have no credentials to this one but I couldn't even find the end points) https://datahub.esriuk.com/arcgis/rest/ (I managed to generate token from https://datahub.esriuk.com/arcgis/tokens/generateToken but I cannot see any admin interface. Here is the function I tried to get token with. Hopefully I'll figure out some way of using it to access secured services with arcapi/arrest.py.
import urllib2
import urllib
import json
from contextlib import closing
def generateToken(url, username, password):
params = urllib.urlencode({'username': username, 'password': password, 'client': 'requestip', 'f': 'json'})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
req = urllib2.Request(url, params, headers)
with closing(urllib2.urlopen(req)) as res:
dta = res.read()
jsn = json.loads(dta)
return jsn.get('token')
username,password = '***', '***'
url = "https://datahub.esriuk.com/arcgis/tokens/generateToken"
token = generateToken(url, username, password)
Regards, Filip.
... View more
09-24-2014
01:22 PM
|
0
|
0
|
2831
|
|
POST
|
Oh, thanks for the tip, Larry. The element of authentication makes it slightly more complex but I'll consider it if I can make a nice simple function out of it. F.
... View more
09-20-2014
02:20 PM
|
0
|
0
|
2831
|
|
POST
|
How about something like the code below?
# input table (must be geodatabase to allow sorting)
tbl = r'C:\TEMP\tdb.gdb\sorting'
# add column to record the change
arcpy.management.AddField(tbl, "changed", "SHORT")
orderby = 'ORDER BY line_id, theyear, thecode'
last_id, last_code = None, None
with arcpy.da.UpdateCursor(tbl, ['line_id', 'theyear', 'thecode', 'changed'], sql_clause=(None, orderby)) as uc:
for row in uc:
this_id, this_year, this_code, changed = row
if this_id == last_id:
if last_code != this_code:
newrow = [this_id, this_year, this_code, 1] # change!
uc.updateRow(newrow) #save
last_id, last_code = this_id, this_code
... View more
09-18-2014
07:40 AM
|
0
|
1
|
2155
|
|
POST
|
Hello, I need to to provide secured ArcGIS for Server services in a wider system (portal of portals) with only a single sign on. These services will be consumed by an ArcGIS API for JavaScript web application. The authentication tool used by the system is Atlassian Crowd . The way I understand it is that the user signed onto the Atlassian Crowd service. Atlassian Crowd verifies users identity and issues a token. Each subsequent request is routed via the Atlassian Crowd along with the token to ensure the token is valid and up to date. Does anyone have any experience with this kind of authentication? Can you point me to some help topics or resources to get me going please? How far is it from OAuth2? Any pointers welcome. Filip.
... View more
09-17-2014
07:23 AM
|
0
|
0
|
2742
|
| Title | Kudos | Posted |
|---|---|---|
| 1 | 02-05-2014 04:40 AM | |
| 1 | 02-08-2015 12:49 PM | |
| 1 | 07-20-2014 12:41 PM | |
| 1 | 03-23-2017 01:48 PM | |
| 1 | 08-18-2014 04:14 PM |
| Online Status |
Offline
|
| Date Last Visited |
11-11-2020
02:23 AM
|