[GRASS-SVN] r68358 - in grass/trunk/scripts: d.frame d.out.file d.polar d.to.rast d.what.rast d.what.vect g.extension g.manual r.in.wms r.tileset r3.in.xyz v.db.addtable v.db.reconnect.all v.in.wfs v.pack v.what.strds

svn_grass at osgeo.org svn_grass at osgeo.org
Mon May 2 09:08:34 PDT 2016


Author: zarch
Date: 2016-05-02 09:08:34 -0700 (Mon, 02 May 2016)
New Revision: 68358

Modified:
   grass/trunk/scripts/d.frame/d.frame.py
   grass/trunk/scripts/d.out.file/d.out.file.py
   grass/trunk/scripts/d.polar/d.polar.py
   grass/trunk/scripts/d.to.rast/d.to.rast.py
   grass/trunk/scripts/d.what.rast/d.what.rast.py
   grass/trunk/scripts/d.what.vect/d.what.vect.py
   grass/trunk/scripts/g.extension/g.extension.py
   grass/trunk/scripts/g.manual/g.manual.py
   grass/trunk/scripts/r.in.wms/wms_base.py
   grass/trunk/scripts/r.in.wms/wms_cap_parsers.py
   grass/trunk/scripts/r.in.wms/wms_drv.py
   grass/trunk/scripts/r.tileset/r.tileset.py
   grass/trunk/scripts/r3.in.xyz/r3.in.xyz.py
   grass/trunk/scripts/v.db.addtable/v.db.addtable.py
   grass/trunk/scripts/v.db.reconnect.all/v.db.reconnect.all.py
   grass/trunk/scripts/v.in.wfs/v.in.wfs.py
   grass/trunk/scripts/v.pack/v.pack.py
   grass/trunk/scripts/v.what.strds/v.what.strds.py
Log:
Fix conflicts during rebasing

Modified: grass/trunk/scripts/d.frame/d.frame.py
===================================================================
--- grass/trunk/scripts/d.frame/d.frame.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/d.frame/d.frame.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -152,7 +152,7 @@
 # calculate position of the frame in percent
 def calculate_frame(frame, at, width, height):
     try:
-        b, t, l, r = map(float, at.split(','))
+        b, t, l, r = list(map(float, at.split(',')))
     except:
         fatal(_("Invalid frame position: %s") % at)
 

Modified: grass/trunk/scripts/d.out.file/d.out.file.py
===================================================================
--- grass/trunk/scripts/d.out.file/d.out.file.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/d.out.file/d.out.file.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -47,7 +47,7 @@
     if 'MONITOR' in gisenv:
         cmd_file = gcore.parse_command('d.mon', flags='g')['cmd']
         dout_cmd = 'd.out.file'
-        for param, val in options.iteritems():
+        for param, val in options.items():
             if val:
                 dout_cmd += " {param}={val}".format(param=param, val=val)
         with open(cmd_file, "a") as file_:

Modified: grass/trunk/scripts/d.polar/d.polar.py
===================================================================
--- grass/trunk/scripts/d.polar/d.polar.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/d.polar/d.polar.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -62,10 +62,10 @@
     newline = ['\n']
     p = grass.Popen(['xgraph'], stdin = grass.PIPE)
     for point in sine_cosine_replic + newline + outercircle + newline + vector:
-	if isinstance(point, types.TupleType):
-	    p.stdin.write("%f %f\n" % point)
-	else:
-	    p.stdin.write(point + '\n')
+        if isinstance(point, tuple):
+            p.stdin.write("%f %f\n" % point)
+        else:
+            p.stdin.write(point + '\n')
     p.stdin.close()
     p.wait()
 
