[GRASS-SVN] r62282 - in grass/trunk: general/g.list lib/python/script vector/v.what

svn_grass at osgeo.org svn_grass at osgeo.org
Fri Oct 17 13:53:44 PDT 2014


Author: annakrat
Date: 2014-10-17 13:53:44 -0700 (Fri, 17 Oct 2014)
New Revision: 62282

Modified:
   grass/trunk/general/g.list/main.c
   grass/trunk/lib/python/script/vector.py
   grass/trunk/vector/v.what/main.c
   grass/trunk/vector/v.what/what.c
   grass/trunk/vector/v.what/what.h
Log:
partially revert r62281 (committed by mistake)

Modified: grass/trunk/general/g.list/main.c
===================================================================
--- grass/trunk/general/g.list/main.c	2014-10-17 20:42:22 UTC (rev 62281)
+++ grass/trunk/general/g.list/main.c	2014-10-17 20:53:44 UTC (rev 62282)
@@ -93,7 +93,7 @@
     opt.pattern->type = TYPE_STRING;
     opt.pattern->required = NO;
     opt.pattern->multiple = NO;
-    opt.pattern->gisprompt = "old,element,element";
+    opt.pattern->gisprompt = "new,element,element";
     opt.pattern->description = _("Map name search pattern (default: all)");
     opt.pattern->guisection = _("Pattern");
 

Modified: grass/trunk/lib/python/script/vector.py
===================================================================
--- grass/trunk/lib/python/script/vector.py	2014-10-17 20:42:22 UTC (rev 62281)
+++ grass/trunk/lib/python/script/vector.py	2014-10-17 20:53:44 UTC (rev 62282)
@@ -258,11 +258,7 @@
     return {'columns': columns, 'values': values}
 
 
