New answers tagged

0

The only line that is going to generate that error is return(subsetOut) If subsetOut is referenced before assignment it means none of the above if and elif conditions matched as true. There's no else to catch anything else. You seem to be comparing a selection value with a numeric. I suspect the selection values are character values (since a selection ...


0

Add an AttributeExposer, expose the fme_feature_type attribute Connect the AttributeExposer to a AttributeCreator to push fme_feature_type out an attribute (named fme_feature_type below) In the PythonCaller, get your attribute by: layer_name = feature.getAttribute("fme_feature_type")


4

I got an orders of magnitude speed-up simply by moving two if statements just underneath their corresponding fiona.listlayers calls. if (featureName == "HydrographySrf") if (bldgName == "StructureSrf") I just went from taking over 5.5 hours of parsing down to less than 2.5 minutes. Sorry for getting things spun up on what is otherwise an easy fix.


1

It could be that your GDB files (which are self-contained databases) have indexes designed to make these kinds of operations very fast for ArcGIS. If OGR (which is what Fiona uses to read GDB files) supports these indexes, you should be able to get a significant speed up if not the same performance as ArcGIS. The section at ...


1

You could use: iface.mapCanvas().saveAsImage( "myGeoreferencedView.png" ) It exports both PNG and PNGw files. The latter is known as World file and contains coordinate information.


1

Answered at https://github.com/mapbox/rasterio/issues/710. Example reading a 30x30 window into a 3x3 array where overviews (if available) would kick in. arr = np.empty(shape=(3, 3)).astype(src.profile['dtype']) arr = src.read(1, out=arr, window=((0, 30), (0, 30))) arr array([[9195, 9116, 9134], ...


3

Use layer.GetNextFeature() from osgeo import ogr driver = ogr.GetDriverByName("WFS") wfs = driver.Open("WFS:http://geodienste-hamburg.de/DE_HH_WFS_INSPIRE_A3_1_Statistische_Einheiten") # This is a public WFS with open data layer = wfs.GetLayerByName("Stadtteile") # Some polygons, possibly multipolygons # A random point inside one of them ...


0

I had the same issue, solved it by calling the parent's accept() like so: myDialog.parent().accept()


2

I think when you're adding a layer and you want to add it to the composer to save it as an image, you need to make sure the layer is visible. Try adding this line after your for loop: iface.legendInterface().setLayerVisible(layer, True) So now it should look like: for layer in layers: iface.legendInterface().setLayerVisible(layer, True) myFile = ...


0

Old question but leaving this here for anyone else who stumbles across it: Geoff Boeing wrote a great tutorial on how to install the geopandas library, which goes over installation of fiona (as well as other libraries like shapely, gdal, pyproj...). The tutorial is located here: http://geoffboeing.com/2014/09/using-geopandas-windows/ The step that tripped ...


0

You could use something like the following to get the coordinates of your extent: xmin = layer2.extent().xMinimum() xmax = layer2.extent().xMaximum() ymin = layer2.extent().yMinimum() ymax = layer2.extent().yMaximum()


2

In QGIS you can try the Distance Matrix of Saga (under Processing > Tools > Saga > Shapes - Points). This calculates a distance matrix for all points in one layer only, but does include an ID. Just combine the two layers into one (e.g. with Vector > Data Management Tools > Merge Shapefile to One). Make sure that you have some attribute that makes it possible ...


2

You probably need to add something like raster = processing.getObject(RASTERLAYER_BAND) and remove nodatabackground=processing.runalg(...) The following works for me: ##NoData Background=name ##RASTERLAYER_BAND=raster ##nodatabackground=output raster import processing raster = processing.getObject(RASTERLAYER_BAND) ext = raster.extent() a = ...


0

Arcgis solution, but applicable to any decent GIS. Project your layers. Calculate xy columns Join table to another by address. Calculate distance between 2 pairs of coordinates


0

I know this post is old, but I think that the best tool for doing what the original post described is the Detect Feature Changes tool that was first released with ArcGIS 10.2. At ArcGIS 10.4 it also detects line direction changes (flipped lines) that are otherwise identical. The tool optionally creates a table to identify 1:1 segment matches or 1:M, M:1 or ...


0

Could be helpful for future: arcpy.SelectLayerByAttribute_management("pts", "NEW_SELECTION", "\"FID\" = "+ str(i)) In this example, value is int, but expression has to be str, thus just convert it str(i)and append it to expression. In addition, if the value is str i.e. i='0', then I would apply format, i.e. "\"FID\" = \"{}\" ".format(i)


2

To automatically open the QGIS Python Console when QGIS starts, you can read How to show Python console at QGIS program start. However, I guess your ultimate intention is to run the script (even if it doesn't run from the QGIS Python Console), so you can create (if it doesn't exist already) a startup.py file in the QGIS Python directory: On GNU/Linux: ...


0

