‘module’ object has no attribute ‘MStatus' in Maya python Api 2020 - python

I am trying to build a command in python for Maya following a course on youtube and it's showing this error "# Error: RuntimeError: file line 2: AttributeError: file C:/Users/saeed/OneDrive/Documents/maya/2020/Plugins/vertexParticle.py line 23: 'module' object has no attribute 'MStatus' # "
I checked Maya API documents and we should have "MStatus" class but I have no idea why it's not accepted, I tried to use "MStatusCode" and it's showing same error.
from maya import OpenMaya
from maya import OpenMayaMPx
from maya import OpenMayaFX
import sys
commandName = "vertexParticle"
kHelpFlag = "-h"
kHelpLongFlag = "-help"
kSparseFlag = "-s"
kSparseLongFlag = "-sparse"
helpMessage = "This command will attach a particle for each vertex"
class pluginCommand(OpenMayaMPx.MPxCommand):
sparse = None
def __init__(self):
OpenMayaMPx.MPxCommand.__init__(self)
def argumentParser(self, argList):
syntax = self.syntax()
parserArguments = OpenMaya.MArgDatabase(syntax, argList)
if parserArguments.isFlagSet(kSparseFlag):
self.sparse = parserArguments.flagArgumentDouble(kSparseFlag, 0)
return OpenMaya.MStatus.kSuccess
if parserArguments.isFlagSet(kSparseLongFlag):
self.sparse = parserArguments.flagArgumentDouble(kSparseLongFlag, 0)
return OpenMaya.MStatus.kSuccess
if parserArguments.isFlagSet(kHelpFlag):
self.setResult(helpMessage)
return OpenMaya.MStatus.kSuccess
if parserArguments.isFlagSet(kHelpLongFlag):
self.setResult(helpMessage)
return OpenMaya.MStatus.kSuccess
def isUndoable(self):
return True
def undoIt(self):
print "undo"
mFnDagNode = OpenMaya.MFnDagNode(self.mObjParticle)
mDagMod = OpenMaya.MDagModifier()
mDagMod.deleteNode(mFnDagNode.parent(0))
mDagMod.doIt()
return OpenMaya.MStatus.kSuccess
def redoIt(self):
mSel = OpenMaya.MSelectionList()
mDagPath = OpenMaya.MDagPath()
mFnMesh = OpenMaya.MFnMesh()
OpenMaya.MGlobal.getActiveSelectionList(mSel)
if mSel.length() >= 1:
try:
mSel.getDagPath(0, mDagPath)
mFnMesh.setObject(mDagPath)
except:
print "please select a poly mesh"
return OpenMaya.MStatus.kUnknownParameter
else:
print "please select a poly mesh"
return OpenMaya.MStatus.kUnknownParameter
mPointArray = OpenMaya.MPointArray()
mFnMesh.getPoints(mPointArray, OpenMaya.MSpace.kWorld)
mFnParticle = OpenMayaFX.MFnParticleSystem()
self.mObjParticle = mFnParticle.create()
mFnParticle = OpenMayaFX.MFnParticleSystem(self.mObjParticle)
counter == 0
for i in xrange(mPointArray.length()):
if i%self.sparse == 0:
mFnParticle.emit(mPointArray[i])
counter += 1
print "total points :" + str(counter)
mFnParticle.saveInitialState()
return OpenMaya.MStatus.kSuccess
def doIt(self, argList):
self.argumentParser(argList)
if self.sparse != None:
self.redoIt()
return OpenMaya.MStatus.kSuccess
def cmdCreator():
return OpenMayaMPx.asMPxPtr(pluginCommand())
def syntaxCreator():
syntax = OpenMaya.MSyntax()
syntax.addFlag(kHelpFlag, kHelpLongFlag)
syntax.addFlag(kSparseFlag, kSparseLongFlag, OpenMaya.MSyntax.kDouble)
return syntax
def initializePlugin(mObject):
mPlugin = OpenMayaMPx.MFnPlugin(mObject)
try:
mPlugin.registerCommand(commandName, cmdCreator, syntaxCreator)
except:
sys.stderr.write("Failed to register" + commandName)
def uninitializePlugin(mObject):
mPlugin = OpenMayaMPx.MFnPlugin(pluginCommand())
try:
mPlugin.deregisterCommand(commandName)
except:
sys.stderr.write("Failed to deregister" + commandName)

Because MStatus.MStatusCode is an enum, you can return its integer value in Python. The only issue is that because in C++ this is an enum, there is no guarantee that the values won't change/shift between releases. This enum has remained consistent since 2019, so there isn't much risk of this happening for MStatus.MStatusCode.
https://help.autodesk.com/view/MAYAUL/2019/ENU/?guid=__cpp_ref_class_m_status_html
https://help.autodesk.com/view/MAYAUL/2023/ENU/?guid=Maya_SDK_cpp_ref_class_m_status_html
Somewhere in the top of your file simply add the constants you intend to use:
MStatus_kSuccess = 0
MStatus_kFailure = 1
MStatus_kUnknownParameter = 5
Then return the constant instead in your functions:
if parserArguments.isFlagSet(kHelpFlag):
self.setResult(helpMessage)
return MStatus_kSuccess

Related

Python, SqlAlchemy. Or_ expected 2 arguments, got 3

