>>> float(1)
1.0
>>> float(1) / 10
0.10000000000000001
>>> 4 + (float(1) / 10)
4.0999999999999996
4 + (float(1) / 10) is expected to be 4.10000000000000001
Is this a kind of bug?
Hiya.
When I install things into a virtualenv using pip I often see the message "UserWarning: Unbuilt egg for setuptools". I always safely ignore it and go about my business and it doesn't seem to cause me any problems.
But I've suddenly been smacked in the face with curiosity, and wondered if someone could explain what it means, exactly?
Also, does the new virtualenv option to use distribute instead fit into all this somewhere? Should I be using that instead, or just ignoring it until distutils2 comes out? (apologies if that's totally unrelated - maybe it should be a new question?)
Thanks!
i use gaema for twitter user loggin http://code.google.com/p/gaema/
and my code is :
class TwitterAuth(WebappAuth, auth.TwitterMixin):
pass
class TwitterHandler(BaseHandler):
def get(self):
twitter_auth = TwitterAuth(self)
try:
if self.request.GET.get("oauth_token", None):
twitter_auth.get_authenticated_user(self._on_auth)
self.response.out.write('sss')
return
twitter_auth.authorize_redirect()
except RequestRedirect, e:
return self.redirect(e.url, permanent=True)
self.render_template('index.html', user=None)
def _on_auth(self, user):
"""This function is called immediatelly after an authentication attempt.
Use it to save the login information in a session or secure cookie.
:param user:
A dictionary with user data if the authentication was successful,
or ``None`` if the authentication failed.
"""
if user:
# Authentication was successful. Create a session or secure cookie
# to keep the user logged in.
#self.response.out.write('logged in as '+user['first_name']+' '+user['last_name'])
self.response.out.write(user)
return
else:
# Login failed. Show an error message or do nothing.
pass
# After cookie is persisted, redirect user to the original URL, using
# the home page as fallback.
self.redirect(self.request.GET.get('redirect', '/'))
and the error is :
Traceback (most recent call last):
File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__
handler.get(*groups)
File "D:\zjm_code\gaema\demos\webapp\main.py", line 76, in get
twitter_auth.authorize_redirect()
File "D:\zjm_code\gaema\demos\webapp\gaema\auth.py", line 209, in authorize_redirect
http.fetch(self._oauth_request_token_url(), self.async_callback(
File "D:\zjm_code\gaema\demos\webapp\gaema\auth.py", line 239, in _oauth_request_token_url
consumer_token = self._oauth_consumer_token()
File "D:\zjm_code\gaema\demos\webapp\gaema\auth.py", line 441, in _oauth_consumer_token
self.require_setting("twitter_consumer_key", "Twitter OAuth")
TypeError: require_setting() takes at most 2 arguments (3 given)
thanks
I am a django newbie and i was playing around in django's manage.py shell. Here is something i am trying in the shell:
>>> data
[{'primary_program': False, 'id': 3684}, {'primary_program': True, 'id': 3685}]
>>> data[0]
{'primary_program': False, 'id': 3684}
>>> data[1]
{'primary_program': True, 'id': 3685}
>>> data[0].values()
[False, 3684]
>>> data[1].values()
[True, 3685]
>>>
How should i give a command here to update the value of primary_program in data[1] to False and keep the rest of the json the same?
Lets say I have an application with a structure such as:
System
set date
set name
set something
Other
set death ray target
calibrate
and I want to have "back" and "next" buttons on a page. The catch is, if you're going in via the "wizard", I want the nav path to be something like "set name" - "set death ray target" - "set name". If you go via the Advanced options menu, I want to just iterate options... "set date" - "set name" - "set something" - "set death ray target" - calibrate.
So far, I'm thinking I have to use different URIs, but that's that. Any ideia how this could be done?
Thanks.
I have a model form that I use to update a model.
class Turtle(models.Model):
name = models.CharField(max_length=50, blank=False)
description = models.TextField(blank=True)
class TurtleForm(forms.ModelForm):
class Meta:
model = Turtle
Sometimes I don't need to update the entire model, but only want to update one of the fields. So when I POST the form only has information for the description. When I do that the model never saves because it thinks that the name is being blanked out while my intent is that the name not change and just be used from the model.
turtle_form = TurtleForm(request.POST, instance=object)
if turtle_form.is_valid():
turtle_form.save()
Is there any way to make this happen? Thanks!
hi,
just wonder how those air ticket booking website redirect the user to the airline booking website and then fill up(i suppose doing POST) the required information so that the users will land on the booking page with origin/destination/date selected?
Is the technique used is to open up new browser window and do a ajax POST from there?
Thanks.
How can I list the numbers 01 to 12 (one for each of the 12 months) in such a way so that the current month always comes last where the oldest one is first. In other words, if the number is grater than the current month, it's from the previous year.
e.g. 02 is Feb, 2011 (the current month right now), 03 is March, 2010 and 09 is Sep, 2010 but 01 is Jan, 2011. In this case, I'd like to have [09, 03, 01, 02]. This is what I'm doing to determine the year:
for inFile in os.listdir('.'):
if inFile.isdigit():
month = months[int(inFile)]
if int(inFile) <= int(strftime("%m")):
year = strftime("%Y")
else:
year = int(strftime("%Y"))-1
mnYear = month + ", " + str(year)
I don't have a clue what to do next. What should I do here?
Hi,
I am new to Google App Engine,
I have this entites User class -
user_id - integer
user_name - string
password - string
I want to do auto increment for the user_id,How I can do this?
I will have a set of data (x, y, heading), and I need to animate it in real-time. I am currently using matplotlib to animate (x, y) and it works fine, but I would really like to have some way to indicate heading, ie what direction the object is facing. What would be the best library for this? It seems like PyGame might be able to help me out, but would I have to roll out my own graphing library for it?
Thanks
I need to open a file for reading and writing. If the file is not found, it should be created. It should also be treated as a binary for Windows. Can you tell me the file mode sequence I need to use for this?
I tried 'r+ab' but that doesn't create the files if they are not found.
Thanks
After installing the BitTorrent-bencode package, either via easy_install BitTorrent-bencode or pip install BitTorrent-bencode, or by downloading the tarball and installing that via easy_install $tarball, I discover that /usr/local/lib/python2.6/dist-packages/BitTorrent_bencode-5.0.8-py2.6.egg/ contains EGG-INFO/ and test/ directories. Although both of these subdirectories contain files, there are no files in the BitTorr* directory itself. The tarball does contain bencode.py, which is meant to be the actual source for this package, but it's not installed by either of those utils.
I'm pretty new to all of this so I'm not sure if this is a problem with the package or with what I'm doing. The package was packaged a while ago (2007), so perhaps it's using some deprecated configuration aspect that I need to supply a command-line flag for.
I'm more interested in learning what's wrong with either the package or my procedures than in getting this particular package installed; there is another package called hunnyb that seems to do a decent enough job of decoding bencoded data. Mostly I'd like to know how to deal with such problems in other packages.
I have a simple rules/conditions table in my database which is used to generate alerts for one of our systems. I want to create a rules engine or a domain specific language.
A simple rule stored in this table would be..(omitting the relationships here)
if temp > 40 send email
Please note there would be many more such rules. A script runs once daily to evaluate these rules and perform the necessary actions. At the beginning, there was only one rule, so we had the script in place to only support that rule. However we now need to make it more scalable to support different conditions/rules. I have looked into rules engines , but I hope to achieve this in some simple pythonic way. At the moment, I have only come up with eval/exec and I know that is not the most recommended approach. So, what would be the best way to accomplish this??
( The rules are stored as data in database so each object like "temperature", condition like "/=..etc" , value like "40,50..etc" and action like "email, sms, etc.." are stored in the database, i retrieve this to form the condition...if temp 50 send email, that was my idea to then use exec or eval on them to make it live code..but not sure if this is the right approach )
I'm trying to make a very large file editor (where the editor only stores a part of the buffer in memory at a time), but I'm stuck while building my textview object. Basically- I know that I have to be able to update the text view buffer dynamically, and I don't know hot to get the scrollbars to relate to the full file while the textview contains only a small buffer of the file.
I've played with Gtk.Adjustment on a Gtk.ScrolledWindow and ScrollBars, but though I can extend the range of the scrollbars, they still apply to the range of the buffer and not the filesize (which I try to set via Gtk.Adjustment parameters) when I load into textview. I need to have a widget that "knows" that it is looking at a part of a file, and can load/unload buffers as necessary to view different parts of the file. So far, I believe I'll respond to the "change_view" to calculate when I'm off, or about to be off the current buffer and need to load the next, but I don't know how to get the scrollbars to have the top relate to the beginning of the file, and the bottom relate to the end of the file, rather than to the loaded buffer in textview.
Any help would be greatly appreciated, thanks!
import math
def area(base, height):
'''(number,number) -> number
Return the area of a wirh given base and height.
>>>area(10,40)
200.0
'''
return base * height / 2
def perimeter(side1, side2, side3):
'''(number,number,number) -> number
Return the perimeter of the triangle with sides of
length side1,side2 and side3.
>>>perimeter(3,4,5)
12
>>>perimeter(10.5,6,9.3)
25.8
'''
return (side1 + side2 + side3)
def semiperimeter(side1, side2, side3):
return perimeter(side1, side2, side3) / 2
def area_hero(side1, side2, side3):
semi = semiperimeter(side1, side2, side3)
area = math.sqrt((semi * (semi - side1) * (semi - side2) * (semi - side3))
return area
I'm trying to use Eclipse + PyDev for studying OpenGL programming but when I type
from OpenGL.GL import *
from OpenGL.GLUT import *
IDE becomes extremely slow!
Ok. It isn't a smart idea import to much useless things but it's so useful for learning a new library!
Any help?
PS: I use Ubuntu with Eclipse Galileo.
hello
is there any way to get the selected item in a qmenu ?
i want to bind all items in that list to one function and get the item once user click it .
i've been looking for a way to get the item's label or index for 3 days , but couldn't find it .
any ideas ?
thanks in advance
i have a function which is a class method, and i want to test a attribute of the class which may or may not be None, but will exist always.
class classA():
def __init__(self, var1, var2 = None):
self.attribute1 = var1
self.attribute2 = var2
@classmethod
def func(self,x):
if self.attribute2 is None:
do something
i get the error
AttributeError: class classA has no attribute 'attributeB'
when i access the attribute like i showed but if on command line i can see it works,
x = classA()
x.attributeB is None
True
so the test works.
if i remove the @classmethod decorator from func, the problem disapears.
if i leave the @classmethod decorator, it only seems to affect variables which are supplied default values in the super-class's constructor.
whats going on in the above code?
info = {'phone_number': '123456', 'personal_detail': {'foo':foo, 'bar':bar}, 'is_active': 1, 'document_detail': {'baz':baz, 'saz':saz}, 'is_admin': 1, 'email': '[email protected]'}
return HttpResponse(simplejson.dumps({'success':'True', 'result':info}), mimetype='application/javascript')
if(data["success"] === "True") {
alert(data[**here I want to display personal_detail and document_details**]);
}
How can I do this?
Ptterb can you post your full code please?
I copied your code.
Added fvidscale_cap to pipeline, with:
self.player.add(self.source, self.scaler, self.fvidscale_cap, self.sink)
gst.element_link_many(self.source,self.scaler, self.fvidscale_cap, self.sink)
From the main program I create a new QWidget, and pass its winId() to Vid constructor.
The widget start loading, but crashes.
The output says:
should be playing
Segmentation fault
I want to make a function that can determine the source code of how it was called. I'm aware of how to do this generally with the inspect module. For example, this question, works well and provides my desired output in the lines variable as shown below:
def hello(x):
frame,filename,line_number,function_name,lines,index=\
inspect.getouterframes(inspect.currentframe())[1]
print(frame,filename,line_number,function_name,lines,index)
The problem is that this solution doesn't work in an interactive command line session. For example, from a command line, the result looks like:
>>> y = hello(7)
(<frame object at 0x01ECA9E8>, '<stdin>', 1, '<module>', None, None)
The problem is that the source file is '<stdin>', so the lines variable is None. How can I access the calling line to find the result containing the string y = hello(7) during an interactive session?
Hello,
I have the following table in the model with a recursive structure (a page can have children pages)
class DynamicPage(models.Model):
name = models.CharField("Titre",max_length=200)
parent = models.ForeignKey('self',null=True,blank=True)
I want to create another table with manytomany relation with this one:
class UserMessage(models.Model):
name = models.CharField("Nom", max_length=100)
page = models.ManyToManyField(DynamicPage)
The generated SQL creates the following constraint:
ALTER TABLE `website_dynamicpage` ADD CONSTRAINT `parent_id_refs_id_29c58e1b` FOREIGN KEY (`parent_id`) REFERENCES `website_dynamicpage` (`id`);
I would like to have the ManyToMany with the page itself (the id) and not with the parent field.
How to modify the model to make the constraint using the id and not the parent?
Thanks in advance
I'm writing to many files in a threaded app and I'm creating one handler per file. I have HandlerFactory class that manages the distribution of these handlers. What I'd like to do is that
thread A requests and gets foo.txt's file handle from the HandlerFactory class
thread B requests foo.txt's file handler
handler class recognizes that this file handle has been checked out
handler class puts thread A to sleep
thread B closes file handle using a wrapper method from HandlerFactory
HandlerFactory notifies sleeping threads
thread B wakes and successfully gets foo.txt's file handle
This is what I have so far,
def get_handler(self, file_path, type):
self.lock.acquire()
if file_path not in self.handlers:
self.handlers[file_path] = open(file_path, type)
elif not self.handlers[file_path].closed:
time.sleep(1)
self.lock.release()
return self.handlers[file_path][type]
I believe this covers the sleeping and handler retrieval successfully, but I am unsure how to wake up all threads, or even better wake up a specific thread.