-json = None
-orderedDict = None
-
-
-def vector_what(map, coord, distance=0.0, ttype=None, encoding=None):
+def vector_what(map, coord, distance=0.0, ttype=None):
     """Query vector map at given locations
 
     To query one vector map at one location
@@ -340,7 +336,7 @@
             coord_list.append('%f,%f' % (e, n))
 
     cmdParams = dict(quiet      = True,
-                     flags      = 'aj',
+                     flags      = 'ag',
                      map        = ','.join(map_list),
                      layer      = ','.join(layer_list),
                      coordinates = ','.join(coord_list),
@@ -349,7 +345,7 @@
         cmdParams['type'] = ','.join(ttype)
 
     ret = read_command('v.what',
-                       **cmdParams).strip()
+                       **cmdParams)
 
     if "LC_ALL" in os.environ:
         os.environ["LC_ALL"] = locale
@@ -358,31 +354,62 @@
     if not ret:
         return data
 
-    # lazy import
-    global json
-    global orderedDict
-    if json is None:
-        import json
-    if orderedDict is None:
+    # parse `v.what -g` output is a nightmare
+    # TODO: change `v.what -g` format or add parsable format (e.g. XML)
+    dict_attrb = None
+    dict_map = None
+    dict_layer = None
+    attr_pseudo_key = 'Attributes'
+    for item in ret.splitlines():
         try:
-            from collections import OrderedDict
-            orderedDict = OrderedDict
-        except ImportError:
-            orderedDict = dict
+            key, value = __builtin__.map(lambda x: x.strip(), item.split('=', 1))
+        except ValueError:
+            continue
+        if key in ('East', 'North'):
+            continue
 
-    if encoding:
-        result = json.loads(ret, object_pairs_hook=orderedDict, encoding=encoding)
-    else:
-        result = json.loads(ret, object_pairs_hook=orderedDict)
-    del result['Coordinates']
-    for vmap in result['Maps']:
-        cats = vmap.pop('Categories', None)
-        if cats:
-            for cat in cats:
-                tmp = vmap.copy()
-                tmp.update(cat)
-                data.append(tmp)
+        if key == 'Map':
+            # attach the last one from the previous map
+            if dict_map is not None:
+                dict_main = copy.copy(dict_map)
+                if dict_layer is not None:
+                    dict_main.update(dict_layer)
+                data.append(dict_main)
+            dict_map = {key : value}
+            dict_layer = None
+            dict_attrb = None
+        elif key == 'Layer':
+            if not dict_attrb:
+                # attach the last the previous Layer
+                if dict_layer is not None:
+                    dict_main = copy.copy(dict_map)
+                    dict_main.update(dict_layer)
+                    data.append(dict_main)
+                dict_layer = {key: int(value)}
+                dict_attrb = None
+            else:
+                dict_attrb[key] = value
+        elif key == 'Key_column':
+            dict_layer[key] = value
+            dict_attrb = dict()
+            dict_layer[attr_pseudo_key] = dict_attrb
+        elif dict_attrb is not None:
+            dict_attrb[key] = value
+        elif dict_layer is not None:
+            if key == 'Category':
+                dict_layer[key] = int(value)
+            else:
+                dict_layer[key] = value
         else:
-            data.append(vmap)
+            dict_map[key] = value
+            # TODO: there are some keys which has non-string values
+            # examples: Sq_Meters, Hectares, Acres, Sq_Miles
 
+    # attach the last one
+    if dict_map is not None:
+        dict_main = copy.copy(dict_map)
+        if dict_layer:
+            dict_main.update(dict_layer)
+        data.append(dict_main)
+
     return data

Modified: grass/trunk/vector/v.what/main.c
===================================================================
--- grass/trunk/vector/v.what/main.c	2014-10-17 20:42:22 UTC (rev 62281)
+++ grass/trunk/vector/v.what/main.c	2014-10-17 20:53:44 UTC (rev 62282)
@@ -33,7 +33,7 @@
 int main(int argc, char **argv)
 {
     struct {
-	struct Flag *print, *topo, *shell, *json;
+	struct Flag *print, *topo, *shell;
     } flag;
     struct {
 	struct Option *map, *field, *coords, *maxdist, *type;
@@ -97,11 +97,6 @@
     flag.shell->key = 'g';
     flag.shell->description = _("Print the stats in shell script style");
     flag.shell->guisection = _("Print");
-    
-    flag.json = G_define_flag();
-    flag.json->key = 'j';
-    flag.json->description = _("Print the stats in JSON");
-    flag.json->guisection = _("Print");
 
     if (G_parser(argc, argv))
 	exit(EXIT_FAILURE);
@@ -117,9 +112,6 @@
     else
 	G_fatal_error(_("No input vector maps!"));
 
-    if (flag.shell->answer && flag.json->answer)
-        G_fatal_error(_("Flags g and j are mutually exclusive"));
-
     maxd = atof(opt.maxdist->answer);
     type = Vect_option_to_types(opt.type);
 
@@ -186,7 +178,7 @@
 	    ret = sscanf(buf, "%lf%c%lf", &xval, &ch, &yval);
 	    if (ret == 3 && (ch == ',' || ch == ' ' || ch == '\t')) {
 		what(Map, nvects, vect, xval, yval, maxd, type, flag.topo->answer,
-		     flag.print->answer, flag.shell->answer, flag.json->answer, field);
+		     flag.print->answer, flag.shell->answer, field);
 	    }
 	    else {
 		G_warning(_("Unknown input format, skipping: '%s'"), buf);
@@ -200,7 +192,7 @@
 	    xval = atof(opt.coords->answers[i]);
 	    yval = atof(opt.coords->answers[i + 1]);
 	    what(Map, nvects, vect, xval, yval, maxd, type, flag.topo->answer,
-		 flag.print->answer, flag.shell->answer, flag.json->answer, field);
+		 flag.print->answer, flag.shell->answer, field);
 	}
     }
 

Modified: grass/trunk/vector/v.what/what.c
===================================================================
--- grass/trunk/vector/v.what/what.c	2014-10-17 20:42:22 UTC (rev 62281)
+++ grass/trunk/vector/v.what/what.c	2014-10-17 20:53:44 UTC (rev 62282)
@@ -17,7 +17,7 @@
 
 static void F_generate(const char *drvname, const char *dbname,
 		       const char *tblname, const char *key, int keyval,
-		       int script, int json, char **form)
+		       char **form)
 {
     int col, ncols, sqltype, more;
     char buf[5000];
@@ -87,14 +87,8 @@
 	    colname = db_get_column_name(column);
 
 	    G_debug(2, "%s: %s", colname, db_get_string(&str));
-	    if (json) {
-		sprintf(buf, "%s\"%s\": \"%s\"", col == 0 ? "" : ",\n",
-			colname, db_get_string(&str));
-	    }
-	    else if (script)
-		sprintf(buf, "%s=%s\n", colname, db_get_string(&str));
-	    else
-		sprintf(buf, "%s : %s\n", colname, db_get_string(&str));
+
+	    sprintf(buf, "%s : %s\n", colname, db_get_string(&str));
 	    db_append_string(&html, buf);
 	}
     }
@@ -112,7 +106,7 @@
 }
 
 void what(struct Map_info *Map, int nvects, char **vect, double east, double north,
-          double maxdist, int qtype, int topo, int showextra, int script, int json, int *field)
+          double maxdist, int qtype, int topo, int showextra, int script, int *field)
 {
     int type;
     char east_buf[40], north_buf[40];
@@ -179,9 +173,6 @@
 		    fprintf(stdout, "East=%s\nNorth=%s\n", east_buf,
 			    north_buf);
 		}
-		else if (json){
-		    fprintf(stdout, "{\"Coordinates\": {\"East\": %s, \"North\": %s}", east_buf,
-			    north_buf);}
 		else {
 		    fprintf(stdout, "East: %s\nNorth: %s\n", east_buf,
 			    north_buf);
@@ -198,14 +189,6 @@
 	    fprintf(stdout, "\nMap=%s\nMapset=%s\n", Map[i].name,
 		    Map[i].mapset);
 	}
-	else if (json) {
-	    if (!i)
-		fprintf(stdout, ",\n\"Maps\":\n[{\"Map\": \"%s\",\n\"Mapset\": \"%s\"",
-			Map[i].name, Map[i].mapset);
-	    else
-		fprintf(stdout, ",\n{\"Map\": \"%s\",\n\"Mapset\": \"%s\"",
-			Map[i].name, Map[i].mapset);
-	}
 	else {
 	    fprintf(stdout, "%s", SEP);
 	    fprintf(stdout, "\nMap: %s \nMapset: %s\n", Map[i].name,
@@ -269,12 +252,6 @@
 			    "Id=%d\nType=%s\nLeft=%d\nRight=%d\n",
 			    line, buf, left, right);
 		}
-		else if (json) {
-		    fprintf(stdout, ",\n\"Feature_max_distance\": %f", maxdist);
-		    fprintf(stdout,
-			    ",\n\"Id\": %d,\n\"Type\": \"%s\",\n\"Left\": %d,\n\"Right\": %d",
-			    line, buf, left, right);
-		}
 		else {
 		    fprintf(stdout, "Looking for features within: %f\n",
 			    maxdist);
@@ -306,11 +283,6 @@
 				_("Node[%d]=%d\nNumber_lines=%d\nCoordinates=%.6f,%.6f,%.6f\n"),
 				n, node[n], nnlines, nx, ny, nz);
 		    }
-		    else if (json) {
-			fprintf(stdout,
-				_(",\n\"Node[%d]\": %d,\n\"Number_lines\": %d,\n\"Coordinates\": %.6f,%.6f,%.6f"),
-				n, node[n], nnlines, nx, ny, nz);
-		    }
 		    else {
 			fprintf(stdout,
 				_("Node[%d]: %d\nNumber of lines: %d\nCoordinates: %.6f, %.6f, %.6f\n"),
@@ -326,10 +298,6 @@
 			    fprintf(stdout, "Id=%5d\nAngle=%.8f\n",
 				    nodeline, angle);
 			}
-			else if (json) {
-			    fprintf(stdout, ",\n\"Id\": %5d,\n\"Angle\": %.8f",
-				    nodeline, angle);
-			}
 			else {
 			    fprintf(stdout, _("Id: %5d\nAngle: %.8f\n"),
 				    nodeline, angle);
@@ -345,12 +313,6 @@
 		    if (type & GV_LINES)
 			fprintf(stdout, "Length=%f\n", l);
 		}
-		else if (json) {
-		    fprintf(stdout, ",\n\"Type\": \"%s\"", buf);
-		    fprintf(stdout, ",\n\"Id\": %d", line);
-		    if (type & GV_LINES)
-			fprintf(stdout, ",\n\"Length\": %f", l);
-		}
 		else {
 		    fprintf(stdout, _("Type: %s\n"), buf);
 		    fprintf(stdout, _("Id: %d\n"), line);
@@ -368,9 +330,6 @@
 		    if (script) {
 			fprintf(stdout, "Point_height=%f\n", Points->z[0]);
 		    }
-		    else if (json) {
-			fprintf(stdout, ",\n\"Point_height\": %f", Points->z[0]);
-		    }
 		    else {
 			fprintf(stdout, _("Point height: %f\n"),
 				Points->z[0]);
@@ -388,9 +347,6 @@
 			if (script) {
 			    fprintf(stdout, "Line_height=%f\n", min);
 			}
-			else if (json) {
-			    fprintf(stdout, ",\n\"Line_height\": %f", min);
-			}
 			else {
 			    fprintf(stdout, _("Line height: %f\n"), min);
 			}
@@ -401,11 +357,6 @@
 				    "Line_height_min=%f\nLine_height_max=%f\n",
 				    min, max);
 			}
-			else if (json) {
-			    fprintf(stdout,
-				    ",\n\"Line_height_min\": %f,\n\"Line_height_max\": %f",
-				    min, max);
-			}
 			else {
 			    fprintf(stdout,
 				    _("Line height min: %f\nLine height max: %f\n"),
@@ -421,9 +372,6 @@
 		if (script) {
 		    fprintf(stdout, "Type=Area\nArea_height=%f\n", z);
 		}
-		else if (json) {
-		    fprintf(stdout, ",\n\"Type\": \"Area\",\n\"Area_height\": %f", z);
-		}
 		else {
 		fprintf(stdout, _("Type: Area\nArea height: %f\n"), z);
 		}
@@ -432,9 +380,6 @@
 		if (script) {
 		    fprintf(stdout, "Type=Area\n");
 		}
-		else if (json) {
-		    fprintf(stdout, ",\n\"Type\": \"Area\"");
-		}
 		else {
 		    fprintf(stdout, _("Type: Area\n"));
 		}
@@ -457,10 +402,6 @@
 		    fprintf(stdout, "Area=%d\nNumber_isles=%d\n", area,
 			    nisles);
 		}
-		else if (json) {
-		    fprintf(stdout, ",\n\"Area\": %d,\n\"Number_isles\": %d", area,
-			    nisles);
-		}
 		else {
 		    fprintf(stdout, _("Area: %d\nNumber of isles: %d\n"),
 			    area, nisles);
@@ -471,9 +412,6 @@
 		    if (script) {
 			fprintf(stdout, "Isle[%d]=%d\n", isleidx, isle);
 		    }
-		    else if (json) {
-			fprintf(stdout, ",\n\"Isle[%d]\": %d", isleidx, isle);
-		    }
 		    else {
 			fprintf(stdout, _("Isle[%d]: %d\n"), isleidx, isle);
 		    }
@@ -487,10 +425,6 @@
 			fprintf(stdout, "Island=%d\nIsland_area=%d\n", isle,
 				isle_area);
 		    }
-		    else if (json) {
-			fprintf(stdout, ",\n\"Island\": %d,\n\"Island_area\": %d", isle,
-				isle_area);
-		    }
 		    else {
 			fprintf(stdout, _("Island: %d In area: %d\n"), isle,
 				isle_area);
@@ -504,12 +438,6 @@
 		    fprintf(stdout, "Acres=%.3f\nSq_Miles=%.4f\n",
 			    acres, sq_miles);
 		}
-		else if (json) {
-		    fprintf(stdout, ",\n\"Sq_Meters\": %.3f,\n\"Hectares\": %.3f",
-			    sq_meters, hectares);
-		    fprintf(stdout, ",\n\"Acres\": %.3f,\n\"Sq_Miles\": %.4f",
-			    acres, sq_miles);
-		}
 		else {
 		    fprintf(stdout, _("Sq Meters: %.3f\nHectares: %.3f\n"),
 			    sq_meters, hectares);
@@ -526,10 +454,8 @@
 
 	if (Cats->n_cats > 0) {
 	    int j;
-	    char *formbuf1;
-	    if (json) {
-		fprintf(stdout, ",\n\"Categories\": [");
-	    }
+	    char *formbuf1, *formbuf2;
+
 	    for (j = 0; j < Cats->n_cats; j++) {
 		G_debug(2, "field = %d  category = %d\n", Cats->field[j],
 			Cats->cat[j]);
@@ -537,10 +463,6 @@
 		    fprintf(stdout, "Layer=%d\nCategory=%d\n", Cats->field[j],
 			    Cats->cat[j]);
 		}
-		else if (json) {
-		    fprintf(stdout, "%s\n{\"Layer\": %d, \"Category\": %d", j == 0 ? "": ",", 
-			    Cats->field[j], Cats->cat[j]);
-		}
 		else {
 		    fprintf(stdout, _("Layer: %d\nCategory: %d\n"),
 			    Cats->field[j], Cats->cat[j]);
@@ -552,46 +474,29 @@
 				"Driver=%s\nDatabase=%s\nTable=%s\nKey_column=%s\n",
 				Fi->driver, Fi->database, Fi->table, Fi->key);
 		    }
-		    else if (json) {
-			fprintf(stdout,
-				",\n\"Driver\": \"%s\",\n\"Database\": \"%s\",\n\"Table\": \"%s\",\n\"Key_column\": \"%s\"",
-				Fi->driver, Fi->database, Fi->table, Fi->key);
-		    }
 		    else {
 			fprintf(stdout,
 				_("\nDriver: %s\nDatabase: %s\nTable: %s\nKey column: %s\n"),
 				Fi->driver, Fi->database, Fi->table, Fi->key);
 		    }
 		    F_generate(Fi->driver, Fi->database, Fi->table,
-			       Fi->key, Cats->cat[j], script, json, &form);
+			       Fi->key, Cats->cat[j], &form);
 
 		    if (script) {
-			formbuf1 = G_str_replace(form, " ", "_");
-			fprintf(stdout, "%s", formbuf1);
+			formbuf1 = G_str_replace(form, " : ", "=");
+			formbuf2 = G_str_replace(formbuf1, " ", "_");
+			fprintf(stdout, "%s", formbuf2);
 			G_free(formbuf1);
+			G_free(formbuf2);
 		    }
-		    else if (json)
-			fprintf(stdout, ",\n\"Attributes\": {%s}", form);
 		    else
 			fprintf(stdout, "%s", form);
 		    G_free(form);
 		    G_free(Fi);
 		}
-		if (json) {
-		    fprintf(stdout, "}");
-		}
 	    }
-	    if (json) {
-		fprintf(stdout, "]");
-	    }
 	}
-	if (json) {
-	    fprintf(stdout, "}");
-	}
     }				/* for nvects */
-    if (json) {
-        fprintf(stdout, "]}\n");
-    }
 
     fflush(stdout);
 }

Modified: grass/trunk/vector/v.what/what.h
===================================================================
--- grass/trunk/vector/v.what/what.h	2014-10-17 20:42:22 UTC (rev 62281)
+++ grass/trunk/vector/v.what/what.h	2014-10-17 20:53:44 UTC (rev 62282)
@@ -1,3 +1,3 @@
 /* what.c */
 void what(struct Map_info *, int, char **,
-	  double, double, double, int, int, int, int, int, int *);
+	  double, double, double, int, int, int, int, int *);



More information about the grass-commit mailing list