I'm building an app that has a grid of 20x20 labels which I've set as ids id: x1y1, id: x1y2, ... , id: x20y20 etc. I want to be able to reference the id by passing a string, and modify the text within, using something like;
self.ids.name("x1y1").text = "Anything"
I've had a look at dir(self.ids), dir(self.ids.items()) etc but can't seem to figure it out. Is it even possible?
I could create a list of if statements like;
if str(passedString) == "x1y1":
self.id.x1y1.text == "Anything"
if str(passedString) == "x1y2":
self.id.x1y2.text == "Anything"
Although I feel that this is incredibly bad practice, also considering I'd need 400 if statements! - Sure I could write a little helper-script to write all this code out for me, but again, it's not ideal.
EDIT:
I had a look at;
for key, val in self.ids.items():
print("key={0}, val={1}".format(key, val))
Which printed;
key=x1y2, val=<kivy.uix.label.Label object at 0x7f565a34e6d0>
key=x1y3, val=<kivy.uix.label.Label object at 0x7f565a2c1e88>
Might give you/someone an idea of where to go and/or what to do.
You just want to get the reference via a string of the id? You can use normal dictionary lookup (as ids is really a dict).
the_string = 'x1y1'
the_reference = self.ids[the_string]
the_reference.text = 'the_new_text'
Related
Hi i have the following code:
Z = [ [<Entity:0*7fasdas55c:type1101(1101,NGRID)id:-2600>, <Entity:0*5fafaef45c:type1101(1101,NGRID)id:-3665>]
, [<Entity:0*7fasdas55c:type1101(1101,NGRID)id:-5600>, <Entity:0*5fafaef45c:type1101(1101,NGRID)id:-545465>] ]
edge1= ansa.basecollectentity(constant.nastran, Z[0],'NODE')
print(edge1)
and my result is
[<Entity:0*7fasdas55c:type1101(1101,NGRID)id:-2600>, <Entity:0*5fafaef45c:type1101(1101,NGRID)id:-3665>]
Enen though code is written in ansa python, my question is General
I would like to write a code such that it goes through the 'edge1' and prints the number after ids with two different names: like
Node1= 2600
Node2= 3665
Pls help me with writing the code, thanks in advance
Each class controls its own printable representation with the __repr__() special method.
The number you're looking at, id: could potentially be anywhere in the Entity, in any field, or somewhere in an internal datastructure, or nowhere and calculated at display time. It might easily be an id property as #PM2Ring's comment suggests - but it might not be.
So it's either a very specific question - you need to examine the Entity for an appropriate field or method to get the ID. And you haven't said what it is, so that could be anything.
Or it's a general question about processing the repr() value - which is probably not what you want to do ever, really.
But if you did want to, it would be:
for count, item in enumerate(edge1):
id = repr(item).split(':')[-1].rstrip('>')
print "Node" + str(count), id
in ansa say you have a entity eg:
nod=<Entity:0*7fasdas55c:type1101(1101,NGRID)id:-2600>
to print id you can use:
Print(nod._id)
result:
2600
you can also use ._type to get the type of entity you are dealing with
hope it helps
I have many large collections of objects that need to be filtered. I need the filters to be flexible and user definable.
Hard coded, it might look something like:
selected = set()
for o in objects:
if o.someproperty == 'ab':
selected.add(o)
if o.a == 'a' and 'something' in o.b:
selected.add(o)
But I need something I can store in the db.
I've seen something referring to this is the Criteria (or Filter) pattern http://www.tutorialspoint.com/design_pattern/filter_pattern.htm but I can't find much information on it.
I'd like the rules to be flexible and serializable in a simple format.
Maybe the above could look something like:
someproperty == 'ab'
a == 'a', 'something' in b
With each line of the rule being a different set of things that need to meet. If any line in the ruleset matches then the object is included. But should the boolean logic be the other way around (with and between the lines and or within them)? Does this give the flexibility to handle various negations? How would I parse it?
What simple approaches are there to this problem?
A couple of my example uses
# example 1
for o in objects:
if o.width < 1 and o.height < 1:
selected.add(o)
# example 2
for o in objects:
if o.type == 'i' or o.type == 't':
continue
if not o.color:
selected.add(o)
continue
if o.color == 'ffffff':
selected.add(o)
continue
if o.color == '000000':
continue
grey = (o.color[1:3] == o.color[3:5] and o.color[1:3] == o.color[5:7])
if grey:
selected.add(o)
Well, if you want a safe method you don't want to store code in your db.
What you want is a way for the user to specify the properties that can be parsed efficiently and applied as a filter.
I believe it's useless to invent your own language for describing properties. Just use an existing one. For example XML (though I'm not a fan...).
A filter may look like:
<filter name="something">
<or>
<isEqual attrName="someproperty" type="str" value="ab" />
<and>
<isEqual attrName="a" type="str" value="a" />
<contains value="something" type="str" attribute="b" />
</and>
</or>
</filter>
You can then parse the XML to obtain an object representation of the filter.
It shouldn't be hard from this to obtain a piece of code that performs the actions.
For each kind of check you'll have a class that implement that check, and when parsing you replace the nodes with an instance of that class. It should be a very simple thing to do.
In this way the filter is easily modified by anyone who has a little knowledge of XML. Moreover you can extend its logic and you don't have to change the parser for every new construct that you allow.
I am making a renaming script, but I am getting in a bit of trouble with my
Seach and Replace function.
Actually, the function works as long as there are no duplication of the same
object in the hierarchy. For example, as depicted in the attachment, locator1
and locator2 are created from scratch, whereas locator3 is a duplication from
locator2
If I were to display them in their short name, it is as follows:
locator1
locator2
locator2|locator3
So as mentioned, when I tried to replace the word 'locator' to 'Point', the
renaming works for locator 1 and 2, but when it comes to locator3, I got the
error RuntimeError: No object matches name
As such, I was wondering if there is a better way for me to recode, cause in
cases like in Modelling, where artists duplicates the object over and over again
or using of instances..
I know that this fails is due to the short name in itself but is it possible to bypass it?
def searchReplace(self):
wordSearch = str(self.searchTxt.text())
wordReplace = str(self.replaceTxt.text())
objCnt = cmds.ls(sl=True, sn=True)
if len(objCnt) == 0:
self.searchTxt.clear()
self.replaceTxt.clear()
cmds.warning('Nothing is selected')
else:
for wordString in sorted(objCnt):
if wordSearch in wordString:
newWordString = wordString.replace(wordSearch, wordReplace)
cmds.rename(wordString, newWordString)
self.searchTxt.clear()
self.replaceTxt.clear()
print '%s' %wordString + " has changed to : " + "%s" %newWordString
This is a tricky problem, but the solution is actually really simple!
When you sort objCnt, you're doing it lexicographically:
for wordString in sorted(objCnt):
This means that locator2 comes before locator2|locator3. On its own that should be fine, but...
When locator2 is renamed, the path to locator3 has also changed, so accessing it fails.
The trick is to reverse the sort so longer objects come first. That way the children always get renamed before their parents
for wordString in sorted(objCnt, reverse=True):
For this to work, you also need to make sure your ls gives you long names, be adding the long=True argument
I'm probably going about this all wrong but...
I am trying to populate a QTreeView from SQL data - using QAbstractItemModel (and having a great deal of trouble understanding it tbh). One of the tutorials I am following (the simplest) populates the Tree by simply calling new instances of the 'Node' and generating the model from the list. The Node has a name and a parentnode (as below). This is OK where you are generating the data within the program. This I can just about follow :)
However, I want to bring the data in from the table and use a string to identify the correct parentnode - mainly because if I am iterating over the records I won't be able to name each one using a separate variable(?). It will be for x in recs: node = Node("name", parentnode).
When I do this, I get the obvious error message that the string isnt the correct object and has no methods. Is there a way of using a string derived from my table to identify the correct 'parent' object (either that, or could somebody point me in the direction of a very basic Qtreeview model tutorial designed for very enthusiastic, but not necessary gifted learners).
rootNode = Node("Hips")
childNode0 = TransformNode("RightPirateLeg", rootNode)
childNode1 = Node("RightPirateLeg_END", childNode0)
childNode2 = CameraNode("LeftFemur", rootNode)
childNode3 = Node("LeftTibia", childNode2)
childNode4 = Node("LeftFoot", childNode3)
childNode5 = LightNode("LeftFoot_END", childNode4)
I realise that I am probably running before I can walk here and apologise in advance for my ignorance.
Are the strings the names of global variables? If so, you can access the value refenced by the global variable with globals()['name'], (replacing 'name' with the string name of the variable of course.)
Or, better yet, instead of littering variable names all over your global namespace
you could use a dict:
node={}
node['rootNode']=Node('Hips')
node['childNode0']=TransformNode('RightPirateLeg',node['rootNode'])
...
This makes it very easy to map between string names and values.
I'd like to set a cookie via Django with that has several different values to it, similar to .NET's HttpCookie.Values property. Looking at the documentation, I can't tell if this is possible. It looks like it just takes a string, so is there another way?
I've tried passing it an array ([10, 20, 30]) and dictionary ({'name': 'Scott', 'id': 1}) but they just get converted to their string format. My current solution is to just use an arbitrary separator and then parse it when reading it in, which feels icky. If multi-values aren't possible, is there a better way? I'd rather not use lots of cookies, because that would get annoying.
.NETs multi-value cookies work exactly the same way as what you're doing in django using a separator. They've just abstracted that away for you. What you're doing is fine and proper, and I don't think Django has anything specific to 'solve' this problem.
I will say that you're doing the right thing, in not using multiple cookies. Keep the over-the-wire overhead down by doing what you're doing.
If you're looking for something a little more abstracted, try using sessions. I believe the way they work is by storing an id in the cookie that matches a database record. You can store whatever you want in it. It's not exactly the same as what you're looking for, but it could work if you don't mind a small amount of db overhead.
(Late answer!)
This will be bulkier, but you call always use python's built in serializing.
You could always do something like:
import pickle
class MultiCookie():
def __init__(self,cookie=None,values=None):
if cookie != None:
try:
self.values = pickle.loads(cookie)
except:
# assume that it used to just hold a string value
self.values = cookie
elif values != None:
self.values = values
else:
self.values = None
def __str__(self):
return pickle.dumps(self.values)
Then, you can get the cookie:
newcookie = MultiCookie(cookie=request.COOKIES.get('multi'))
values_for_cookie = newcookie.values
Or set the values:
mylist = [ 1, 2, 3 ]
newcookie = MultiCookie(values=mylist)
request.set_cookie('multi',value=newcookie)
Django does not support it. The best way would be to separate the values with arbitrary separator and then just split the string, like you already said.