Hi folks,
I'm serving Django with mod_wsgi and Apache... unfortunately requests are returning 502 Bad Gateway error messages...
Received a invalid response
HttpResponse('OK') is affected by this
render_to_response('...') is not!
any ideas?!?
I'm dealing with django-paypal and want to change the button src images. So I went the the conf.py file in the source and edited the src destination. However, I really want to leave the source alone, and I noticed that the
class PayPalPaymentsForm(forms.Form):
has
def get_image(self):
return {
(True, self.SUBSCRIBE): SUBSCRIPTION_SANDBOX_IMAGE,
(True, self.BUY): SANDBOX_IMAGE,
(True, self.DONATE): DONATION_SANDBOX_IMAGE,
(False, self.SUBSCRIBE): SUBSCRIPTION_IMAGE,
(False, self.BUY): IMAGE,
(False, self.DONATE): DONATION_IMAGE,
}[TEST, self.button_type]
which handles all the image src destinations. Since changing this def in the source is worse than changing conf, I was wondering if there was a way to pass in customized defs you make like passing in initial arguments in forms? This way no source code is changed, and I can customize the get_image def as much as I need.
passing in def something like this?
def get_image(self):
....
....
paypal = {
'amount': 10,
'item_name': 'test1',
'item_number': 'test1_slug',
# PayPal wants a unique invoice ID
'invoice': str(uuid.uuid4()),
}
form = PayPalPaymentsForm(initial=paypal, get_image)
Thanks!
I know that HttpResponseRedirect only takes one parameter, a URL. But there are cases when I want to redirect with an error message to display.
I was reading this post: How to pass information using an http redirect (in Django) and there were a lot of good suggestions. I don't really want to use a library that I don't know how works. I don't want to rely on messages which, according to the Django docs, is going to be removed. I thought about using sessions. I also like the idea of passing it in a URL, something like:
return HttpResponseRedirect('/someurl/?error=1')
and then having some map from error code to message. Is it good practice to have a global map-like structure which hard codes in these error messages or is there a better way?
Or should I just use a session
EDIT: I got it working using a session. Is that a good practice to put things like this in the session?
What is the best way to create a custom document editor in GAE? I'm making a website meant for a School Robotics Club (With support for any other organization - DRY).
We currently use Google services for online collaboration, I'm wondering if there is a way to tap into Google Docs and allow users to edit a Google Document without using Google Accounts or the Google Doc interface.
If that is not possible (I've researched and I don't think it is), what is the best way to make a document editor? I want it completely on the website I'm creating, so I'm assuming just some javascript editor like TinyMCE + Ajax + Datastore. Is their anything that replicates Google Doc's/Microsoft Offices's/OpenOffice.org's feature set as far as fonts, spacing, alignment, justification, etc.?
Hey,
Imagine you have this model:
class Category(models.Model):
node_id = models.IntegerField(primary_key = True)
type_id = models.IntegerField(max_length = 20)
parent_id = models.IntegerField(max_length = 20)
sort_order = models.IntegerField(max_length = 20)
name = models.CharField(max_length = 45)
lft = models.IntegerField(max_length = 20)
rgt = models.IntegerField(max_length = 20)
depth = models.IntegerField(max_length = 20)
added_on = models.DateTimeField(auto_now = True)
updated_on = models.DateTimeField(auto_now = True)
status = models.IntegerField(max_length = 20)
node = models.ForeignKey(Category_info, verbose_name = 'Category_info', to_field = 'node_id'
The important part is the foreignkey.
When I try:
Category.objects.filter(type_id = type_g.type_id, parent_id = offset, status = 1)
I get an error that get returned more than category, which is fine, because it is supposed to return more than one. But I want to filter the results trough another field, which would be type id (from the second Model)
Here it is:
class Category_info(models.Model):
objtree_label_id = models.AutoField(primary_key = True)
node_id = models.IntegerField(unique = True)
language_id = models.IntegerField()
label = models.CharField(max_length = 255)
type_id = models.IntegerField()
The type_id can be any number from 1 - 5. I am desparately trying to get only one result where the type_id would be number 1.
Here is what I want in sql:
SELECT n.*, l.*
FROM objtree_nodes n
JOIN objtree_labels l ON (n.node_id = l.node_id)
WHERE n.type_id = 15 AND n.parent_id = 50 AND l.type_id = 1
Any help is GREATLY appreciated.
Regards
I have this, and it works:
# E. Given two lists sorted in increasing order, create and return a merged
# list of all the elements in sorted order. You may modify the passed in lists.
# Ideally, the solution should work in "linear" time, making a single
# pass of both lists.
def linear_merge(list1, list2):
finalList = []
for item in list1:
finalList.append(item)
for item in list2:
finalList.append(item)
finalList.sort()
return finalList
# +++your code here+++
return
But, I'd really like to learn this stuff well. :) What does 'linear' time mean?
I've used virtualenvwrapper, but I'm having problems running it on a new computer. My .bashrc file is updated per the instructions:
export WORKON_HOME=$DEV_HOME/projects
source /usr/local/bin/virtualenvwrapper.sh
But when source is run, I get the following:
bash: /25009.hook: Permission denied
bash: /25009.hook: No such file or directory
This previous post leads me to believe the filename is being recycled and locked because virtualenvwrapper.sh uses $$. Is there any way to fix this?
Hey guys,
let's say I have a sorted list of Floats. Now I'd like to get the index of the next lower item of a given value. The usual for-loop aprroach has a complexity of O(n). Since the list is sorted there must be a way to get the index with O(log n).
My O(n) approach:
index=0
for i,value in enumerate(mylist):
if value>compareValue:
index=i-1
Is there a datatype for solving that problem in O(log n)?
best regards
Sebastian
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()
I need inspiration and motivation so I'm trying to find examples of different programs that have interesting and attractive UI's created free using wxPython.
My searches have been slow to find results. I'm hoping you guys know of some of the best ones out there.
btw, I've seen these:
http://www.wxpython.org/screenshots.php
and the list under "Applications Developed with wxPython" on the wxPython Wikipedia page.
Update: only need Windows examples
I'm trying to bind a float to a postgresql double precision using psycopg2.
ele = 1.0/3.0
dic = {'name': 'test', 'ele': ele}
sql = '''insert into waypoints (name, elevation) values (%(name)s, %(ele)s)'''
cur = db.cursor()
cur.execute(sql, dic)
db.commit()
sql = """select elevation from waypoints where name = 'test'"""
cur.execute(sql_out)
ele_out = cur.fetchone()[0]
ele_out
0.33333333333300003
ele
0.33333333333333331
Obviously I don't need the precision, but I would like to be able to simply compare the values. I could use the struct module and save it as a string, but thought there should be a better way. Thanks
I have a list of artists, albums and tracks that I want to sort using the first letter of their respective name. The issue arrives when I want to ignore "The ", "A ", "An " and other various non-alphanumeric characters (Talking to you "Weird Al" Yankovic and [dialog]). Django has a nice start '^(An?|The) +' but I want to ignore those and a few others of my choice.
I am doing this in Django, using a MySQL db with utf8_bin collation.
EDIT
Well my fault for not mentioning this but the database I am accessing is pretty much ready only. It's created and maintained by Amarok and I can't alter it without a whole mess of issues. That being said the artist table has The Chemical Brothers listed as The Chemical Brothers so I think I am stuck here. It probably will be slow but that's not so much of a concern for me as it's a personal project.
the mothed is :
def printa(x):
return x
the reponse is :
self.response.out.write(template.render(path, {'printa':printa}))
the html is :
{{ printa 'sss'}}
i want to show 'sss' in my page ,
so how to do this ,
thanks
When declaring a class that inherits from a specific class:
class C(dict):
added_attribute = 0
the documentation for C lists all the methods of dict (either through help(C) or pydoc).
Is there a way to hide the inherited methods from the automatically generated documentation (the documentation string can refer to the base class, for non-overwritten methods)?
This would be useful: pydoc lists the functions defined in a module after its classes. Thus, when the classes have a very long documentation, a lot of less than useful information is printed before the new functions provided by the module are presented, which makes the documentation harder to exploit (you have to skip all the documentation for the inherited methods until you reach something specific to the module being documented).
I'm having a difficult time figuring out why a simple SELECT query is taking such a long time with sqlalchemy using raw SQL (I'm getting 14600 rows/sec, but when running the same query through psycopg2 without sqlalchemy, I'm getting 38421 rows/sec).
After some poking around, I realized that toggling sqlalchemy's use_native_unicode parameter in the create_engine call actually makes a huge difference.
This query takes 0.5secs to retrieve 7300 rows:
from sqlalchemy import create_engine
engine = create_engine("postgresql+psycopg2://localhost...",
use_native_unicode=True)
r = engine.execute("SELECT * FROM logtable")
fetched_results = r.fetchall()
This query takes 0.19secs to retrieve the same 7300 rows:
engine = create_engine("postgresql+psycopg2://localhost...",
use_native_unicode=False)
r = engine.execute("SELECT * FROM logtable")
fetched_results = r.fetchall()
The only difference between the 2 queries is use_native_unicode. But sqlalchemy's own docs state that it is better to keep use_native_unicode=True (http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html).
Does anyone know why use_native_unicode is making such a big performance difference? And what are the ramifications of turning off use_native_unicode?
I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi)
The script works fine, that is until you try and use it on files that have Unicode show-names (something I never really thought about, since all the files I have are English, so mostly pretty-much all fall within [a-zA-Z0-9'\-])
How can I allow the regular expressions to match accented characters and the likes? Currently the regex's config section looks like..
config['valid_filename_chars'] = """0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@£$%^&*()_+=-[]{}"'.,<>`~? """
config['valid_filename_chars_regex'] = re.escape(config['valid_filename_chars'])
config['name_parse'] = [
# foo_[s01]_[e01]
re.compile('''^([%s]+?)[ \._\-]\[[Ss]([0-9]+?)\]_\[[Ee]([0-9]+?)\]?[^\\/]*$'''% (config['valid_filename_chars_regex'])),
# foo.1x09*
re.compile('''^([%s]+?)[ \._\-]\[?([0-9]+)x([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.s01.e01, foo.s01_e01
re.compile('''^([%s]+?)[ \._\-][Ss]([0-9]+)[\.\- ]?[Ee]([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.103*
re.compile('''^([%s]+)[ \._\-]([0-9]{1})([0-9]{2})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.0103*
re.compile('''^([%s]+)[ \._\-]([0-9]{2})([0-9]{2,3})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])),
]
I've been looking for an implementation (I'm using networkx library.) that will find all the minimum spanning trees (MST) of an undirected weighted graph.
I can only find implementations for Kruskal's Algorithm and Prim's Algorithm both of which will only return a single MST.
I've seen papers that address this problem (such as http://fano.ics.uci.edu/cites/Publication/Epp-TR-95-50.html) but my head tends to explode someway through trying to think how to translate it to code.
In fact i've not been able to find an implementation in any language!
I am attempting to add functionality to my Django app: when a new post is approved, I want to update the corresponding Facebook Page's status with a message and a link to the post automatically. Basic status update.
I have downloaded and installed pyfacebook - and I have read through the tutorial from Facebook. I have also seen this suggestion here on SO:
import facebook
fb = facebook.Facebook('YOUR_API_KEY', 'YOUR_SECRET_KEY')
fb.auth.createToken()
fb.login() # THIS IS AS FAR AS I CAN GET
fb.auth.getSession()
fb.set_status('Checking out StackOverFlow.com')
When I get to the login() call, however, pyfacebook tries to open lynx so I can login to Facebook 'via the web' -- this is, obviously, not going to work for me because the system is supposed to be automated ...
I've been looking, but can't find out how I can keep this all working with the script and not having to login via a web browser.
Any ideas?
I have a list of Persons each which have multiple fields that I usually filter what's upon, using the object_list generic view. Each person can have multiple Comments attached to them, each with a datetime and a text string. What I ultimately want to do is have the option to filter comments based on dates.
class Person(models.Model):
name = models.CharField("Name", max_length=30)
## has ~30 other fields, usually filtered on as well
class Comment(models.Model):
date = models.DateTimeField()
person = models.ForeignKey(Person)
comment = models.TextField("Comment Text", max_length=1023)
What I want to do is get a queryset like
Person.objects.filter(comment__date__gt=date(2011,1,1)).order_by('comment__date')
send that queryset to object_list and be able to only see the comments ordered by date with only so many objects on a page.
E.g., if "Person A" has comments 12/3/11, 1/2/11, 1/5/11, "Person B" has no comments, and person C has a comment on 1/3, I would see:
"Person A", 1/2 - comment
"Person C", 1/3 - comment
"Person A", 1/5 - comment
I would strongly prefer not to have to switch to filtering based on Comments.objects.filter(), as that would make me have to largely repeat large sections of code in the both the view and template.
Right now if I tried executing the following command, I will get a queryset returning (PersonA, PersonC, PersonA), but if I try rendering that in a template each persons comment_set will contain all their comments even if they aren't in the date range.
Ideally they're would be some sort of functionality where I could expand out a Person queryset's comment_set into a larger queryset that can be sorted and ordered based on the comment and put into a object_list generic view. This normally is fairly simple to do in SQL with a JOIN, but I don't want to abandon the ORM, which I use everywhere else.
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!
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?