I had this exact issue - I renamed the folder "C:\Python27" to "C:\Python27_old" and then repaired the ArcGIS Desktop installation from Control Panel, Programs and Features (Win7); highlighting "ArcGIS 10.3.1 for Desktop", and then Clicking "Install/Change" and selecting "Repair". Worked for me, and faster than reinstalling everything.


0

before line 19, insert mylayer = qgis.utils.iface.activeLayer() Then make sure that the layer on which you want to perform the query (col19_lines) is selected in the layer tree and that all its features are selected (if you want to run the script on all the features, that is). What is does is that it points to your layer, so that the variable "mylayer" ...


1

I'm going to assume your text file is like a CSV with a header called "LayerName" and each row is a different layer. In that case, your function would be something like this: import fmeobjects def processFeature(feature): # Get which layer is currently being processed layer_name = feature.getAttribute("LayerName") # do some logical processing ...


0

It doesn't seem any of the answers above answered the question, even though each may contain some useful information. This could be a memory issue. mxd and df could take up huge memories, especially if any huge datasets are involved. When looping through a lot of mxds to export, promptly clear temporary mxds and dfs would be necessary, such as del mxd ...


1

Building on what Peter has suggested, you could try using the following code (note that you did not define file_date in your code so I used the basename of the raster instead but you can modify it): from PyQt4 import QtGui from PyQt4.QtCore import * from PyQt4.QtXml import * from PyQt4.QtCore import QSize, QFileInfo from PyQt4 import QtCore from qgis ...


2

This will get the job done with ArcGIS (most likely can be done with shorter/better code): import os, arcpy from datetime import datetime, time print "Running script..." arcpy.env.outputCoordinateSystem = r"D:\Projektionsfiler\SWEREF99TM.prj" arcpy.env.geographicTransformations = "SWEREF99_To_WGS_1984_1" #workspaces arbetsmapp = r'D:\S2' utdatamapp = ...


3

Another option would be to use os.wallk using .endwith() method, see example below: import os dir = 'C:/Temp' for root, dirs, files in os.walk(dir): for f in files: if f.endswith('.dat'): layer = QgsRasterLayer(os.path.join(root,f), f) QgsMapLayerRegistry.instance().addMapLayer(layer)


2

You can use glob.glob to get a list of all dat files in the directory and use a loop to add them to QgsMapLayerRegistry


1

You can use the geotext python library for the same. pip install geotext all it takes is to install this library. The usage is as simple as: from geotext import GeoText places = GeoText("London is a great city") places.cities gives the result 'London' The list of cities covered in this library is not extensive but it has a good list.


2

I would say that for zoom greater than 15, if you split your area of interest into smaller areas(Bounding box), you will be able to cache them in much less time by running multiple processes on a single machine. For example, you are running zoom 16 (having 50,000,00 tiles) on a machine and according to your average tile-caching speed, this process will ...


4

You can download GDAL 2.1 for Windows from GIS Internals. There is an installer and a portable version that doesn't require installation. GDAL 2.1 is available for Ubuntu 16.04 from the UbuntuGIS-Unstable PPA sudo add-apt-repository -y ppa:ubuntugis/ubuntugis-unstable sudo apt update sudo apt upgrade # if you already have gdal 1.11 installed sudo apt ...


2

Your single line !file!.replace(" ","") can be added to by including more .replace() !file!.replace(" ","").replace("?","").replace(",","").replace(chr(33),"") and so on. You may need to escape some of the characters, or use their chr() code if the field calculator doesn't like them. chr(33) in my example replaces the !. Chr codes can be retrieved ...


1

It's not pretty, but ''.join([x for x in list(!file!) if x not in ["!","@","$"]]) should remove any single character you specify in the list, and return the resulting characters as a string (the "etc" in your example wouldn't work, however).


5

Even though this question can be considered off topic I though I would make a suggestion. Try using the Python re module in the Field Calculator. Here is a simple example used in the ArcMap field calculator. Pre-Logic Script Code import re def repChar(strg) regexChars = '[!@$*#]' line = re.sub(regexChars,'',x) return line Field ...


2

Use sde:sqlserver:mymachinename for your server instance arcpy.ArcSDESQLExecute(server='mymachinename', instance='sde:sqlserver:mymachinename', database='mydbname', user='myuser',password='mypass') This makes your Direct Connect work rather than using an SDE service instance. I recall this happening a couple of versions ago when we were moving from SDE ...


2

You can do this with a batch file by explicitly pointing to your ArcGIS install: start C:\Python27\ArcGIS10.3\python.exe C:\Path\to_the\script\to_run.py You can apply the same logic to the cmd and point it to your desired python interpreter...If you are using a more robust Python IDE, you may even be able to point that to which version to use when running ...


1

Found a way, basically you just need to specify the column when populating the QTableWidget (mentioned in comment): qTable = self.dockwidget.tableWidget data = [] group1 = root.findGroup('Group1') group2 = root.findGroup('Group2') for child in group1.children(): data.append(child.name()) for child in group2.children(): data.append(child.name()) ...


