I have written this function in a package of mine.
def partitionIntoDays(ls, number, lookupKey=None):
''' Partitions the location measurements into days.
#ls: The list of measurements you want to partition
#return: A dictionary in the format {'Number of partition':
'List of measurements'}'''
if len(ls) == 0:
return {0: []}
firstMidnight = TimeAux.localTimeToEpoch(Delorean(TimeAux.epochToLocalTime(ls[0].time, TIMEZONE)).midnight())
return splitByTimedelta(ls, delta=number*24*3600, lowerBound=firstMidnight, lookupKey=lookupKey)
But whenever I try to call the function from a script I get the following error:
TypeError: partitionIntoDays() got an unexpected keyword argument 'lookupKey'
However if I import the function somewhere manually, I can check that the function has the argument. For example, I can even do this while I am debugging the above error in pdb.
import geogps.Partition as pt
pt.partitionIntoDays.func_code.co_varnames
>>>>('ls', 'number', 'lookupKey', 'firstMidnight')
Also the above code works fine in Python 3.4.
I am in short completely flabbergasted.
So I figured it out: While there were no lingering pyc files, my package structure was messed up and I had an extraneous file in a nested folder.
Thanks #bruno-desthuilliers for pointing me the right way.
Related
Necessarily within a python program and given an str variable that contains C code, I want to check fast if this code is syntactically correct, or not. Essentially, I only need to pass it through the compiler's front end.
My current implementation uses a temp file to dump the string and calls a clang process with subprocess (non-working code below to illustrate my solution). This is very slow for my needs.
src = "int main(){printf("This is a C program\n"); return 0;}"
with open(temp_file, 'w') as f:
f.write(src)
cmd = ["clang", abs_path(f), flags]
subprocess.Popen(cmd)
## etc..
After looking around, I found out about clang.cindex module (pip clang), which I tried out. After reading a bit the main module, lines 2763-2837 (specifically line 2828) led me to the conclusion that the following code snippet will do what I need:
import clang.cindex
......
try:
unit = clang.cindex.TranslationUnit.from_source(temp_code_file, ##args, etc.)
print("Compiled!")
except clang.cindex.TranslationUnitLoadError:
print("Did not compile!")
However, it seems that even if the source file contains obvious syntactic errors, an exception is not raised. Anyone knows what am I missing to make this work ?
On a general context, any suggestions on how to do this task as fast as possible would be more than welcome. Even with clang.cindex, I cannot get away from writing my string-represented code to a temp file, which may be an additional overhead. Writing a python parser could solve this but is an overkill at the moment, no matter how much I need speed.
The compilation itself succeeds even if the file has syntax errors. Consider the following example:
import clang.cindex
with open('broken.c', 'w') as f:
f.write('foo bar baz')
unit = clang.cindex.TranslationUnit.from_source('broken.c')
for d in unit.diagnostics:
print(d.severity, d)
Run it and you will get
3 broken.c:1:1: error: unknown type name 'foo'
3 broken.c:1:8: error: expected ';' after top level declarator
The severity member of is an int, with the value from the enum CXDiagnosticSeverity with values
CXDiagnostic_Ignored = 0
CXDiagnostic_Note = 1
CXDiagnostic_Warning = 2
CXDiagnostic_Error = 3
CXDiagnostic_Fatal = 4
I need to write an optimization file for Gurobi (Python) that is a modified version of a classic TSP. I tried to run the example file from their website:
examples.gurobi.com/traveling-salesman-problem/
I always get the following error:
TypeError: object of type 'NoneType' has no len()
What do I need to change?
Thx
Full code: https://www.dropbox.com/s/ewisx805b3o2wq5/beispiel_opt.py?dl=0
I can confirm the error with the example code from Gurobi's website. At the first look the problem seems to be inside the subtour function, that returns None if sum(lengths) == n and the missing check for if tour is None inside the subtourlim function.
Instead of providing a fix for the specific code, I first checked the examples that Gurobi installs inside the specific installation directory:
Mac: /Library/gurobi810/mac64/examples/python/
Linux: /opt/gurobi800/linux64/examples/python/
Windows: c:\gurobi800\win64\examples\python\
And surprisingly the tsp.py from there runs without any errors. Note also that the two mentioned functions are revised. So I guess the example from the website is just a old version of the code.
I keep trying to run this function:
def flipPic():
#Set up source picture
barbf=getMediaPath("barbara.jpg")
barb=makePicture(barbf)
#Now, for the mirroring
mirrorPoint=219
for X in range(0,mirrorPoint):
for Y in range(0,291):
pleft=getPixel(barb,X,Y)
pright=getPixel(barb,Y,mirrorPoint + mirrorPoint - 1 - X)
setColor(pright,(getColor(pleft)))
show(barb)
return(barb)
However, an error comes up on this line:
barb=makePicture(barbf)
It says:
Inappropriate argument value (of correct type).
An error occurred attempting to pass an argument to a function.
I'm not sure what the issue is as it is written the same way that is in my textbook.
I am still learning how to program in python, is there something I doing wrong?
I'm not sure what library you are using but this is a simple call in Pillow. The commands are these:
out = im.transpose(Image.FLIP_LEFT_RIGHT)
out = im.transpose(Image.FLIP_TOP_BOTTOM)
Taken from this chapter in the docs.
I am using python to read the shapefile, however I meet some problems, this is the core code:
value="#code"
print 'value:',value
if '#' in value:
v=value.replace('#','');
print 'replaced:',v
fixed_value=str(feature.GetFieldAsString(v))
It worked as expected if I run the script directly, but it will throw error once I run it in a web environment, I will get error like this:
File "/home/kk/gis/codes/tilestache/map/__init__.py", line 162, in _get_features
fixed_value=str(feature.GetFieldAsString(v))
File "/usr/local/lib/python2.7/dist-packages/GDAL-1.10.1-py2.7-linux-x86_64.egg/osgeo/ogr.py", line 2233, in GetFieldAsString
return _ogr.Feature_GetFieldAsString(self, *args)
NotImplementedError: Wrong number of arguments for overloaded function 'Feature_GetFieldAsString'.
And if I change the line to :
fixed_value=str(feature.GetFieldAsString('code'))
It worked.
What's going on?
It seems that the replace function in python make things strange.
UPDATE
Seems I get the point,this is caused by the replace function in python which return a different rather than str:
value='#code'
type(value) ==> str
v=value.replace('#','')
type(v) ==>unicode
Then I use:
fixed_value=str(feature.GetFieldAsString(str(v)))
It worked.
But I am not sure why it work in a shell environment but not in a web environment. I hope someone can explain this.
I hope this is an easy one for you guys.
This is my script, for Nuke.
selNodes = nuke.selectedNodes()
for list in selNodes:
if list.Class() == 'Read':
layerArray = []
# Get the list of layers and make unique using set
for chanList in list.channels():
channelLayer = chanList.split('.')
layerArray.append(channelLayer[0])
print list(set(layerArray))
It gives an error:
Traceback (most recent call last):
File "<string>", line 11, in <module>
TypeError: 'Node' object is not callable
So I tried a simpler code of the same nature:
a = [1, 1]
print list(set(a))
And it didn't work. Same error message. Now here's the strange thing: I opened up a new Nuke and ran the simpler codes again, it worked. I couldn't understand why, but I was happy. So I put in my original codes and ran it, error message. I deleted them, the editor is now clean. And ran the simpler code again, error message!!
Which means that a working code can be rendered failure after I pasted and deleted something else!
Can anyone shed some light on this issue? Nuke is a very established software I don't know if it's a software bug.
It is because, you are using list as the loop variable, which hides the builtin function list. You are using that function in
print list(set(layerArray))
The loop variables are leaked even when the loop is over, check this program to understand better
for i in range(10):
pass
print(i)
This will print 9. It means that, i is still available in the program even after the loop is over. The case in your program, after iterating over the selNodes, list variable has the last variable. And you are trying to call that like a function when you say
print list(set(layerArray))
That's why it fails. There are two ways to fix this.
Just change the loop variable to something else.
Use del list when the loop is over. Just pretend that I didn't suggest this. This is NOT recommended. Just change the loop variable to something else.