I have this problem with my code. When Iinsert three or more params in the body request, I get this Error "POST Error: or_ expected 2 arguments, got 3."
I can only pass one or two parameters in the body, in this case it works fine. But I don't understand where is the mistake. Can someone help me?
def read_uptime(logid, filteredData, dateStart, dateEnd, timeStart, timeEnd, elementsForPage, currentPage, filterUptime):
log.info(f"{logid} read_uptime: Started")
try:
# Check Timeframe Correct
startDateTime, endDateTime = _checkDataInput(timeStart, timeEnd, dateStart, dateEnd)
# Create Filter
filters = _createFilter(filteredData, startDateTime, endDateTime, filterUptime)
# Query
dataFiltered = uptime_model_db.query.with_entities(
uptime_model_db.projectId.label('projectId'),
uptime_model_db.url.label('url'),
uptime_model_db.timeStamp.label('timeStamp'),
uptime_model_db.uptime.label('uptime'),
uptime_model_db.latency.label('latency')
).filter(*filters).paginate(per_page=int(elementsForPage + 1), page=int(currentPage), error_out=True)
# Checking more pages
nextPage = {
"currentPage": currentPage,
"totalElements": len(dataFiltered.items)
}
if (len(dataFiltered.items) > elementsForPage):
nextPage["nextPage"] = True
else:
nextPage["nextPage"] = False
# Format and return JSON
return _createJson(dataFiltered.items, nextPage)
except Exception as e:
log.error(f"{logid} read_uptime: function read_uptime returned {e}")
raise e
i get in this code the mistake: "array.Filter.append(and_(uptime_model.db.porjectId == projectId, or_(*arrayUrl))"
def filterAppend(arrayFilter, urls, projectId, arrayUrl):
if(len(urls) == 1):
arrayFilter.append(and_(uptime_model_db.projectId == projectId, uptime_model_db.url == urls[0]))
if(len(urls) > 1):
for url in urls:
arrayUrl.append(uptime_model_db.url == url)
arrayFilter.append(and_(uptime_model_db.projectId == projectId, or_(*arrayUrl)))
i get in this code the mistake:
"filters.append(or_(*arrayFilter))"
def _createFilter(filteredData, startDateTime, endDateTime, filterUptime):
filters = []
if filteredData is not None:
arrayFilter = []
for data in filteredData:
projectId = data["projectId"]
urls = data["uptimeUrls"]
arrayUrl = []
if (len(filteredData) == 1):
filterAppend(filters, urls, projectId, arrayUrl)
else:
filterAppend(arrayFilter, urls, projectId, arrayUrl)
if(len(filteredData) > 1 or len(arrayFilter) > 1):
filters.append(or_(*arrayFilter))
if startDateTime is not None:
filters.append(str(startDateTime) <= uptime_model_db.timeStamp)
if startDateTime is not None:
filters.append(str(endDateTime) >= uptime_model_db.timeStamp)
if filterUptime == "True":
filters.append(uptime_model_db.uptime < 100)
return filters
import or_ from sqlalchemy instead of operators:
from sqlalchemy import or_

JSON - TypeError: 'NoneType' object is not subscriptable

I am outputting the results of my machine learning model into a JSON file but my python code isn't parsing the file correctly. I don't know what is causing it but I know it is my python code and not anything on the ML side of it The code is supposed to run through the JSON file and find out if the results are within a certain distance of each other (0.10).
My Error:
File "vision.py", line 102, in <module>
find_xy(18, 18)
File "vision.py", line 61, in find_xy
x_dif = obj1["relative_coordinates"]["center_x"] - obj2["relative_coordinates"]["center_x"]
TypeError: 'NoneType' object is not subscriptable
My JSON file(result.json):
[
{
"frame_id":1,
"filename":"Captures/Capevent4/capture0.png",
"objects": [
{"class_id":17, "name":"g ", "relative_coordinates":{"center_x":0.789288, "center_y":0.412911, "width":0.339110, "height":0.789139}, "confidence":0.986945},
{"class_id":17, "name":"g ", "relative_coordinates":{"center_x":0.657672, "center_y":0.411369, "width":0.226476, "height":0.744315}, "confidence":0.532443},
{"class_id":17, "name":"g ", "relative_coordinates":{"center_x":0.736259, "center_y":0.559810, "width":0.409916, "height":0.651102}, "confidence":0.474929}
]
}
]
My Code:
Save New Duplicate & Edit Just Text Twitter
results_path = r'result.json'
# function for formatting after every new picture is run through model
with open(results_path, 'r') as opened_results:
results = json.load(opened_results)
with open(results_path, "w") as opened_results:
json.dump(results, opened_results, indent=4)
def find_xy(id1, id2):
desired_id1 = id1
obj1 = None
for thing in results:
for object1 in thing["objects"]:
if object1["class_id"] == desired_id1:
specific_class = object1
obj1 = object1
print("Correct Class")
break
for _class in results:
for object1 in _class["objects"]:
relative_coordinates = object1["relative_coordinates"]
center_x = relative_coordinates["center_x"]
center_y = relative_coordinates["center_y"]
# Do something with these values
desired_id2 = id2
obj2 = None
for thing in results:
for object2 in thing["objects"]:
if object2["class_id"] == desired_id2:
specific_class = object2
obj2 = object2
print("Correct Class")
break
for _class in results:
for object2 in _class["objects"]:
relative_coordinates = object2["relative_coordinates"]
center_x = relative_coordinates["center_x"]
center_y = relative_coordinates["center_y"]
x_dif = obj1["relative_coordinates"]["center_x"] - obj2["relative_coordinates"]["center_x"]
x_absolute_dif = abs(x_dif)
print("X Absolute Dif Is:" + str(x_absolute_dif))
if (x_absolute_dif <= 0.10):
print("X-Cords Within Range")
x_within_range = True
else:
print("X-Cords Not Within Range")
x_within_range = False
y_dif = obj1["relative_coordinates"]["center_y"] - obj2["relative_coordinates"]["center_y"]
y_absolute_dif = abs(y_dif)
print("Y Absolute Difference Is: " + str(y_absolute_dif))
if (y_absolute_dif <= 0.10):
print("Y-Cords Within Range")
y_within_range = True
else:
print("Y-Cords Not Within Range")
y_within_range = False
Okay, I found something.
"class_id":17...
"class_id":17...
"class_id":17...
All objects have the same ID? Is it correct so or not?
You need a check if block or use a try except.
if block
if obj1 == None:
print("No, obj1 found!")
exit(0)
try catch
try:
relative_coordinates = object1["relative_coordinates"]
except:
print("No, obj1 found!")
exit(0)
If you search find_xy(18, 18) and you have only "class_id":17 - that can only go wrong without a break position. So you must check if your variable still Nothing or not!
One point more
Duplicate code is also bad. Make a function for these, than you can read your code easier!
def check_obj():
#do you staff here...