3

The expression functions are all stored under .qgis2\python\expressions You can copy and install them onto any machine that needs them. The other option is to add them as a Python macro for the project under Project -> Properties -> Marcos. Paste the text of your expression function in the there.


2

I added that recipe to the rasterio documentation. Since it was such a simple shape, in this case I just unzipped the coords in the single record contained by the shapefile. That is, x, y = zip(*features[0]['coordinates'][0]), and then just plot. More generally, I use PolygonPatch from descartes, and matplotlib.collections. import fiona import rasterio ...


1

This was for a mac. I wound up downloading exifread manually here - https://pypi.python.org/pypi/ExifRead. I then copied the sub directory to /Applications/QGIS.app/Contents/Resources/python. Afterwards I restarted QGIS and was able to install the photo2shape plugin sucessfully.


5

Let me share how it works for me: self.setWindowTitle(title) #data = 'Recordset back from postgis' nb_row = len(data) nb_col = 2 qTable.setRowCount(nb_row) qTable.setColumnCount(nb_col) for row in range (nb_row): for col in range(nb_col): item = QTableWidgetItem(str(data[row][col])) qTable.setItem(row,col,item) ...


1

You could use something like the following: import processing lddLrs = qgis.utils.iface.legendInterface().layers() path = "path/to/results//" for lyr in lddLrs: processing.runalg("saga:rastercalculator", lyr, None, "(a/a)*a", True, 7, path + lyr.name() + "_suffix.tif") EDIT : If you want to use the QgsRasterCalculator, you could try using the ...


1

EPSG:28992 is projected system, not geographical so you cannot call SetWellKnownGeogCS() for it. You need to define both ellipsoid (GeogCS) and projection method (ProjCS) for projected systems. For UTM projection you can set both explicitly: proj = osr.SpatialReference() proj.SetProjCS("UTM 30N (WGS84)") proj.SetWellKnownGeogCS("WGS84") proj.SetUTM(30, ...


1

Warp to reduce the resolution. Went from 674MB to 36MB. gdal_warp


1

Read your CSV file and create a vars_list list of tuples to insert. Reading the CSV file is off topic, but it should have a structure something like this: vars_list = [ (lng1, lat1, lng2, lat2), # first record (lng1, lat1, lng2, lat2), # second ... ] Then insert them all at once with executemany, like this: sql = '''\ INSERT INTO ...


3

The Gohlke GDAL/OGR wheel includes the FileGDB driver compiled as a plugin. To get the FileGDB driver working: Copy the Esri bin64\FileGDB.dll to [python install/virtualenv dir]\Lib\site-packages\osgeo (use bin\FileGDB.dll if using 32bit python). Do not copy the FileGDB.dll to the gdalplugins directory. Set GDAL_DRIVER_PATH environment variable, ...


2

Look first at More Efficient Spatial join in Python without QGIS, ArcGIS, PostGIS, etc The results of Fiona are Python dictionaries (GeoJSON format) import fiona layer = fiona.open("test_regex.shp") # first feature first = layer.next() print first {'geometry': {'type': 'Polygon', 'coordinates': [[(203371.23902535878, 89863.381050732), ...


3

The key information is here: I am also able to get OGR formats: ogrinfo --formats prints a bunch of them in the Windows cmd (with no FileGDB there though). This tells me that your GDAL_DRIVER_PATH environment variable is not set. See the instructions at https://trac.osgeo.org/gdal/wiki/FileGDB#Testingthedriver. Once "FileGDB" shows in ogrinfo --formats ...


0

As of ArcGIS Server 10.3, several Python-based command line utilities come bundled with ArcGIS server. Per esri's documentation they are usually installed here: C:\Program Files\ArcGIS\Server\tools\admin The manage service utility is great for starting, stopping or deleting services: python manageservice.py -u admin -p admin -s ...


2

I've also created a script that creates a Network Dataset using comtypes and arcobjects COM Objects. The information posted here, these two GIS-se posts and the ArcGIS tutorial linked in the question were extremely helpful me in putting this together. I went into a little more depth in configuring the network attributes and other settings of the Network ...


0

You have to choose GRASS commands -> v.generalize. In parameters you need to choose Input polygon and one of the simplifications methods. Personaly I prefer snakes because it creates very nice smoothed border.


1

As of one week ago, this can now be achieved with the development version of mapview: # devtools::install_github("environmentalinformatics-marburg/mapview", ref = "develop") library(mapview) library(sp) # video pt <- data.frame(x = 174.764474, y = -36.877245) coordinates(pt) <- ~ x + y proj4string(pt) <- "+init=epsg:4326" mapview(pt, popup = ...


1

Another thing to try if you're using a standard query is creating a materialized view from the query, and building your tiles from that: http://www.postgresql.org/docs/9.3/static/sql-creatematerializedview.html What this will do is make you a table that stores the query (so you could potentially update it in the future). Make sure you have spatial indices ...



Top 50 recent answers are included