Generating shapefiles from WKT format polygons using Arcpy? - arcpy

I am working with a database containing a geography field representing the Admin1 boundaries of countries. I would like to draw a map of the Admin1 boundaries of Somalia:
params = urllib.quote_plus(...)
engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
query = ("SELECT SimplifiedCoords.STAsText() FROM Adm1GeoBoundaries WHERE (Adm0Code = '226')")
df = pd.read_sql(query,engine)
this returns a list of the 18 subdivisions, e.g.:
0 POLYGON ((44.661 3.2516, 44.611 3.2715, 44.410...
1 POLYGON ((49.0611 9.571, 48.561 9.541, 48.061 ...
2 POLYGON ((44.2362 10.4724, 44.2021 10.5066, 44...
My issue now is to convert these into shapefiles in order to map them using arcpy. So far I have tried:
wkt = (df.loc[1]).to_string() # I only focus on one to test
g1 = loads(wkt)
But this throws :
"ParseException: Expected number but encountered word: '46.151...'"
I also tried the following:
sr = arcpy.SpatialReference(4326)
g1 = arcpy.FromWKT(wkt,sr)
But this has not led me anywhere yet... Any idea / advise welcome. Thanks in advance :)


How to convert query string to Map in Groovy

I would like to split the below query string with ; delimiter and convert to a map. So that I can access the values iPhone, 6s Plus and 2016 by using the key.
def query = type=iPhone;modelName=6s Plus;year=2016
def result = query .split(';')
println result
I want to access the value like this - result.getAt('type'), result.getAt('modelName')
I tried the below approach - but it's not working as expected
Map<String,String> response = result.collectEntries{
How can I achieve this in Groovy?
Shortest version I know looks like this:
def query = 'type=iPhone;modelName=6s Plus;year=2016'
def map = query.tokenize(';')*.tokenize('=').collectEntries()
println map.modelName // => 6s Plus
The algorithm in depth:
the first tokenize splits input string into a list of 3 strings
['type=iPhone', 'modelName=6s Plus', 'year=2016']
next we call tokenize on every element from that list to split it using = as a delimiter to a list of two string elements, like:
[['type', 'iPhone'], ['modelName', '6s Plus'], ['year', '2016']]
in the end we call collectEntries() - if no argument is passed it expects a list of size 2 where the first element is a key and the second element is the value of a map entry
['type':'iPhone', 'modelName':'6s Plus', 'year':'2016']
finally, you get a map from the query string and you can simply access every map entry by key.
def x = "type=iPhone;modelName=6s Plus;year=2016"
def m = x.split(';').collectEntries{it.split('=') as List}
println m.modelName

Getting classification result from mahout

Finally I am able to train mahout classifier , now my problem is how can i get target category for my input document.
What is the process of getting target category for my text documents ?
First, you have to vectorize the text document, RandomAccessSparseVector.
Some sample code for your reference:
Vector vector = new RandomAccessSparseVector(FEATURES);
FeatureExtractor fe = new FeatureExtractor();
HashSet<String> fs = fe.extract(text);
for (String s : fs) {
int index = dictionary.get(s);
vector.setQuick(index, frequency.get(index));
Then, use the Classifier.classify(Vector) to get the result.

Is language conditional in some operations?

I'm developing an app where I use the Geocoder to get a place's coordinates.
The operative is this:
The user defines an address.
The geocoder finds that address and I get the coordinates from that address.
This coordinates are in decimal format and I need them in degrees-minutos so I format them.
To format the coordinates from decimal to degrees-minutes I use:
String frmtLatitude = Location.convert(Double.parseDouble(lat), Location.FORMAT_MINUTES);
So, if I have for example this latitude 43.249591 in decimal value, it returns it like this 43:14.97546.
After this, I have to make some operations to finally get the latitude with this appearance: 4314.975
When I do this operations, one of them is to split the value using the ".". I split 14.97546 to get in one hand the 14 and in the other 97546.
Until here, everything ok. It works fine when I have my phone's language selected to be in english. But if I select to be in spanish, the app crashes. I have followed the stacktrace and it points there. Is like that in english when using the first commented function to convert from decimal to degrees-minutes it separates the decimals with a "." but if I have it in spanish, it separates them with a ",".
Can this really happen or the cause could be another thing?
We can look at the source code of the convert method
public static String convert(double coordinate, int outputType) {
if (coordinate < -180.0 || coordinate > 180.0 ||
Double.isNaN(coordinate)) {
throw new IllegalArgumentException("coordinate=" + coordinate);
if ((outputType != FORMAT_DEGREES) &&
(outputType != FORMAT_MINUTES) &&
(outputType != FORMAT_SECONDS)) {
throw new IllegalArgumentException("outputType=" + outputType);
StringBuilder sb = new StringBuilder();
// Handle negative values
if (coordinate < 0) {
coordinate = -coordinate;
DecimalFormat df = new DecimalFormat("###.#####");
if (outputType == FORMAT_MINUTES || outputType == FORMAT_SECONDS) {
int degrees = (int) Math.floor(coordinate);
coordinate -= degrees;
coordinate *= 60.0;
if (outputType == FORMAT_SECONDS) {
int minutes = (int) Math.floor(coordinate);
coordinate -= minutes;
coordinate *= 60.0;
return sb.toString();
We can see that it uses a DecimalFormat with a given pattern. So, if we look to the DecimalFormat constructor :
public DecimalFormat(String pattern) {
// Always applyPattern after the symbols are set
this.symbols = new DecimalFormatSymbols(Locale.getDefault());
applyPattern(pattern, false);
We can see here that even if we give a pattern, it uses the locale values. The javadoc also said :
pattern A non-localized pattern string.
To finish, we can go here to see the different local variant of numbers representation :
So we can see that US-English use the "dot format" and that Spanish use "comma format".
To answer your question : the proflem you're facing is probably due to the Decimal format of your locale. I advice you to be REALLY CAREFUL when converting types of objects to make manipulation on them. Converting an int to a String should be only to display it.
I think you should seperate decimal part of your number when it stills a float (or any decimal type) and then convert your object to a String to display it. You can take a look at Math class or search SO to get some example on how to this ;)
Also, as #Dmitry said, you can get DecimalSeparator with DecimalFormatSymbols.getDecimalSeparator().
Location.convert(double,int) source code
DecimalFormat(String) source code
Java "Decimal and thousands separators"
You are right, decimal seperator depends on your locale. You can get it by something like this
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols formatSymbols = df.getDecimalFormatSymbols();
char separator = formatSymbols.getDecimalSeparator();

Python: Class substantiation

I want to be able to open up a file like this:
42.65 42.75
-72.85 -72.75
TW52 42.73 -72.84 2.1
TW98 42.727 -72.81 2.9
TW2a 42.688 -72.82 1.1
CT4b 42.715 -72.78 2.4
CT5c 42.682 -72.779 2.41
I want to do this using a class, but I am not sure how I would approach it... so far I have this
class Homework:
fname = raw_input("Enter the name of the input file ==> ")
in_file = open(fname, "r")
def __init__(self, in_file):
self.in_file[0] = pID
self.in_file[1] = latitude
self.in_file[2] = longitude
self.in_file[3] = distance
def displayFile(self):
print self.in_file[0], self.in_file[1], self.in_file[2], self.in_file[3]
x = Homework()
print x.displayFile()
The first two lines, I want to be able to store them somewhere for later usage, and then the remainder into pID, latitude, longitude, and distance.
I want to be able to store the 0th index: TW52 to an object like pID and store the 1st index: 42.73 to latitude, -72.84 to longitude, and 2.1 to distance.
How would I be able to do this?
I get the error where it tells me that init takes exactly 2 arguments when only 1 is given!
Any help is appreciated!
Your error says that __init__ takes two arguments, but you only gave it one (self is passed automatically). You never passed anything for the in_file argument:
in_file = open(filename, "r")
x = Homework(in_file)
I suggest you read through a Python tutorial before jumping into classes. You seem to be assigning variables backwards.

Extracting substring

i have some problems extracting strings
i am making a multiple choice with 4 choices (e.g. as buttons), with the choices by referencing to the filename. The file (i.e. the question) is a png and the filename is Number-Q01AZ7BZ8CZ9DZ10ANZ8.png. These png are put under assets folder.
Set<String> regions = regionsMap.keySet(); // get Set of regions
// loop through each region
for (String region : regions)
if (regionsMap.get(region)) // if region is enabled
// get a list of all flag image files in this region
String[] paths = assets.list(region);
for (String path : paths)
fileNameList.add(path.replace(".png", ""));
} // end if
} // end for
String fileName = fileNameList.get(randomIndex);
if (!quizCountriesList.contains(fileName))
quizCountriesList.add(fileName); // add the file to the list
String nextImageName = quizCountriesList.remove(0);
correctAnswer = nextImageName; // update the correct answer
int AZ = correctAnswer.indexOf("AZ");
int BZ = correctAnswer.indexOf("BZ");
int CZ = correctAnswer.indexOf("CZ");
int DZ = correctAnswer.indexOf("DZ");
int ANZ = correctAnswer.indexOf("ANZ");
String choiceA = null;
String choiceB = null;
String choiceC = null;
String choiceD = null;
choiceA = correctAnswer.substring( (AZ+2), (BZ) );
choiceB = correctAnswer.substring( (BZ+2), (CZ) );
choiceC = correctAnswer.substring( (CZ+2), (DZ) );
choiceD = correctAnswer.substring( (DZ+2), (ANZ) );
The logcat is as follows:
11-09 21:14:08.495: E/AndroidRuntime(25905): FATAL EXCEPTION: main
11-09 21:14:08.495: E/AndroidRuntime(25905): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.trial.quizgame/com.trial.quizgame.QuizGame}: java.lang.StringIndexOutOfBoundsException: length=15; regionStart=1; regionLength=-2
11-09 21:14:08.495: E/AndroidRuntime(25905): at
I have tried to set the buttons as .setText(correctAnswer) and it will correctly show as Number-Q01AZ7BZ8CZ9DZ10ANZ8, so the top part of getting the String for "correctAnswer" should be ok. The problem left at extracting strings, yet BZ must be at a position behind AZ, so as CZ behind BZ, etc:
From the logcat the regionLength is -2? How could I handle this?
I would like it to be for Q01, choice A=7, B=8, C=9, D=10 and ANZ=8
thanks in advance for your advice!
Your assumption on the strings value is wrong. This code, if AZ, BZ, CZ, DZ, ANZ is present, should run with no error.
Either run debugger as advised in comments, or use android logcat to provide some debugging context. android.utils.Log.d("APP", String.format("AZ=%d", AZ));
How you store your data is not a big deal. You can tune it for days... You could create xml files that contain the name of the image, and the four possible answers... You can use the underscore approach, you can stay with your current one. Til it is only used by you, it doesn't really matter. You should just keep it simple. More complex => more chance for bugs...
So I'd advise reading about debugging and logging instead of refining the way you store the information... Storing it in the filename, that's a smart idea, quick and efficient, an ideal hack...