Run python script to replace betacode with greek letters LaTeX

I want to convert the betacode in an existing .tex-File to normal greek letters.
For example: I want to replace:
\bcode{lo/gos}
with simple:
λόγος
And so on for all other glyphs. Fortunately there seems to be a python-script that is supposed to do just that. But, being completely inexperienced I simply don’t know how to run it.
Here is the code of the python sript:
# beta2unicode.py
#
# Version 2004-11-23
#
# James Tauber
# http://jtauber.com/
#
# You are free to redistribute this, but please inform me of any errors
#
# USAGE:
#
# trie = beta2unicodeTrie()
# beta = "LO/GOS\n";
# unicode, remainder = trie.convert(beta)
#
# - to get final sigma, string must end in \n
# - remainder will contain rest of beta if not all can be converted
class Trie:
def __init__(self):
self.root = [None, {}]
def add(self, key, value):
curr_node = self.root
for ch in key:
curr_node = curr_node[1].setdefault(ch, [None, {}])
curr_node[0] = value
def find(self, key):
curr_node = self.root
for ch in key:
try:
curr_node = curr_node[1][ch]
except KeyError:
return None
return curr_node[0]
def findp(self, key):
curr_node = self.root
remainder = key
for ch in key:
try:
curr_node = curr_node[1][ch]
except KeyError:
return (curr_node[0], remainder)
remainder = remainder[1:]
return (curr_node[0], remainder)
def convert(self, keystring):
valuestring = ""
key = keystring
while key:
value, key = self.findp(key)
if not value:
return (valuestring, key)
valuestring += value
return (valuestring, key)
def beta2unicodeTrie():
t = Trie()
t.add("*A", u"\u0391")
t.add("*B", u"\u0392")
t.add("*G", u"\u0393")
t.add("*D", u"\u0394")
t.add("*E", u"\u0395")
t.add("*Z", u"\u0396")
t.add("*H", u"\u0397")
t.add("*Q", u"\u0398")
t.add("*I", u"\u0399")
t.add("*K", u"\u039A")
t.add("*L", u"\u039B")
t.add("*M", u"\u039C")
t.add("*N", u"\u039D")
t.add("*C", u"\u039E")
t.add("*O", u"\u039F")
t.add("*P", u"\u03A0")
t.add("*R", u"\u03A1")
t.add("*S", u"\u03A3")
t.add("*T", u"\u03A4")
t.add("*U", u"\u03A5")
t.add("*F", u"\u03A6")
t.add("*X", u"\u03A7")
t.add("*Y", u"\u03A8")
t.add("*W", u"\u03A9")
t.add("A", u"\u03B1")
t.add("B", u"\u03B2")
t.add("G", u"\u03B3")
t.add("D", u"\u03B4")
t.add("E", u"\u03B5")
t.add("Z", u"\u03B6")
t.add("H", u"\u03B7")
t.add("Q", u"\u03B8")
t.add("I", u"\u03B9")
t.add("K", u"\u03BA")
t.add("L", u"\u03BB")
t.add("M", u"\u03BC")
t.add("N", u"\u03BD")
t.add("C", u"\u03BE")
t.add("O", u"\u03BF")
t.add("P", u"\u03C0")
t.add("R", u"\u03C1")
t.add("S\n", u"\u03C2")
t.add("S,", u"\u03C2,")
t.add("S.", u"\u03C2.")
t.add("S:", u"\u03C2:")
t.add("S;", u"\u03C2;")
t.add("S]", u"\u03C2]")
t.add("S#", u"\u03C2#")
t.add("S_", u"\u03C2_")
t.add("S", u"\u03C3")
t.add("T", u"\u03C4")
t.add("U", u"\u03C5")
t.add("F", u"\u03C6")
t.add("X", u"\u03C7")
t.add("Y", u"\u03C8")
t.add("W", u"\u03C9")
t.add("I+", U"\u03CA")
t.add("U+", U"\u03CB")
t.add("A)", u"\u1F00")
t.add("A(", u"\u1F01")
t.add("A)\\", u"\u1F02")
t.add("A(\\", u"\u1F03")
t.add("A)/", u"\u1F04")
t.add("A(/", u"\u1F05")
t.add("E)", u"\u1F10")
t.add("E(", u"\u1F11")
t.add("E)\\", u"\u1F12")
t.add("E(\\", u"\u1F13")
t.add("E)/", u"\u1F14")
t.add("E(/", u"\u1F15")
t.add("H)", u"\u1F20")
t.add("H(", u"\u1F21")
t.add("H)\\", u"\u1F22")
t.add("H(\\", u"\u1F23")
t.add("H)/", u"\u1F24")
t.add("H(/", u"\u1F25")
t.add("I)", u"\u1F30")
t.add("I(", u"\u1F31")
t.add("I)\\", u"\u1F32")
t.add("I(\\", u"\u1F33")
t.add("I)/", u"\u1F34")
t.add("I(/", u"\u1F35")
t.add("O)", u"\u1F40")
t.add("O(", u"\u1F41")
t.add("O)\\", u"\u1F42")
t.add("O(\\", u"\u1F43")
t.add("O)/", u"\u1F44")
t.add("O(/", u"\u1F45")
t.add("U)", u"\u1F50")
t.add("U(", u"\u1F51")
t.add("U)\\", u"\u1F52")
t.add("U(\\", u"\u1F53")
t.add("U)/", u"\u1F54")
t.add("U(/", u"\u1F55")
t.add("W)", u"\u1F60")
t.add("W(", u"\u1F61")
t.add("W)\\", u"\u1F62")
t.add("W(\\", u"\u1F63")
t.add("W)/", u"\u1F64")
t.add("W(/", u"\u1F65")
t.add("A)=", u"\u1F06")
t.add("A(=", u"\u1F07")
t.add("H)=", u"\u1F26")
t.add("H(=", u"\u1F27")
t.add("I)=", u"\u1F36")
t.add("I(=", u"\u1F37")
t.add("U)=", u"\u1F56")
t.add("U(=", u"\u1F57")
t.add("W)=", u"\u1F66")
t.add("W(=", u"\u1F67")
t.add("*A)", u"\u1F08")
t.add("*)A", u"\u1F08")
t.add("*A(", u"\u1F09")
t.add("*(A", u"\u1F09")
#
t.add("*(\A", u"\u1F0B")
t.add("*A)/", u"\u1F0C")
t.add("*)/A", u"\u1F0C")
t.add("*A(/", u"\u1F0F")
t.add("*(/A", u"\u1F0F")
t.add("*E)", u"\u1F18")
t.add("*)E", u"\u1F18")
t.add("*E(", u"\u1F19")
t.add("*(E", u"\u1F19")
#
t.add("*(\E", u"\u1F1B")
t.add("*E)/", u"\u1F1C")
t.add("*)/E", u"\u1F1C")
t.add("*E(/", u"\u1F1D")
t.add("*(/E", u"\u1F1D")
t.add("*H)", u"\u1F28")
t.add("*)H", u"\u1F28")
t.add("*H(", u"\u1F29")
t.add("*(H", u"\u1F29")
t.add("*H)\\", u"\u1F2A")
t.add(")\\*H", u"\u1F2A")
t.add("*)\\H", u"\u1F2A")
#
t.add("*H)/", u"\u1F2C")
t.add("*)/H", u"\u1F2C")
#
t.add("*)=H", u"\u1F2E")
t.add("(/*H", u"\u1F2F")
t.add("*(/H", u"\u1F2F")
t.add("*I)", u"\u1F38")
t.add("*)I", u"\u1F38")
t.add("*I(", u"\u1F39")
t.add("*(I", u"\u1F39")
#
#
t.add("*I)/", u"\u1F3C")
t.add("*)/I", u"\u1F3C")
#
#
t.add("*I(/", u"\u1F3F")
t.add("*(/I", u"\u1F3F")
#
t.add("*O)", u"\u1F48")
t.add("*)O", u"\u1F48")
t.add("*O(", u"\u1F49")
t.add("*(O", u"\u1F49")
#
#
t.add("*(\O", u"\u1F4B")
t.add("*O)/", u"\u1F4C")
t.add("*)/O", u"\u1F4C")
t.add("*O(/", u"\u1F4F")
t.add("*(/O", u"\u1F4F")
#
t.add("*U(", u"\u1F59")
t.add("*(U", u"\u1F59")
#
t.add("*(/U", u"\u1F5D")
#
t.add("*(=U", u"\u1F5F")
t.add("*W)", u"\u1F68")
t.add("*W(", u"\u1F69")
t.add("*(W", u"\u1F69")
#
#
t.add("*W)/", u"\u1F6C")
t.add("*)/W", u"\u1F6C")
t.add("*W(/", u"\u1F6F")
t.add("*(/W", u"\u1F6F")
t.add("*A)=", u"\u1F0E")
t.add("*)=A", u"\u1F0E")
t.add("*A(=", u"\u1F0F")
t.add("*W)=", u"\u1F6E")
t.add("*)=W", u"\u1F6E")
t.add("*W(=", u"\u1F6F")
t.add("*(=W", u"\u1F6F")
t.add("A\\", u"\u1F70")
t.add("A/", u"\u1F71")
t.add("E\\", u"\u1F72")
t.add("E/", u"\u1F73")
t.add("H\\", u"\u1F74")
t.add("H/", u"\u1F75")
t.add("I\\", u"\u1F76")
t.add("I/", u"\u1F77")
t.add("O\\", u"\u1F78")
t.add("O/", u"\u1F79")
t.add("U\\", u"\u1F7A")
t.add("U/", u"\u1F7B")
t.add("W\\", u"\u1F7C")
t.add("W/", u"\u1F7D")
t.add("A)/|", u"\u1F84")
t.add("A(/|", u"\u1F85")
t.add("H)|", u"\u1F90")
t.add("H(|", u"\u1F91")
t.add("H)/|", u"\u1F94")
t.add("H)=|", u"\u1F96")
t.add("H(=|", u"\u1F97")
t.add("W)|", u"\u1FA0")
t.add("W(=|", u"\u1FA7")
t.add("A=", u"\u1FB6")
t.add("H=", u"\u1FC6")
t.add("I=", u"\u1FD6")
t.add("U=", u"\u1FE6")
t.add("W=", u"\u1FF6")
t.add("I\\+", u"\u1FD2")
t.add("I/+", u"\u1FD3")
t.add("I+/", u"\u1FD3")
t.add("U\\+", u"\u1FE2")
t.add("U/+", u"\u1FE3")
t.add("A|", u"\u1FB3")
t.add("A/|", u"\u1FB4")
t.add("H|", u"\u1FC3")
t.add("H/|", u"\u1FC4")
t.add("W|", u"\u1FF3")
t.add("W|/", u"\u1FF4")
t.add("W/|", u"\u1FF4")
t.add("A=|", u"\u1FB7")
t.add("H=|", u"\u1FC7")
t.add("W=|", u"\u1FF7")
t.add("R(", u"\u1FE4")
t.add("*R(", u"\u1FEC")
t.add("*(R", u"\u1FEC")
# t.add("~", u"~")
# t.add("-", u"-")
# t.add("(null)", u"(null)")
# t.add("&", "&")
t.add("0", u"0")
t.add("1", u"1")
t.add("2", u"2")
t.add("3", u"3")
t.add("4", u"4")
t.add("5", u"5")
t.add("6", u"6")
t.add("7", u"7")
t.add("8", u"8")
t.add("9", u"9")
t.add("#", u"#")
t.add("$", u"$")
t.add(" ", u" ")
t.add(".", u".")
t.add(",", u",")
t.add("'", u"'")
t.add(":", u":")
t.add(";", u";")
t.add("_", u"_")
t.add("[", u"[")
t.add("]", u"]")
t.add("\n", u"")
return t
t = beta2unicodeTrie()
import sys
for line in file(sys.argv[1]):
a, b = t.convert(line)
if b:
print a.encode("utf-8"), b
raise Exception
print a.encode("utf-8")
And here is a little .tex-file with which it should work.
\documentclass[12pt]{scrbook}
\usepackage[polutonikogreek, ngerman]{babel}
\usepackage[ngerman]{betababel}
\usepackage{fontspec}
%\defaultfontfeatures{Ligatures=TeX}
%\newfontfeature{Microtype}{protrusion=default;expansion=default;}
\begin{document}
\bcode{lo/gos}
\end{document}
In case the script does not work: would it be possible to convert all the strings within the \bcode-Makro with something like regex? For example the "o/" to the ό and so on? What would be the weapon of choice here?
Do I have python installed?
Try python -V at a shell prompt. Your code is python 2 code, so you will a python 2 version.
I need to install Python
Most straight forward way if you don't need a complex environment (and you don't for this problem) is just to go to python.org. Don't forget you need python 2.
Running the program
Generally it will be as simple as:
python beta2unicode.py myfile.tex-file
And to capture the output:
python beta2unicode.py myfile.tex-file > myfile.not-tex-file
Does the script work?
Almost. You will need to replace the code at the end of the script that starts the same way this does, with this:
import sys
t = beta2unicodeTrie()
import re
BCODE = re.compile(r'\\bcode{[^}]*}')
for line in open(sys.argv[1]):
matches = BCODE.search(line)
for match in BCODE.findall(line):
bcode = match[7:-1]
a, b = t.convert(bcode.upper())
if b:
raise IOError("failed conversion '%s' in '%s'" % (b, line))
converted = a.encode("utf-8")
line = line.replace(match, converted)
print(line.rstrip())
Results
\documentclass[12pt]{scrbook}
\usepackage[polutonikogreek, ngerman]{babel}
\usepackage[ngerman]{betababel}
\usepackage{fontspec}
%\defaultfontfeatures{Ligatures=TeX}
%\newfontfeature{Microtype}{protrusion=default;expansion=default;}
\begin{document}
λόγοσ
\end{document}

