Hi all,
I wanna show a gtk.Window under a gtk.widget.
But I don't know how to retrieve the gtk.widget's coordinates for my gtk.window.
Anyone knows ?
Thanks.
End of line anchor $ match even there is extra trailing \n in matched string, so we use \Z instead of $
For example
^\w+$ will match the string abcd\n but ^\w+\Z is not
How about \A and when to use?
I just made a fresh copy of eclipse and installed pydev.
In my first trial to use pydev with eclipse, I created 2 module under the src package(the default one)
FirstModule.py:
'''
Created on 18.06.2009
@author: Lars Vogel
'''
def add(a,b):
return a+b
def addFixedValue(a):
y = 5
return y +a
print "123"
run.py:
'''
Created on Jun 20, 2011
@author: Raymond.Yeung
'''
from FirstModule import add
print add(1,2)
print "Helloword"
When I pull out the pull down menu of the run button, and click "ProjectName run.py", here is the result:
123
3
Helloword
Apparantly both module ran, why? Is this the default setting?
I'm have a problem sending data as a file from one end of a socket to the other. What's happening is that both the server and client are trying to read the file so the file never gets sent. I was wondering how to have the client block until the server's completed reading the file sent from the client.
I have this working with raw packets using send and recv, but figured this was a cleaner solution...
Client:
connects to server creating socket connection
creates a file on socket and sends data
waits for file from server
Server:
waits for file from client
Complete interraction:
client sends data to server
server sends data to client
I have a function that attempts to take a list of usernames, look each one up in a user table, and then add them to a membership table. If even one username is invalid, I want the entire list to be rolled back, including any users that have already been processed. I thought that using sessions was the best way to do this but I'm running into a DetachedInstanceError:
DetachedInstanceError: Instance <Organization at 0x7fc35cb5df90> is not bound to a Session; attribute refresh operation cannot proceed
Full stack trace is here.
The error seems to trigger when I attempt to access the user (model) object that is returned by the query. From my reading I understand that it has something to do with there being multiple sessions, but none of the suggestions I saw on other threads worked for me. Code is below:
def add_members_in_bulk(organization_eid, users):
"""Add users to an organization in bulk - helper function for add_member()"""
"""Returns "success" on success and id of first failed student on failure"""
session = query_session.get_session()
session.begin_nested()
users = users.split('\n')
for u in users:
try:
user = user_lookup.by_student_id(u)
except ObjectNotFoundError:
session.rollback()
return u
if user:
membership.add_user_to_organization(
user.entity_id,
organization_eid,
'',
[]
)
session.flush()
session.commit()
return 'success'
here's the membership.add_user_to_organization:
def add_user_to_organization(user_eid, organization_eid, title, tag_ids):
"""Add a User to an Organization with the given title"""
user = user_lookup.by_eid(user_eid)
organization = organization_lookup.by_eid(organization_eid)
new_membership = OrganizationMembership(
organization_eid=organization.entity_id,
user_eid=user.entity_id,
title=title)
new_membership.tags = [get_tag_by_id(tag_id) for tag_id in tag_ids]
crud.add(new_membership)
and here is the lookup by ID query:
def by_student_id(student_id, include_disabled=False):
"""Get User by RIN"""
try:
return get_query_set(include_disabled).filter(User.student_id == student_id).one()
except NoResultFound:
raise ObjectNotFoundError("User with RIN %s does not exist." % student_id)
What I'm trying to do is query the datastore for a model where the key is not the key of an object I already have. Here's some code:
class User(db.Model):
partner = db.SelfReferenceProperty()
def text_message(self, msg):
user = User.get_or_insert(msg.sender)
if not user.partner:
# user doesn't have a partner, find them one
# BUG: this line returns 'user' himself... :(
other = db.Query(User).filter('partner =', None).get()
if other:
# connect users
else:
# no one to connect to!
The idea is to find another User who doesn't have a partner, that isn't the User we already know.
I've tried filter('key !=, user.key()), filter('__key__ !=, user.key()) and a couple others, and nothing returns another User who doesn't have a partner.
filter('foo !=, user.key()) also returns nothing, for the record.
Am running into ValueError, here is the traceback dpaste.com/197332/ .
Am using AutoSlugify , this is my AutoSlugField.py dpaste.com/197330/
Am trying to get the django-tagging system working, this is my models.py
dpaste.com/197331/
Help?
Hi,
I'm trying to implement a shuttle control in wxPython but there doesn't seem to be one. I've decided to use two listbox controls. The shuttle control looks like this:
I've got two listboxes — one's populated, one's not. Could someone show me how to add a selected item to the second list box when it is double clicked? It should be removed from the first. When it is double clicked in the second, it should be added to the first and removed from the second. The shuttle control implements these by default but it's a pity it isn't there.
Thank you.
I'm having a attribute on my model to allow the user to order the objects. I have to update the element's order depending on a list, that contains the object's ids in the new order; right now I'm iterating over the whole queryset and set one objects after the other. What would be the easiest/fastest way to do the same with the whole queryset?
def update_ordering(model, order):
""" order is in the form [id,id,id,id] for example: [8,4,5,1,3] """
id_to_order = dict((order[i], i) for i in range(len(order)))
for x in model.objects.all():
x.order = id_to_order[x.id]
x.save()
I don't think i fully understand character sets so i was wondering if anyone would be kind enough to explain it in layman's terms with examples ( for Dummies).I know there is utf8, latin1, ascii ect
The more answers the better really.
Thank you in advance;-)
I have a code snippet like this
class A(object):
class b:
def print_hello(self):
print "Hello world"
b = property(b)
And I want to override the inner class b (please dont worry about the lowercase name) behaviour. Say, I want to add a new method or I want to change an existing method, like:
class C(A):
class b(A.b):
def print_hello(self):
print "Inner Class: Hello world"
b = property(b)
Now if I create C's object as c = C(), and call c.b I get TypeError: 'property' object is not callable error. How would I get pass this and call print_hello of the extended inner class? Disclaimer: I dont want to change the code for A class.
I've got a class like this:
class Image (models.Model):
...
sizes = ((90,90), (300,250))
def resize_image(self):
for size in sizes:
...
and another class like this:
class SomeClassWithAnImage (models.Model):
...
an_image = models.ForeignKey(Image)
what i'd like to do with that class is this:
class SomeClassWithAnImage (models.Model):
...
an_image = models.ForeignKey(Image, sizes=((90,90), (150, 120)))
where i'm can specify the sizes that i want the Image class to use to resize itself as a argument rather than being hard coded on the class. I realise I could pass these in when calling resize_image if that was called directly but the idea is that the resize_image method is called automatically when the object is persisted to the db.
if I try to pass arguments through the foreign key declaration like this i get an error straight away. is there an easy / better way to do this before I begin hacking down into django?
What is the best way to touch two following values in an numpy array?
example:
npdata = np.array([13,15,20,25])
for i in range( len(npdata) ):
print npdata[i] - npdata[i+1]
this looks really messed up and additionally needs exception code for the last iteration of the loop.
any ideas?
Thanks!
Given a string named line whose raw version has this value:
\rRAWSTRING
how can I detect if it has the escape character \r? What I've tried is:
if repr(line).startswith('\r'):
blah...
but it doesn't catch it. I also tried find, such as:
if repr(line).find('\r') != -1:
blah
doesn't work either. What am I missing?
thx!
Hello good people!
The website of the statistics generator in question is:
http://gitstats.sourceforge.net/
It's git repo can be cloned from:
git clone git://repo.or.cz/gitstats.git
What I want to do is something like:
./gitstatus --ext=".py" /input/foo /output/bar
Failing being able to easily pass the above option without heavy modification, I'd just hardcore the file extentsion I want to be included.
However, I'm unsure of the relevant section of code to modify and even if I did no, I'm unsure of how to start such modifications.
It's seems like it'd be rather simple but alas...
If I have a string, for example which reads: 'Hello how are you today Joe' How am I able to insert spaces into it at regular intervals? So for example I want to insert spaces into it using the range function in these steps: range(0,27,2). So it will look like this:
'He lo ho w ar e yo u to da y Jo e'
It now has a space at every 2nd index going up to it's end. How do I do this does anyone know? thanks.
I'm trying to export data to a csv file. It should contain a header (from datastack) and restacked arrays with my data (from datastack). One line in datastack has the same length as dataset. The code below works but it removes parts of the first line from datastack. Any ideas why that could be?
s = ','.join(itertools.chain(dataset)) + '\n'
newfile = 'export.csv'
f = open(newfile,'w')
f.write(s)
numpy.savetxt(newfile, (numpy.transpose(datastack)), delimiter=', ')
f.close()
Is there a way to pickle a class definition?
What I'd like to do is pickle the definition (which may created dynamically), and then send it over a TCP connection so that an instance can be created on the other end.
I understand that there may be dependencies, like modules and global variables that the class relies on. I'd like to bundle these in the pickling process as well, but I'm not concerned about automatically detecting the dependencies because it's okay if the onus is on the user to specify them.
I have some django code that runs fine on a SQLite database or on a MySQL database, but it runs into problems with Postgres, and it's making me crazy that no one has has this issue before. I think it may also be related to the way querysets are evaluated by the pager.
In a view I have:
def index(request, page=1):
latest_posts = Post.objects.all().order_by('-pub_date')
paginator = Paginator(latest_posts, 5)
try:
posts = paginator.page(page)
except (EmptyPage, InvalidPage):
posts = paginator.page(paginator.num_pages)
return render_to_response('blog/index.html', {'posts' : posts})
And inside the template:
{% for post in posts.object_list %}
{# some rendering jazz #}
{% endfor %}
This works fine with SQLite, but Postgres gives me:
Caught TypeError while rendering: 'NoneType' object is not callable
To further complicate things, when I switch the Queryset call to:
latest_posts = Post.objects.all()
Everything works great. I've tried re-reading the documentation, but found nothing, although I admit I'm a bit clouded by frustration at this point. What am I missing?
Thanks in advance.
Im trying to build a calculator with PyQt4 and connecting the 'clicked()' signals from the buttons doesn't as expected.
Im creating my buttons for the numbers inside a for loop where i try to connect them afterwards.
def __init__(self):
for i in range(0,10):
self._numberButtons += [QPushButton(str(i), self)]
self.connect(self._numberButtons[i], SIGNAL('clicked()'),
lambda : self._number(i))
def _number(self, x):
print(x)
When I click on the buttons all of them print out '9'.
Why is that so and how can i fix this?
I'm new to anything related to servers and am trying to deploy a django application. Today I bought a domain name for the app and am having trouble configuring it so that the base URL does not need the port number at the end of it. I have to type www.trackthecharts.com:8001 to see the website when I only want to use www.trackethecharts.com. I think the problem is somewhere in my nginx, gunicorn or supervisor configuration.
gunicorn_config.py
command = '/opt/myenv/bin/gunicorn'
pythonpath = '/opt/myenv/top-chart-app/'
bind = '162.243.76.202:8001'
workers = 3
root@django-app:~#
nginx config
server {
server_name 162.243.76.202;
access_log off;
location /static/ {
alias /opt/myenv/static/;
}
location / {
proxy_pass http://127.0.0.1:8001;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
}
}
supervisor config
[program:top_chart_gunicorn]
command=/opt/myenv/bin/gunicorn -c /opt/myenv/gunicorn_config.py djangoTopChartApp.wsgi
autostart=true
autorestart=true
stderr_logfile=/var/log/supervisor_gunicorn.err.log
stdout_logfile=/var/log/supervisor_gunicorn.out.log
Thanks for taking a look.
I've been trying for a couple days to figure out why my QAbstractLisModel won't allow a user to toggle a checkable item in three states. The model returns the Qt.IsTristate and Qt.ItemIsUserCheckable in the flags() method, but when the program runs only Qt.Checked and Qt.Unchecked are toggled on edit.
class cboxModel(QtCore.QAbstractListModel):
def __init__(self, parent=None):
super(cboxModel, self).__init__(parent)
self.cboxes = [
['a',0],
['b',1],
['c',2],
['d',0]
]
def rowCount(self,index=QtCore.QModelIndex()):
return len(self.cboxes)
def data(self,index,role):
if not index.isValid: return QtCore.QVariant()
myname,mystate = self.cboxes[index.row()]
if role == QtCore.Qt.DisplayRole:
return QtCore.QVariant(myname)
if role == QtCore.Qt.CheckStateRole:
if mystate == 0:
return QtCore.QVariant(QtCore.Qt.Unchecked)
elif mystate == 1:
return QtCore.QVariant(QtCore.Qt.PartiallyChecked)
elif mystate == 2:
return QtCore.QVariant(QtCore.Qt.Checked)
return QtCore.QVariant()
def setData(self,index,value,role=QtCore.Qt.EditRole):
if index.isValid():
self.cboxes[index.row()][1] = value.toInt()[0]
self.emit(QtCore.SIGNAL("dataChanged(QModelIndex,QModelIndex)"),
index, index)
print self.cboxes
return True
return False
def flags(self,index):
if not index.isValid():
return QtCore.Qt.ItemIsEditable
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsTristate
You can test it with this,
class MainForm(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
model = cboxModel(self)
self.view = QtGui.QListView()
self.view.setModel(model)
self.setCentralWidget(self.view)
app = QtGui.QApplication(sys.argv)
form = MainForm()
form.show()
app.exec_()
and see that only 2 states are available. I'm assuming there's something simple I'm missing. Any ideas? Thanks!
I don't think I'm missing anything. Then again I'm kind of a newbie.
def GET(self, filename):
name = urllib.unquote(filename)
full = path.abspath(path.join(STATIC_PATH, filename))
#Make sure request is not tricksy and tries to get out of
#the directory, e.g. filename = "../.ssh/id_rsa". GET OUTTA HERE
assert full[:len(STATIC_PATH)] == STATIC_PATH, "bad path"
return open(full).read()