unable to select layer for a given polygon input in arcpy - python

I have created python script tool and able to select layer by providing feature classes as below.
import arcpy
arcpy.env.workspace = "C:/project/pmms.gdb"
arcpy.SelectLayerByLocation_management('stops', 'intersect', 'adminarea')
But when I used the following code to take user input polygon (FeatureSet), it fails and an error message is given. I have created a parameter of FeatureSet type to allow user to provide interactive polygon input. Please provide your suggestions.
import arcpy
fc = "C:/project/pmms.gdb/stops"
infeat = arcpy.GetParameterAsText(0)
arcpy.SelectLayerByLocation_management(fc, 'intersect', infeat)
Error message:
Traceback (most recent call last):
File "C:\project\scripts\select.py", line 7, in <module>
arcpy.SelectLayerByLocation_management(fc, 'intersect', infeat)
File "c:\program files\arcgis\desktop10.1\arcpy\arcpy\management.py", line 6585, in SelectLayerByLocation
raise e
ExecuteError: Failed to execute. Parameters are not valid.
ERROR 000368: Invalid input data.
Failed to execute (SelectLayerByLocation).

From the ArcGIS help page on the Select Layer By Location function:
The input must be a feature layer; it cannot be a feature class.
Include a Make Feature Layer operation before attempting to select, and it should work as expected.
fc = "C:/project/pmms.gdb/stops"
arcpy.MakeFeatureLayer_management(fc, 'stops')
arcpy.SelectLayerByLocation_management('stops', 'intersect', infeat)
Just make sure you don't already have a layer in your ArcMap table of contents that is called stops (which is presumably why the previous version of your code was working correctly).

Related

Windows device file does not return valid handle with python win32API