AttributeError: 'bool' object has no attribute 'items'

I'm a beginner in python. I'm currently try to deal with use the IK to move the robot arm. When I try to run my program the arm was able to move to the my setted starting position but when it's going to next step it shows me this error:AttributeError: 'bool' object has no attribute 'items'
This is my program:
class Pick_Place (object):
#def __init__(self,limb,hover_distance = 0.15):
def __init__(self,limb):
self._limb = baxter_interface.Limb(limb)
self._gripper = baxter_interface.Gripper(limb)
self._gripper.calibrate(limb)
#self.gripper_open()
#self._verbose = verbose
ns = "ExternalTools/" + limb + "/PositionKinematicsNode/IKService"
self._iksvc = rospy.ServiceProxy(ns,SolvePositionIK)
rospy.wait_for_service(ns, 5.0)
def move_to_start (self,start_angles = None):
print ("moving.....")
if not start_angles:
print ("it is 0")
start_angles = dict(zip(self._joint_names, [0]*7))
self._guarded_move_to_joint_position(start_angles)
self.gripper_open()
rospy.sleep(1.0)
print ("moved!!!")
#########################IK_Server################################################
def ik_request (self,pose):
hdr = Header(stamp=rospy.Time.now(),frame_id='base')
ikreq = SolvePositionIKRequest()
ikreq.pose_stamp.append(PoseStamped(header=hdr, pose=pose))
try:
resp = self._iksvc (ikreq)
except (rospy.ServiceException, rospy.ROSException), e:
rospy.logerr("Service call failed: %s" % (e,))
return False
limb_joints = {}
limb_joints = dict(zip(resp.joints[0].name, resp.joints[0].position))
return limb_joints
###################################################################################
def _guarded_move_to_joint_position(self,joint_angles):
print ("joint position.....")
self._limb.move_to_joint_positions(joint_angles)
def gripper_open (self):
self._gripper.open()
rospy.sleep(1.0)
def gripper_close (self):
self._gripper.close()
rospy.sleep(1.0)
#################################Individual_Motion####################################
def _approach (self, pose):
print ("\nApproaching.....")
approach = copy.deepcopy(pose)
approach.position.z = approach.position.z #+ self._hover_distance
joint_angles = self.ik_request(approach)
self._guarded_move_to_joint_position(joint_angles)
print ("\nApproached.....")
def _retract (self):
print ("\nRetracting.....")
current_pose = self._limb.endpoint_pose()
ik_pose = Pose()
ik_pose.position.x = current_pose['position'].x
ik_pose.position.y = current_pose['position'].y
ik_pose.position.z = current_pose['position'].z #+ self._hover_distance
ik_pose.orientation.x = current_pose['orientation'].x
ik_pose.orientation.y = current_pose['orientation'].y
ik_pose.orientation.z = current_pose['orientation'].z
ik_pose.orientation.w = current_pose['orientation'].w
joint_angles = self.ik_request(ik_pose)
self._guarded_move_to_joint_position(joint_angles)
print ("\nRetracted......")
def _servo_to_pose (self, pose):
print ("\nPosing.....")
joint_angles = self.ik_request(pose)
self._guarded_move_to_joint_position(joint_angles)
print ("\nPosed.....")
##########################Motion_of_pick_and_place#####################################
def pick (self,pose):
print ("\nPicking_1.....")
# open the gripper
self.gripper_open()
# servo above pose
self._approach(pose)
# servo to pose
self._servo_to_pose(pose)
# close gripper
self.gripper_close()
# retract to clear object
self._retract()
print ("\nPicked")
def place (self,pose):
print ("\nPlacing_1.....")
# servo above pose
self._approach(pose)
# servo to pose
self._servo_to_pose(pose)
# open the gripper
self.gripper_open()
# retract to clear object
self._retract()
print ("\nPlaced")
###########################Main_Program############################################
def main():
print ("Initializing....")
rospy.init_node("ylj_ik_traTest")
print("Getting the robot state.....")
rs= baxter_interface.RobotEnable()
print ("Enabling....")
rs.enable()
limb = 'left'
#hover_distance = 0.15
starting_joint_angles = {'left_s0': -0.50,
'left_s1': -1.30,
'left_e0': -0.60,
'left_e1': 1.30,
'left_w0': 0.20,
'left_w1': 1.60,
'left_w2': -0.30}
#pnp = Pick_Place(limb,hover_distance)
pnp = Pick_Place(limb)
overhead_orientation = Quaternion(
x=-0.0249590815779,
y=0.999649402929,
z=0.00737916180073,
w=0.00486450832011)
ball_poses = list()
#1st ball point
ball_poses.append(Pose(
position = Point(x=0.7, y=0.15, z=-0.1),
orientation = overhead_orientation))
#2nd ball point
ball_poses.append(Pose(
position = Point(x=0.75, y=0.0, z=-0.1),
orientation = overhead_orientation))
pnp.move_to_start(starting_joint_angles)
idx = 0
while not rospy.is_shutdown():
print ("\nPicking.....")
pnp.pick(ball_poses[idx])
print ("\nPlacing.....")
idx = (idx+1) % len(ball_poses)#?????
pnp.place(ball_poses[idx])
return 0
if __name__ == '__main__':
sys.exit(main())
And this is the error shows me:
Initializing....
Getting the robot state.....
Enabling....
[INFO] [WallTime: 1466477391.621678] Robot Enabled
moving.....
joint position.....
moved!!!
Picking.....
Picking_1.....
Approaching.....
joint position.....
Traceback (most recent call last):
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 197, in <module>
sys.exit(main())
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 188, in main
pnp.pick(ball_poses[idx])
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 122, in pick
self._approach(pose)
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 88, in _approach
self._guarded_move_to_joint_position(joint_angles)
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 72, in _guarded_move_to_joint_position
self._limb.move_to_joint_positions(joint_angles)
File "/home/baxter/ros_ws/src/baxter_interface/src/baxter_interface/limb.py", line 368, in move_to_joint_positions
diffs = [genf(j, a) for j, a in positions.items() if
AttributeError: 'bool' object has no attribute 'items'
Does anyone had met this kind of error before? Please help me, thank you.
The error tells you that booleans (either True or False) don't have an attribute "items".
When you call
self._limb.move_to_joint_positions(joint_angles) you are passing the argument "joint_angles" which becomes "positions" in the function
move_to_joint_positions().
Looking into the source code of the library you're using, it tells you what it wants positions to be:
#type positions: dict({str:float})
In short, it wants joint_angles to be a dictionary mapping strings to floats and you passed a boolean. Let's look into how you got joint_angles:
joint_angles = self.ik_request(ik_pose)
In the body of your method, you return False every time:
def ik_request (self,pose):
...
except (rospy.ServiceException, rospy.ROSException), e:
rospy.logerr("Service call failed: %s" % (e,))
return False
Returning a boolean is clearly not what you want to do, and it is the cause of this error.
You're trying to access the elements of a boolean value, which is not allowed. In your example, positions is a true/false value and not what you're expecting it to be. There's some section of the code where positions is being assigned to a boolean. You should walk through your code and look for any line that contains positions = something.

Does Python 3 have LDAP module?

I am porting some Java code to Python and we would like to use Python 3 but I can't find LDAP module for Python 3 in Windows.
This is forcing us to use 2.6 version and it is bothersome as rest of the code is already in 3.0 format.
You may use ldap3 module (formerly known as python3-ldap), it runs on python3 really well and requires no external C dependances. Also it can correctly handle both unicode and byte data in ldap records (in early versions there was a trouble with jpegPhoto field, now everything is fine)
If you're running this on Windows, you can get LDAP to work in Python 3.1 by using the ADO access method via Mark Hammond's PyWin32.
To test this, I installed ActiveState Python 3.1, then installed PyWin32 for Python 3.1
http://sourceforge.net/projects/pywin32/files/
I was then able to run LDAP queries using a module I wrote that is based on this LDAP code from the ActiveState Python Cookbook:
Recipe 511451: Dump all Active Directory Information using LDAP scripting by Manuel Garcia
http://code.activestate.com/recipes/511451/
although now that I look at it I realize I completely rewrote my module just using his code as an example.
Update
Here is my LDAPList module and another support module to convert user access bit codes into something a tiny bit more english-like:
LDAPList.py
# LDAPList.py
# Todd Fiske
# class to encapsulate accessing LDAP information
# 2009-03-18 first version
# 2010-01-04 updated for Python 3 (print functions, <> to !=)
import win32com.client
import UACCodes
ADS_SCOPE_SUBTREE = 2
class LDAPList():
def __init__(self, sContext):
self.Context = sContext # naming context, "DC=xyz,DC=org"
self.objectCategory = ""
self.objectClass = ""
self.FilterClause = ""
self.query = ""
self.cn = None
self.cm = None
self.rs = None
def SetCategory(self, sCategory):
self.objectCategory = sCategory
self.FilterClause = "where objectCategory = '%s'" % self.objectCategory
def SetClass(self, sClass):
self.objectClass = sClass
self.FilterClause = "where objectClass = '%s'" % self.objectClass
def open(self):
self.query = "select * from 'LDAP://%s' %s order by displayName" % (self.Context, self.FilterClause)
self.cn = win32com.client.Dispatch("ADODB.Connection")
self.cm = win32com.client.Dispatch("ADODB.Command")
self.cn.Open("Provider=ADsDSOObject")
self.cm.ActiveConnection = self.cn
self.cm.Properties["Page Size"] = 1000
self.cm.Properties["Searchscope"] = ADS_SCOPE_SUBTREE
self.cm.CommandText = self.query
self.rs = self.cm.Execute()[0]
def close(self):
if self.rs is not None:
self.rs.Close()
self.rs = None
if self.cm is not None:
self.cm = None
if self.cn is not None:
self.cn.Close()
self.cn = None
def count(self):
if self.rs is None:
return -2
return self.rs.RecordCount
def more(self):
if self.rs is None:
return False
return not self.rs.EOF
def GetObject(self):
if self.rs is None:
return None
return win32com.client.GetObject(self.rs.Fields["ADsPath"].Value)
def next(self):
if self.rs is None:
return
self.rs.MoveNext()
#----------
# helper functions
def NamingContext():
# return default naming context
root = win32com.client.GetObject("LDAP://RootDse")
return root.get("DefaultNamingContext")
def AccountControl(obj):
if obj.userAccountControl is not None:
return obj.userAccountControl
else:
return 0
def ConvertUAC(nUAC):
return UACCodes.ConvertUAC(nUAC)
def AccountActive(n):
return (n & UACCodes.ADS_UF_ACCOUNTDISABLE) != UACCodes.ADS_UF_ACCOUNTDISABLE
def GetCategory(obj):
# CN=Group,CN=Schema,CN=Configuration,DC=xyz,DC=org
s = obj.objectCategory
s = s.split(",")[0][3:]
return s
# s = "Group"
def GetGroups(obj):
"""
('CN=XYZ Staff Rockville,OU=Distribution Groups,DC=xyz,DC=org',
'CN=XYZ Staff,OU=Distribution Groups,DC=xyz,DC=org')
"""
if obj.memberOf is None:
return ""
if type(obj.memberOf)==type(()):
tGroups = obj.memberOf
else:
tGroups = (obj.memberOf,)
return tGroups
def GetNameParts(obj):
if obj.givenName is None:
sFirst = ""
else:
sFirst = obj.givenName
if obj.middleName is None:
sMiddle = ""
else:
sMiddle = obj.middleName
if obj.sn is None:
sLast = ""
else:
sLast = obj.sn
if sLast == "" and sFirst == "":
if obj.name is not None:
sName = obj.name
sName = sName[3:]
lParts = sName.split(" ")
if len(lParts) == 1:
"todo: split on embedded capital letter"
print("single-part name: %s" % sName)
sFirst = sName
else:
sLast = lParts[-1]
sFirst = " ".join(lParts[:-1])
return (sFirst, sMiddle, sLast)
def GetManager(obj):
if obj.manager is None:
return ""
else:
return obj.manager
#----------
# test
if __name__ == "__main__":
print
print("testing LDAPList class")
nc = NamingContext()
print("context =", nc)
ll = LDAPList(nc)
ll.SetCategory('user')
ll.open() # generates recordset
print("query = %s" % ll.query)
print("%d items" % ll.count())
n = 0
while (n < 10) and (ll.more()):
o = ll.GetObject() # return
nUAC = AccountControl(o)
print("%-30s %-30s %-30s %-40s %s" % (
o.displayName,
o.name,
o.sAMAccountName,
UACCodes.ConvertUAC(nUAC),
GetManager(o)
))
n += 1
ll.next()
ll.close()
###
UACCodes.py
# UACCodes.py
# Todd Fiske
# generated 2009-09-23 16:36:56 by BuildUACCodes.py
# updated 2010-01-04 for Python 3 (print functions)
# provide UAC constants, lookup list, and conversion function
import sys
# UAC Constants
ADS_UF_SCRIPT = 0x00000001
ADS_UF_ACCOUNTDISABLE = 0x00000002
ADS_UF_HOMEDIR_REQUIRED = 0x00000008
ADS_UF_LOCKOUT = 0x00000010
ADS_UF_PASSWD_NOTREQD = 0x00000020
ADS_UF_PASSWD_CANT_CHANGE = 0x00000040
ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0x00000080
ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0x00000100
ADS_UF_NORMAL_ACCOUNT = 0x00000200
ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 0x00000800
ADS_UF_WORKSTATION_TRUST_ACCOUNT = 0x00001000
ADS_UF_SERVER_TRUST_ACCOUNT = 0x00002000
ADS_UF_DONT_EXPIRE_PASSWD = 0x00010000
ADS_UF_MNS_LOGON_ACCOUNT = 0x00020000
ADS_UF_SMARTCARD_REQUIRED = 0x00040000
ADS_UF_TRUSTED_FOR_DELEGATION = 0x00080000
ADS_UF_NOT_DELEGATED = 0x00100000
ADS_UF_USE_DES_KEY_ONLY = 0x00200000
ADS_UF_DONT_REQUIRE_PREAUTH = 0x00400000
ADS_UF_PASSWORD_EXPIRED = 0x00800000
ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0x01000000
# UAC short name lookup list
lUACCodes = [
("ADS_UF_SCRIPT" , 0x00000001, "script"),
("ADS_UF_ACCOUNTDISABLE" , 0x00000002, "disabled"),
("ADS_UF_HOMEDIR_REQUIRED" , 0x00000008, "homedir"),
("ADS_UF_LOCKOUT" , 0x00000010, "lockout"),
("ADS_UF_PASSWD_NOTREQD" , 0x00000020, "pwnotreqd"),
("ADS_UF_PASSWD_CANT_CHANGE" , 0x00000040, "pwcantchange"),
("ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED" , 0x00000080, "encryptedpw"),
("ADS_UF_TEMP_DUPLICATE_ACCOUNT" , 0x00000100, "dupaccount"),
("ADS_UF_NORMAL_ACCOUNT" , 0x00000200, "useracct"),
("ADS_UF_INTERDOMAIN_TRUST_ACCOUNT" , 0x00000800, "interdomain"),
("ADS_UF_WORKSTATION_TRUST_ACCOUNT" , 0x00001000, "workstation"),
("ADS_UF_SERVER_TRUST_ACCOUNT" , 0x00002000, "server"),
("ADS_UF_DONT_EXPIRE_PASSWD" , 0x00010000, "pwnoexpire"),
("ADS_UF_MNS_LOGON_ACCOUNT" , 0x00020000, "mnslogon"),
("ADS_UF_SMARTCARD_REQUIRED" , 0x00040000, "smartcard"),
("ADS_UF_TRUSTED_FOR_DELEGATION" , 0x00080000, "trustdeleg"),
("ADS_UF_NOT_DELEGATED" , 0x00100000, "notdeleg"),
("ADS_UF_USE_DES_KEY_ONLY" , 0x00200000, "deskey"),
("ADS_UF_DONT_REQUIRE_PREAUTH" , 0x00400000, "nopreauth"),
("ADS_UF_PASSWORD_EXPIRED" , 0x00800000, "pwexpired"),
("ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION", 0x01000000, "trustauth"),
]
# UAC conversion function
def ConvertUAC(nUAC):
s = ""
for c in lUACCodes:
if ((nUAC & c[1]) == c[1]):
s = s + c[2] + " "
return s
# test routine
if __name__ == "__main__":
print("UACCodes Test")
print("-------------")
for n in [0, 512, 514, 65535]:
print("%d = %s" % (n, ConvertUAC(n)))
print
for s in sys.argv[1:]:
n = int(s)
print("%d = %s" % (n, ConvertUAC(n)))
###
Both modules have some usage examples and should be fairly easy to figure out, but let me know if you have any questions or comments.
There is a Pure Python implementation of an LDAP client called Ldaptor. I don't think it's maintained though. If you really need it, you might be able to run 2to3 on this and port it.
This answer is no longer accurate; see below for other answers.
Sorry to break this on you, but I don't think there is a python-ldap for Python 3 (yet)...
That's the reason why we should keep active development at Python 2.6 for now (as long as most crucial dependencies (libs) are not ported to 3.0).

Categories

Resources