@@ -94,10 +94,9 @@
     scaleval = ring * totalvalidnumber / totalnumber
 
     sine_cosine_replic_normalized = [
-	((scaleval * p[0]/maxradius + 1)*50,
-	 (scaleval * p[1]/maxradius + 1)*50)
-	for p in sine_cosine_replic
-	if isinstance(p, types.TupleType)]
+        ((scaleval * p[0] / maxradius + 1) * 50,
+         (scaleval * p[1] / maxradius + 1) * 50)
+        for p in sine_cosine_replic if isinstance(p, tuple)]
 
     # create circle
     circle = [(50*(1 + ring * math.sin(math.radians(i))),
@@ -165,10 +164,10 @@
 
     p = grass.feed_command('d.graph', env = tenv)
     for point in lines:
-	if isinstance(point, types.TupleType):
-	    p.stdin.write("%f %f\n" % point)
-	else:
-	    p.stdin.write(point + '\n')
+        if isinstance(point, tuple):
+            p.stdin.write("%f %f\n" % point)
+        else:
+            p.stdin.write(point + '\n')
     p.stdin.close()
     p.wait()
 
@@ -199,14 +198,14 @@
     southjustification = 8
     westjustification = 8
 
-    northxshift = 1.02 * halfframe 
-    northyshift = 1.98 * halfframe 
-    eastxshift  = 1.98 * halfframe  
-    eastyshift  = 1.02 * halfframe  
-    southxshift = 1.02 * halfframe 
-    southyshift = 0.02 * halfframe 
-    westxshift  = 0.01 * halfframe  
-    westyshift  = 1.02 * halfframe  
+    northxshift = 1.02 * halfframe
+    northyshift = 1.98 * halfframe
+    eastxshift  = 1.98 * halfframe
+    eastyshift  = 1.02 * halfframe
+    southxshift = 1.02 * halfframe
+    southyshift = 0.02 * halfframe
+    westxshift  = 0.01 * halfframe
+    westyshift  = 1.02 * halfframe
 
     alldatastring = "all data (null included)"
     realdatastring = "real data angles"
@@ -451,7 +450,7 @@
 
     occurrences = [(math.radians(x), freq[x]) for x in freq]
     occurrences.sort()
-    
+
     # find the maximum value
     maxradius = max([f for a, f in occurrences])
 

Modified: grass/trunk/scripts/d.to.rast/d.to.rast.py
===================================================================
--- grass/trunk/scripts/d.to.rast/d.to.rast.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/d.to.rast/d.to.rast.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -32,7 +32,7 @@
     if 'MONITOR' in gisenv:
         cmd_file = gcore.parse_command('d.mon', flags='g')['cmd']
         d_cmd = 'd.to.rast'
-        for param, val in options.iteritems():
+        for param, val in options.items():
             if val:
                 d_cmd += " {param}={val}".format(param=param, val=val)
         if gcore.overwrite():

Modified: grass/trunk/scripts/d.what.rast/d.what.rast.py
===================================================================
--- grass/trunk/scripts/d.what.rast/d.what.rast.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/d.what.rast/d.what.rast.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -34,7 +34,7 @@
         if not cmd_file:
             gcore.fatal(_("Unable to open file '%s'") % cmd_file)
         dout_cmd = 'd.what.rast'
-        for param, val in options.iteritems():
+        for param, val in options.items():
             if val:
                 dout_cmd += " {param}={val}".format(param=param, val=val)
         with open(cmd_file, "a") as file_:

Modified: grass/trunk/scripts/d.what.vect/d.what.vect.py
===================================================================
--- grass/trunk/scripts/d.what.vect/d.what.vect.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/d.what.vect/d.what.vect.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -34,7 +34,7 @@
         if not cmd_file:
             gcore.fatal(_("Unable to open file '%s'") % cmd_file)
         dout_cmd = 'd.what.vect'
-        for param, val in options.iteritems():
+        for param, val in options.items():
             if val:
                 dout_cmd += " {param}={val}".format(param=param, val=val)
         with open(cmd_file, "a") as file_:

Modified: grass/trunk/scripts/g.extension/g.extension.py
===================================================================
--- grass/trunk/scripts/g.extension/g.extension.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/g.extension/g.extension.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -142,8 +142,8 @@
     from urllib import urlopen, urlretrieve
 except ImportError:
     # there is also HTTPException, perhaps change to list
-    from urllib.request import HTTPError, URLError, \
-        urlopen, urlretrieve  # pylint: disable=E0611
+    from urllib.error import HTTPError, URLError
+    from urllib.request import urlopen, urlretrieve
 
 try:
     import xml.etree.ElementTree as etree
@@ -329,7 +329,7 @@
     if flags['t']:
         grass.message(_("List of available extensions (toolboxes):"))
         tlist = get_available_toolboxes(url)
-        for toolbox_code, toolbox_data in tlist.iteritems():
+        for toolbox_code, toolbox_data in tlist.items():
             if flags['g']:
                 print('toolbox_name=' + toolbox_data['name'])
                 print('toolbox_code=' + toolbox_code)
@@ -339,8 +339,7 @@
                 list_available_modules(url, toolbox_data['modules'])
             else:
                 if toolbox_data['modules']:
-                    print(os.linesep.join(map(lambda x: '* ' + x,
-                                              toolbox_data['modules'])))
+                    print(os.linesep.join(['* ' + x for x in toolbox_data['modules']]))
     else:
         grass.message(_("List of available extensions (modules):"))
         list_available_modules(url)
@@ -1530,7 +1529,7 @@
     """
     match = None
     actual_start = None
-    for key, value in KNOWN_HOST_SERVICES_INFO.iteritems():
+    for key, value in KNOWN_HOST_SERVICES_INFO.items():
         for start in value['possible_starts']:
             if url.startswith(start + value['domain']):
                 match = value

Modified: grass/trunk/scripts/g.manual/g.manual.py
===================================================================
--- grass/trunk/scripts/g.manual/g.manual.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/g.manual/g.manual.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -48,7 +48,13 @@
 
 import sys
 import os
-import urllib
+
+try:
+    from urlib import urlopen
+except ImportError:
+    # python3
+    from urllib.request import urlopen
+
 import webbrowser
 
 from grass.script.utils import basename
@@ -61,38 +67,39 @@
         grass.fatal(_("Browser '%s' not found") % browser)
 
     if flags['o']:
-        major,minor,patch = grass.version()['version'].split('.')
-        url_path = 'http://grass.osgeo.org/grass%s%s/manuals/%s.html' % (major,minor,entry)
-        if urllib.urlopen(url_path).getcode() != 200:
-            url_path = 'http://grass.osgeo.org/grass%s%s/manuals/addons/%s.html' % (major,minor,entry)
+        major, minor, patch = grass.version()['version'].split('.')
+        url_path = 'http://grass.osgeo.org/grass%s%s/manuals/%s.html' % (major, minor, entry)
+        if urlopen(url_path).getcode() != 200:
+            url_path = 'http://grass.osgeo.org/grass%s%s/manuals/addons/%s.html' % (
+                major, minor, entry)
     else:
         path = os.path.join(gisbase, 'docs', 'html', entry + '.html')
         if not os.path.exists(path) and os.getenv('GRASS_ADDON_BASE'):
             path = os.path.join(os.getenv('GRASS_ADDON_BASE'), 'docs', 'html', entry + '.html')
-    
+
         if not os.path.exists(path):
             grass.fatal(_("No HTML manual page entry for '%s'") % entry)
-    
+
         url_path = 'file://' + path
-    
+
     if browser and browser not in ('xdg-open', 'start'):
         webbrowser.register(browser_name, None)
-    
+
     grass.verbose(_("Starting browser '%(browser)s' for manual"
                     " entry '%(entry)s'...") % \
                   dict(browser=browser_name, entry=entry))
-    
+
     try:
         webbrowser.open(url_path)
     except:
         grass.fatal(_("Error starting browser '%(browser)s' for HTML file"
                       " '%(path)s'") % dict(browser=browser, path=path))
-    
+
 def start_man(entry):
     path = os.path.join(gisbase, 'docs', 'man', 'man1', entry + '.1')
     if not os.path.exists(path) and os.getenv('GRASS_ADDON_BASE'):
         path = os.path.join(os.getenv('GRASS_ADDON_BASE'), 'docs', 'man', 'man1', entry + '.1')
-    
+
     for ext in ['', '.gz', '.bz2']:
         if os.path.exists(path + ext):
             os.execlp('man', 'man', path + ext)
@@ -101,25 +108,25 @@
 
 def main():
     global gisbase, browser, browser_name
-    
+
     if flags['i'] and flags['t']:
         grass.fatal(_("Flags -%c and -%c are mutually exclusive") % ('i', 't'))
-    
+
     special = None
     if flags['i']:
         special = 'index'
     elif flags ['t']:
         special = 'topics'
-    
+
     if flags['m']:
         start = start_man
     else:
         start = start_browser
-    
+
     entry  = options['entry']
     gisbase = os.environ['GISBASE']
     browser = os.getenv('GRASS_HTML_BROWSER', '')
-    
+
     if sys.platform == 'darwin':
         # hack for MacOSX
         browser_name = os.getenv('GRASS_HTML_BROWSER_MACOSX', '..').split('.')[2]
@@ -128,14 +135,14 @@
         browser_name = basename(browser, 'exe')
     else:
         browser_name = basename(browser)
-    
+
     # keep order!
     # first test for index...
     if special:
         start(special)
     else:
         start(entry)
-    
+
     return 0
 
 if __name__ == "__main__":

Modified: grass/trunk/scripts/r.in.wms/wms_base.py
===================================================================
--- grass/trunk/scripts/r.in.wms/wms_base.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/r.in.wms/wms_base.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -1,5 +1,5 @@
 """!
- at brief Preparation of parameters for drivers, which download it, and managing downloaded data. 
+ at brief Preparation of parameters for drivers, which download it, and managing downloaded data.
 
 List of classes:
  - wms_base::WMSBase
@@ -18,9 +18,16 @@
 from math import ceil
 
 import base64
-import urllib2
-from httplib import HTTPException
 
+try:
+    from urllib2 import Request, urlopen, HTTPError
+    from httplib import HTTPException
+except ImportError:
+    from urllib.request import Request, urlopen
+    from urllib.error import HTTPError
+    from http.client import HTTPException
+
+
 import grass.script as grass
 from grass.exceptions import CalledModuleError
 
@@ -29,7 +36,7 @@
     def __init__(self):
         # these variables are information for destructor
         self.temp_files_to_cleanup = []
-        
+
         self.params = {}
         self.tile_size = {'bbox' : None}
 
@@ -37,20 +44,20 @@
         self.temp_warpmap = None
 
     def __del__(self):
-            
+
         # tries to remove temporary files, all files should be
         # removed before, implemented just in case of unexpected
         # stop of module
         for temp_file in self.temp_files_to_cleanup:
             grass.try_remove(temp_file)
-        
+
     def _debug(self, fn, msg):
         grass.debug("%s.%s: %s" %
                     (self.__class__.__name__, fn, msg))
-        
+
     def _initializeParameters(self, options, flags):
         self._debug("_initialize_parameters", "started")
-        
+
         # initialization of module parameters (options, flags)
         self.params['driver'] = options['driver']
         drv_info = WMSDriversInfo()
@@ -68,10 +75,10 @@
         if self.flags['o']:
             self.params['transparent'] = 'FALSE'
         else:
-            self.params['transparent'] = 'TRUE'   
+            self.params['transparent'] = 'TRUE'
 
         for key in ['password', 'username', 'urlparams']:
-            self.params[key] = options[key] 
+            self.params[key] = options[key]
 
         if (self.params ['password'] and self.params ['username'] == '') or \
            (self.params ['password'] == '' and self.params ['username']):
@@ -88,25 +95,25 @@
         self.params['format'] = drv_info.GetFormat(options['format'])
         if not self.params['format']:
             self.params['format'] = self.params['format']
-        
-        #TODO: get srs from Tile Service file in OnEarth_GRASS driver 
+
+        #TODO: get srs from Tile Service file in OnEarth_GRASS driver
         self.params['srs'] = int(options['srs'])
         if self.params['srs'] <= 0 and  not 'srs' in driver_props['ignored_params']:
             grass.fatal(_("Invalid EPSG code %d") % self.params['srs'])
 
-        self.params['wms_version'] = options['wms_version']  
+        self.params['wms_version'] = options['wms_version']
         if "CRS" in GetSRSParamVal(self.params['srs']) and self.params['wms_version'] == "1.1.1":
             self.params['wms_version'] = "1.3.0"
             grass.warning(_("WMS version <1.3.0> will be used, because version <1.1.1> does not support <%s>projection")
                             % GetSRSParamVal(self.params['srs']))
-        
+
         if self.params['wms_version'] == "1.3.0":
             self.params['proj_name'] = "CRS"
         else:
             self.params['proj_name'] = "SRS"
 
         # read projection info
-        self.proj_location = grass.read_command('g.proj', 
+        self.proj_location = grass.read_command('g.proj',
                                                 flags ='jf').rstrip('\n')
         self.proj_location = self._modifyProj(self.proj_location)
 
@@ -116,10 +123,10 @@
             # needed to be tested on more servers
             self.proj_srs = '+proj=merc +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +no_defs +a=6378137 +b=6378137 +nadgrids=@null +to_meter=1'
         else:
-            self.proj_srs = grass.read_command('g.proj', 
-                                               flags = 'jf', 
+            self.proj_srs = grass.read_command('g.proj',
+                                               flags = 'jf',
                                                epsg = str(GetEpsg(self.params['srs']))).rstrip('\n')
-        
+
         self.proj_srs = self._modifyProj(self.proj_srs)
 
         if not self.proj_srs or not self.proj_location:
@@ -131,18 +138,18 @@
         maxcols = int(options['maxcols'])
         if maxcols <= min_tile_size:
             grass.fatal(_("Maxcols must be greater than 100"))
-        
+
         maxrows = int(options['maxrows'])
         if maxrows <= min_tile_size:
             grass.fatal(_("Maxrows must be greater than 100"))
-        
-        # setting optimal tile size according to maxcols and maxrows constraint and region cols and rows      
+
+        # setting optimal tile size according to maxcols and maxrows constraint and region cols and rows
         self.tile_size['cols'] = int(self.region['cols'] / ceil(self.region['cols'] / float(maxcols)))
         self.tile_size['rows'] = int(self.region['rows'] / ceil(self.region['rows'] / float(maxrows)))
-        
+
         # default format for GDAL library
         self.gdal_drv_format = "GTiff"
-        
+
         self._debug("_initialize_parameters", "finished")
 
     def _modifyProj(self, proj):
@@ -184,10 +191,10 @@
     def GetMap(self, options, flags):
         """!Download data from WMS server."""
 
-        self._initializeParameters(options, flags)  
+        self._initializeParameters(options, flags)
 
         self.bbox     = self._computeBbox()
-        
+
         self.temp_map = self._download()
 
         if not self.temp_map:
@@ -196,8 +203,8 @@
         self._reprojectMap()
 
         return self.temp_warpmap
-    
-    def _fetchCapabilities(self, options): 
+
+    def _fetchCapabilities(self, options):
         """!Download capabilities from WMS server
         """
         cap_url = options['url'].strip()
@@ -212,43 +219,45 @@
         elif 'OnEarth' in options['driver']:
             cap_url += "REQUEST=GetTileService"
         else:
-            cap_url += "SERVICE=WMS&REQUEST=GetCapabilities&VERSION=" + options['wms_version'] 
+            cap_url += "SERVICE=WMS&REQUEST=GetCapabilities&VERSION=" + options['wms_version']
 
         if options['urlparams']:
             cap_url += "&" + options['urlparams']
-            
+
         grass.debug('Fetching capabilities file.\n%s' % cap_url)
 
         try:
             cap = self._fetchDataFromServer(cap_url, options['username'], options['password'])
         except (IOError, HTTPException) as e:
-            if urllib2.HTTPError == type(e) and e.code == 401:
-                grass.fatal(_("Authorization failed to <%s> when fetching capabilities") % options['url'])
+            if isinstance(e, HTTPError) and e.code == 401:
+                grass.fatal(
+                    _("Authorization failed to <%s> when fetching capabilities") %
+                    options['url'])
             else:
                 msg = _("Unable to fetch capabilities from <%s>: %s") % (options['url'], e)
-                
+
                 if hasattr(e, 'reason'):
                     msg += _("\nReason: ") + e.reason
-                
+
                 grass.fatal(msg)
-        
+
         grass.debug('Fetching capabilities OK')
         return cap
 
     def _fetchDataFromServer(self, url, username = None, password = None):
         """!Fetch data from server
-        """      
-        request = urllib2.Request(url)
+        """
+        request = Request(url)
         if username and password:
                     base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
                     request.add_header("Authorization", "Basic %s" % base64string)
-        
+
         try:
-            return urllib2.urlopen(request)
+            return urlopen(request)
         except ValueError as error:
             grass.fatal("%s" % error)
 
-    def GetCapabilities(self, options): 
+    def GetCapabilities(self, options):
         """!Get capabilities from WMS server
         """
         cap  = self._fetchCapabilities(options)
@@ -261,36 +270,36 @@
                 temp.write(cap.read())
                 temp.close()
                 return
-            except IOError as error: 
+            except IOError as error:
                 grass.fatal(_("Unabble to open file '%s'.\n%s\n" % (cap_file, error)))
-        
+
         # print to output
         cap_lines = cap.readlines()
-        for line in cap_lines: 
-            print line.rstrip()
-        
+        for line in cap_lines:
+            print(line.rstrip())
+
     def _computeBbox(self):
         """!Get region extent for WMS query (bbox)
         """
         self._debug("_computeBbox", "started")
-        
-        bbox_region_items = {'maxy' : 'n', 'miny' : 's', 'maxx' : 'e', 'minx' : 'w'}  
+
+        bbox_region_items = {'maxy' : 'n', 'miny' : 's', 'maxx' : 'e', 'minx' : 'w'}
         bbox = {}
 
-        if self.proj_srs == self.proj_location: # TODO: do it better
-            for bbox_item, region_item in bbox_region_items.iteritems():
+        if self.proj_srs == self.proj_location:  # TODO: do it better
+            for bbox_item, region_item in bbox_region_items.items():
                 bbox[bbox_item] = self.region[region_item]
-        
+
         # if location projection and wms query projection are
         # different, corner points of region are transformed into wms
         # projection and then bbox is created from extreme coordinates
         # of the transformed points
         else:
-            for bbox_item, region_item  in bbox_region_items.iteritems():
+            for bbox_item, region_item in bbox_region_items.items():
                 bbox[bbox_item] = None
 
             temp_region = self._tempfile()
-            
+
             try:
                 temp_region_opened = open(temp_region, 'w')
                 temp_region_opened.write("%f %f\n%f %f\n%f %f\n%f %f\n"  %\
@@ -300,8 +309,8 @@
                                         self.region['e'], self.region['s'] ))
             except IOError:
                  grass.fatal(_("Unable to write data into tempfile"))
-            finally:           
-                temp_region_opened.close()            
+            finally:
+                temp_region_opened.close()
 
             points = grass.read_command('m.proj', flags = 'd',
                                         proj_out = self.proj_srs,
@@ -311,14 +320,14 @@
             grass.try_remove(temp_region)
             if not points:
                 grass.fatal(_("Unable to determine region, %s failed") % 'm.proj')
-            
+
             points = points.splitlines()
             if len(points) != 4:
                 grass.fatal(_("Region definition: 4 points required"))
-            
+
             for point in points:
                 try:
-                    point = map(float, point.split("|"))
+                    point = list(map(float, point.split("|")))
                 except ValueError:
                     grass.fatal(_('Reprojection of region using m.proj failed.'))
                 if not bbox['maxy']:
@@ -327,33 +336,33 @@
                     bbox['maxx'] = point[0]
                     bbox['minx'] = point[0]
                     continue
-                
+
                 if   bbox['maxy'] < point[1]:
                     bbox['maxy'] = point[1]
                 elif bbox['miny'] > point[1]:
                     bbox['miny'] = point[1]
-                
+
                 if   bbox['maxx'] < point[0]:
                     bbox['maxx'] = point[0]
                 elif bbox['minx'] > point[0]:
-                    bbox['minx'] = point[0]  
-        
+                    bbox['minx'] = point[0]
+
         self._debug("_computeBbox", "finished -> %s" % bbox)
 
         # Ordering of coordinates axis of geographic coordinate
-        # systems in WMS 1.3.0 is flipped. If  self.tile_size['flip_coords'] is 
+        # systems in WMS 1.3.0 is flipped. If  self.tile_size['flip_coords'] is
         # True, coords in bbox need to be flipped in WMS query.
 
         return bbox
 
-    def _reprojectMap(self): 
+    def _reprojectMap(self):
         """!Reproject data  using gdalwarp if needed
         """
         # reprojection of raster
         if self.proj_srs != self.proj_location: # TODO: do it better
             grass.message(_("Reprojecting raster..."))
             self.temp_warpmap = grass.tempfile()
-            
+
             if int(os.getenv('GRASS_VERBOSE', '2')) <= 2:
                 nuldev = file(os.devnull, 'w+')
             else:
@@ -365,7 +374,7 @@
                 gdal_method = "bilinear"
             else:
                 gdal_method = self.params['method']
-            
+
             #"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs"
             # RGB rasters - alpha layer is added for cropping edges of projected raster
             try:
@@ -385,10 +394,10 @@
                 ps.wait()
             except OSError as e:
                 grass.fatal('%s \nThis can be caused by missing %s utility. ' % (e, 'gdalwarp'))
-            
+
             if nuldev:
                 nuldev.close()
-            
+
             if ps.returncode != 0:
                 grass.fatal(_('%s failed') % 'gdalwarp')
             grass.try_remove(self.temp_map)
@@ -398,20 +407,20 @@
             self.temp_files_to_cleanup.remove(self.temp_map)
 
         return self.temp_warpmap
-        
+
     def _tempfile(self):
-        """!Create temp_file and append list self.temp_files_to_cleanup 
-            with path of file 
-     
+        """!Create temp_file and append list self.temp_files_to_cleanup
+            with path of file
+
         @return string path to temp_file
         """
         temp_file = grass.tempfile()
         if temp_file is None:
             grass.fatal(_("Unable to create temporary files"))
-        
+
         # list of created tempfiles for destructor
         self.temp_files_to_cleanup.append(temp_file)
-        
+
         return temp_file
 
 class GRASSImporter:
@@ -427,13 +436,13 @@
         # into raster named:self.opt_output + this suffix)
         self.original_mask_suffix = "_temp_MASK"
 
-        # check names of temporary rasters, which module may create 
+        # check names of temporary rasters, which module may create
         maps = []
         for suffix in ('.red', '.green', '.blue', '.alpha', self.original_mask_suffix ):
             rast = self.opt_output + suffix
             if grass.find_file(rast, element = 'cell', mapset = '.')['file']:
                 maps.append(rast)
-        
+
         if len(maps) != 0:
             grass.fatal(_("Please change output name, or change names of these rasters: %s, "
                           "module needs to create this temporary maps during execution.") % ",".join(maps))
@@ -447,7 +456,7 @@
             except CalledModuleError:
                 grass.fatal(_('%s failed') % 'r.mask')
 
-            # restore original mask, if exists 
+            # restore original mask, if exists
             if grass.find_file(self.opt_output + self.original_mask_suffix, element = 'cell', mapset = '.' )['name']:
                 try:
                     mask_copy = self.opt_output + self.original_mask_suffix
@@ -457,25 +466,25 @@
                     grass.fatal(_('%s failed') % 'g.copy')
 
         # remove temporary created rasters
-        if self.cleanup_layers: 
+        if self.cleanup_layers:
             maps = []
             for suffix in ('.red', '.green', '.blue', '.alpha', self.original_mask_suffix):
                 rast = self.opt_output + suffix
                 if grass.find_file(rast, element = 'cell', mapset = '.')['file']:
                     maps.append(rast)
-            
+
             if maps:
                 grass.run_command('g.remove',
                                   quiet = True,
                                   flags = 'fb',
                                   type = 'raster',
                                   name = ','.join(maps))
-        
-        # delete environmental variable which overrides region 
+
+        # delete environmental variable which overrides region
         if 'GRASS_REGION' in os.environ.keys():
             os.environ.pop('GRASS_REGION')
 
-    def ImportMapIntoGRASS(self, raster): 
+    def ImportMapIntoGRASS(self, raster):
         """!Import raster into GRASS.
         """
         # importing temp_map into GRASS
@@ -489,14 +498,14 @@
         # information for destructor to cleanup temp_layers, created
         # with r.in.gdal
         self.cleanup_layers = True
-        
+
         # setting region for full extend of imported raster
         if grass.find_file(self.opt_output + '.red', element = 'cell', mapset = '.')['file']:
             region_map = self.opt_output + '.red'
         else:
             region_map = self.opt_output
         os.environ['GRASS_REGION'] = grass.region_env(rast = region_map)
-          
+
         # mask created from alpha layer, which describes real extend
         # of warped layer (may not be a rectangle), also mask contains
         # transparent parts of raster
@@ -566,7 +575,7 @@
 
         props = {}
         props['ignored_flags'] = ['o']
-        props['ignored_params'] = ['bgcolor', 'styles', 'capfile_output', 
+        props['ignored_params'] = ['bgcolor', 'styles', 'capfile_output',
                                    'format', 'srs', 'wms_version']
         props['req_multiple_layers'] = False
 
@@ -635,9 +644,9 @@
 
 def GetEpsg(srs):
     """
-     @return EPSG number 
+     @return EPSG number
              If srs is CRS number, return EPSG number which corresponds to CRS number.
-    """    
+    """
     if srs == 84:
         return 4326
     if srs == 83:

Modified: grass/trunk/scripts/r.in.wms/wms_cap_parsers.py
===================================================================
--- grass/trunk/scripts/r.in.wms/wms_cap_parsers.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/r.in.wms/wms_cap_parsers.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -599,7 +599,7 @@
             return None
 
         try:
-            bbox = map(float, bbox.split(','))
+            bbox = list(map(float, bbox.split(',')))
         except ValueError:
             return None
 

Modified: grass/trunk/scripts/r.in.wms/wms_drv.py
===================================================================
--- grass/trunk/scripts/r.in.wms/wms_drv.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/r.in.wms/wms_drv.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -31,9 +31,15 @@
 Numeric.arrayrange = Numeric.arange
 
 from math import pi, floor
-from urllib2 import HTTPError
-from httplib import HTTPException
 try:
+    from urllib2 import HTTPError
+    from httplib import HTTPException
+except ImportError:
+    # python3
+    from urllib.error import HTTPError
+    from http.client import HTTPException
+
+try:
     from xml.etree.ElementTree import ParseError
 except ImportError: # < Python 2.7
     from xml.parsers.expat import ExpatError as ParseError

Modified: grass/trunk/scripts/r.tileset/r.tileset.py
===================================================================
--- grass/trunk/scripts/r.tileset/r.tileset.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/r.tileset/r.tileset.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -175,7 +175,7 @@
         if "*" in line:
             errors += 1
         else:
-            p_x2, p_y2, p_z2 = map(float, line.split(';'))
+            p_x2, p_y2, p_z2 = list(map(float, line.split(';')))
             points.append((p_x2 / dest['scale'], p_y2 / dest['scale']))
 
     return points, errors

Modified: grass/trunk/scripts/r3.in.xyz/r3.in.xyz.py
===================================================================
--- grass/trunk/scripts/r3.in.xyz/r3.in.xyz.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/r3.in.xyz/r3.in.xyz.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -256,7 +256,7 @@
     proc = {}
     pout = {}
 
-    depths = range(1, 1 + region['depths'])
+    depths = list(range(1, 1 + region['depths']))
 
     for i in depths:
         tmp_layer_name = 'tmp.r3xyz.%d.%s' % (os.getpid(), '%05d' % i)

Modified: grass/trunk/scripts/v.db.addtable/v.db.addtable.py
===================================================================
--- grass/trunk/scripts/v.db.addtable/v.db.addtable.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/v.db.addtable/v.db.addtable.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -105,7 +105,7 @@
     
     if not table in tables.splitlines():
         if columns:
-            column_def = map(lambda x: x.strip().lower(), columns.strip().split(','))
+            column_def = [x.strip().lower() for x in columns.strip().split(',')]
         else:
             column_def = []
         

Modified: grass/trunk/scripts/v.db.reconnect.all/v.db.reconnect.all.py
===================================================================
--- grass/trunk/scripts/v.db.reconnect.all/v.db.reconnect.all.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/v.db.reconnect.all/v.db.reconnect.all.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -60,7 +60,7 @@
 def substitute_db(database):
     gisenv = grass.gisenv()
     tmpl = string.Template(database)
-    
+
     return tmpl.substitute(GISDBASE = gisenv['GISDBASE'],
                            LOCATION_NAME = gisenv['LOCATION_NAME'],
                            MAPSET = gisenv['MAPSET'])
@@ -76,13 +76,13 @@
             os.makedirs(path)
 	    return True
         return False
-    
+
     if driver == 'sqlite':
         path = os.path.dirname(subst_database)
         # check if destination directory exists
         if not os.path.isdir(path):
             os.makedirs(path)
-    
+
     if subst_database in grass.read_command('db.databases', quiet = True,
                                       driver = driver).splitlines():
         return False
@@ -95,7 +95,7 @@
     except CalledModuleError:
         grass.fatal(_("Unable to create database <%s> by driver <%s>") % \
                         (subst_database, driver))
-        
+
     return False
 
 # copy tables if required (-c)
@@ -106,7 +106,7 @@
                                       database = to_database,
                                       stderr = nuldev).splitlines():
         return False
-    
+
     grass.info("Copying table <%s> to target database..." % to_table)
     try:
         grass.run_command('db.copy', from_driver = from_driver,
@@ -116,7 +116,7 @@
                           to_table = to_table)
     except CalledModuleError:
         grass.fatal(_("Unable to copy table <%s>") % from_table)
-    
+
     return True
 
 # drop tables if required (-d)
@@ -134,7 +134,7 @@
                           table = table)
     except CalledModuleError:
         grass.fatal(_("Unable to drop table <%s>") % table)
-        
+
 # create index on key column
 def create_index(driver, database, table, index_name, key):
     if driver == 'dbf':
@@ -174,44 +174,45 @@
 	old_database_subst = substitute_db(old_database)
 
     new_database_subst = substitute_db(new_database)
-    
+
     if old_database_subst == new_database_subst and old_schema == new_schema:
 	grass.fatal(_("Old and new database connection is identical. Nothing to do."))
-    
+
     mapset = grass.gisenv()['MAPSET']
-        
+
     vectors = grass.list_grouped('vect')[mapset]
     num_vectors = len(vectors)
 
     if flags['c']:
 	# create new database if not existing
 	create_db(new_driver, new_database)
-    
+
     i = 0
     for vect in vectors:
         vect = "%s@%s" % (vect, mapset)
         i += 1
-	grass.message(_("%s\nReconnecting vector map <%s> (%d of %d)...\n%s") % \
-                          ('-' * 80, vect, i, num_vectors, '-' * 80))
-        for f in grass.vector_db(vect, stderr = nuldev).itervalues():
+        gscript.message(_("%s\nReconnecting vector map <%s> "
+                          "(%d of %d)...\n%s") %
+                        ('-' * 80, vect, i, num_vectors, '-' * 80))
+        for f in gscript.vector_db(vect, stderr=nuldev).values():
             layer = f['layer']
             schema_table = f['table']
             key = f['key']
             database = f['database']
             driver = f['driver']
-            
+
             # split schema.table
             if '.' in schema_table:
                 schema, table = schema_table.split('.', 1)
             else:
                 schema = ''
                 table = schema_table
-            
+
             if new_schema:
                 new_schema_table = "%s.%s" % (new_schema, table)
             else:
                 new_schema_table = table
-            
+
             grass.debug("DATABASE = '%s' SCHEMA = '%s' TABLE = '%s' ->\n"
                         "      NEW_DATABASE = '%s' NEW_SCHEMA_TABLE = '%s'" % \
                             (old_database, schema, table, new_database, new_schema_table))
@@ -224,15 +225,15 @@
 		do_reconnect = False
 	    if schema != old_schema:
 		do_reconnect = False
-		
+
             if do_reconnect == True:
                 grass.verbose(_("Reconnecting layer %d...") % layer)
-                                          
+
                 if flags['c']:
                     # check if table exists in new database
                     copy_tab(driver, database, schema_table,
                              new_driver, new_database, new_schema_table)
-                
+
                 # drop original table if required
                 if flags['d']:
                     drop_tab(vect, layer, schema_table, driver, substitute_db(database))
@@ -251,7 +252,7 @@
 		if database != new_database_subst:
 		    grass.warning(_("Layer <%d> will not be reconnected because "
 				    "database or schema do not match.") % layer)
-	
+
     return 0
 
 if __name__ == "__main__":

Modified: grass/trunk/scripts/v.in.wfs/v.in.wfs.py
===================================================================
--- grass/trunk/scripts/v.in.wfs/v.in.wfs.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/v.in.wfs/v.in.wfs.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -78,7 +78,10 @@
 import sys
 from grass.script.utils import try_remove
 from grass.script import core as grass
-import urllib
+try:
+    from urllib import urlopen
+except ImportError:
+    from urllib.request import urlopen
 
 def main():
     out = options['output']
@@ -116,7 +119,7 @@
     grass.debug(wfs_url)
 
     grass.message(_("Retrieving data..."))
-    inf = urllib.urlopen(wfs_url)
+    inf = urlopen(wfs_url)
     outf = file(tmpxml, 'wb')
     while True:
 	s = inf.read()

Modified: grass/trunk/scripts/v.pack/v.pack.py
===================================================================
--- grass/trunk/scripts/v.pack/v.pack.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/v.pack/v.pack.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -49,30 +49,30 @@
 def main():
     infile = options['input']
     compression_off = flags['c']
-    
+
     global basedir
     basedir = grass.tempdir()
-    
+
     # check if vector map exists
     gfile = grass.find_file(infile, element = 'vector')
     if not gfile['name']:
         grass.fatal(_("Vector map <%s> not found") % infile)
-    
+
     # check if input vector map is in the native format
     if vector.vector_info(gfile['fullname'])['format'] != 'native':
         grass.fatal(_("Unable to pack vector map <%s>. Only native format supported.") % \
                         gfile['fullname'])
-    
+
     # split the name if there is the mapset name
     if infile.find('@'):
         infile = infile.split('@')[0]
-    
+
     # output name
     if options['output']:
         outfile = options['output']
     else:
         outfile = infile + '.pack'
-    
+
     # check if exists the output file
     if os.path.exists(outfile):
         if os.getenv('GRASS_OVERWRITE'):
@@ -80,33 +80,33 @@
             try_remove(outfile)
         else:
             grass.fatal(_("option <%s>: <%s> exists.") % ("output", outfile))
-    
+
     # prepare for packing
     grass.verbose(_("Packing <%s>...") % (gfile['fullname']))
-    
-    # write tar file, optional compression 
+
+    # write tar file, optional compression
     if compression_off:
         tar = tarfile.open(name = outfile, mode = 'w:')
     else:
         tar = tarfile.open(name = outfile, mode = 'w:gz')
     tar.add(gfile['file'], infile)
-    
-    # check if exist a db connection for the vector 
+
+    # check if exist a db connection for the vector
     db_vect = vector.vector_db(gfile['fullname'])
     if not db_vect:
         grass.verbose(_('There is not database connected with vector map <%s>') % gfile['fullname'])
     else:
         # for each layer connection save a table in sqlite database
         sqlitedb = os.path.join(basedir, 'db.sqlite')
-        for i, dbconn in db_vect.iteritems():
-            grass.run_command('db.copy', from_driver = dbconn['driver'], 
-                              from_database = dbconn['database'],
-                              from_table =  dbconn['table'], 
-                              to_driver = 'sqlite', to_database = sqlitedb, 
-                              to_table = dbconn['table'])
+        for i, dbconn in db_vect.items():
+            grass.run_command('db.copy', from_driver=dbconn['driver'],
+                              from_database=dbconn['database'],
+                              from_table=dbconn['table'],
+                              to_driver='sqlite', to_database=sqlitedb,
+                              to_table=dbconn['table'])
         tar.add(sqlitedb, 'db.sqlite')
-    
-    # add to the tar file the PROJ files to check when unpack file    
+
+    # add to the tar file the PROJ files to check when unpack file
     gisenv = grass.gisenv()
     for support in ['INFO', 'UNITS', 'EPSG']:
         path = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'],
@@ -114,9 +114,9 @@
         if os.path.exists(path):
             tar.add(path, 'PROJ_' + support)
     tar.close()
-    
+
     grass.message(_("Pack file <%s> created") % os.path.join(os.getcwd(), outfile))
-            
+
 if __name__ == "__main__":
     options, flags = grass.parser()
     atexit.register(cleanup)

Modified: grass/trunk/scripts/v.what.strds/v.what.strds.py
===================================================================
--- grass/trunk/scripts/v.what.strds/v.what.strds.py	2016-05-02 16:08:06 UTC (rev 68357)
+++ grass/trunk/scripts/v.what.strds/v.what.strds.py	2016-05-02 16:08:34 UTC (rev 68358)
@@ -162,7 +162,7 @@
                                                         "equal", False,
                                                         False)
 
-        for i in xrange(len(mapmatrizes[0])):
+        for i in range(len(mapmatrizes[0])):
             isvalid = True
             mapname_list = []
             for mapmatrix in mapmatrizes:



More information about the grass-commit mailing list