I am trying to open a device file in windows using python. I heard I needed to use win32 API. So I am using that, to open my file I need to perform the following this stackoverflow question : Opening a handle to a device in Python on Windows
import win32file as w32
self.receiver_handle = w32.CreateFile("\\\\.\\xillybus_read_32", # file to open
w32.GENERIC_READ, # desired access
w32.FILE_ATTRIBUTE_READONLY, # shared mode
None, # security attribute
w32.OPEN_EXISTING, # creation distribution
w32.FILE_ATTRIBUTE_READONLY, #flags and attributes
None) # no template file
This results in the handle always returning 0.
Here is the API reference: http://winapi.freetechsecrets.com/win32/WIN32CreateFile.htm
The driver came with a barebones C program to test it and it works flawlessly, so it can't be the driver itself that is not properly working.
What am I doing wrong?
The API should not return zero. It should return a PyHANDLE object. I don't have your device, but opening an existing file works. The 3rd parameter should be w32.FILE_SHARE_READ (or similar share mode value), however:
>>> import win32file as w32
>>> w32.CreateFile('blah.txt',w32.GENERIC_READ,w32.FILE_SHARE_READ,None,w32.OPEN_EXISTING,w32.FILE_ATTRIBUTE_READONLY,None)
<PyHANDLE:280>
If the file does not exist (or any other error), Python should raise an exception based on the GetLastError() code returned by the Win32 API called:
>>> w32.CreateFile('blah.txt',w32.GENERIC_READ,w32.FILE_SHARE_READ,None,w32.OPEN_EXISTING,w32.FILE_ATTRIBUTE_READONLY,None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
pywintypes.error: (2, 'CreateFile', 'The system cannot find the file specified.')
If this doesn't help, edit your question to show the exact code you are running and the exact results of running the code.

What is the second argument in QgsProcessingUtils.mapLayerFromString()?

I'm currently trying to select a layer. In Qgis 2, this was done by doing
from qgis import processing
lyrConsumer = processing.getObject('contours-iris-2014')
But now, the documentation says that I have to use QgsProcessingUtils.mapLayerFromString() in Qgis3. Apparently, I need to put a second argument now, as I get this error.
Traceback (most recent call last):
File "C:\OSGEO4~1\apps\Python37\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
TypeError: QgsProcessingUtils.mapLayerFromString(): not enough arguments
What is the second argument?
The second parameter is a QgsProcessingContext(), which lets the algorithm know what is the context in which it will run.
You can set it in this way:
context = QgsProcessingContext()
context.setProject(QgsProject.instance())
QgsProcessingUtils.mapLayerFromString('my_layer', context)
However, since you said you're trying to select a layer, if you're attempting to get a layer from the QGIS layer tree, you can have a look at Getting layer by name in PyQGIS?.
Visit QGIS API Documentation you will find the answer.

Setting up VGG-Face Descriptor in PyTorch

I've been trying to use the VGG-Face descriptor model (http://www.robots.ox.ac.uk/~vgg/software/vgg_face/) for a project of mine. All I want to do is to simply obtain the outputs of the network from an input image.
I haven't used any of MatConvNet, Caffe or PyTorch before and so I picked PyTorch at random. It turns out that the model (of class torch.legacy.nn.Sequential.Sequential) was saved in an older version of PyTorch and the syntax was thus slightly different to the ones on PyTorch's documentation.
I was able to load the lua .t7 model like so:
vgg_net = load_lua('./vgg_face_torch/VGG_FACE.t7', unknown_classes=True)
And loading in the input image:
# load image
image = imread('./ak.png')
# convert to tensor
input = torch.from_numpy(image).float()
Gleefully, I loaded in the image into the model with much anticipation:
# load into vgg_net
output = vgg_net.forward(input)
However, my hopes of it cooperating at all was quickly dashed when the code fails to compile. Leaving behind a cryptic error message:
Traceback (most recent call last):
File "~/Documents/python/vgg-face-test/vgg-pytorch.py", line 25, in <module>
output = vgg_net.forward(input)
File "~/.local/lib/python3.6/site-packages/torch/legacy/nn/Module.py", line 33, in forward
return self.updateOutput(input)
File "~/.local/lib/python3.6/site-packages/torch/utils/serialization/read_lua_file.py", line 235, in updateOutput_patch
return obj.updateOutput(*args)
File "~/.local/lib/python3.6/site-packages/torch/legacy/nn/Sequential.py", line 36, in updateOutput
currentOutput = module.updateOutput(currentOutput)
TypeError: 'NoneType' object is not callable
Of which I am absolutely dumbfounded by.
This is why I sought help on Stackoverflow. I hope someone here could perhaps lend me a hand in setting up the model - not even necessarily in Torch, in fact any working model will do, where I can simply get the description for any particular image.
try output = vgg_net(input) without the forward.
This apparently calls a default method defined in the module but I'm having trouble understanding why this is necessary.

Error for classifier.predict in tensorflow (Shape in shape_and_slice spec does not match)

I am new to tensorflow and to understand the basics I am following a tutorial. When copying this code (https://github.com/random-forests/tutorials/blob/master/ep7.ipynb) and trying to execute it I am getting an error.
W tensorflow/core/framework/op_kernel.cc:993] Invalid argument: Shape in shape_and_slice spec [1,10] does not match the shape stored in checkpoint: [784,10]
Traceback (most recent call last):...
The command which seems to be responsible is the follwing:
classifier.predict(test_data[0])
Can you tell me the problem?
Please try
classifier.predict(np.array([test_data[0]], dtype=float), as_iterable=False)
That worked for me
side note : you have to increase the memory on the raspberry pi to be able to run the example ( and add plt.show() in the display function )
learned it from this site
https://qiita.com/mgr206/items/9fc0de88ff9547372cac
no need for japanese , just check the commands

Using cPickle for multiple regression statsmodel formula in Python Memory Error

I have a multiple linear regression model from the statsmodels and I want to save this model and then use it in a different python script. In looking online it seems that the best way to do this is with cPickle. However, I seem to be getting a Memory error when I try and save this model as a pickle file and an EOFerror when I try and load the cPickled model. I have used cPickle earlier in my code to pickle a list of strings and when I try to load that in my next python script it works just fine. I am not sure why when I try using the same method with my statsmodel that it won't work but the list does. Below is some snippets of my code:
In Python script #1:
import cPickle
import import statsmodels.formula.api as smf
selected = ['name1',....,'name20']
model = smf.ols(formula, data).fit()
cPickle.dump(selected, open('predictors.p', 'w'))
cPickle.dump(model, open('model.p', 'w')) # Here I get a MemoryError
In Python script #2:
predictors = cPickle.load(open('predictors.p','r')) # This works
model = cPickle.load(open('model.p','r')) # This results in an EOFerror
Traceback (most recent call last):
File "MOS_predictor_test.py", line 305, in <module>
model = cPickle.load(open('model.p','r'))
EOFError
How can I save this model and use it in a shorter script? It seems as though cPickle may not be able to store this model because it doesn't have enough memory. Is there something else I can use beside cPickle that will allow me to do what I am trying to do?

Categories