I'm trying to create a custom tag. Inside this custom tag, I want to be able to have some logic that checks if the user is logged in, and then have the tag rendered accordingly. This is what I have:
class UserActionNode(template.Node):
def __init__(self):
pass
def render(self, context):
if context.user.is_authenticated():
return render_to_string('layout_elements/sign_in_register.html');
else:
return render_to_string('layout_elements/logout_settings.html');
def user_actions(parser, test):
return UserActionNode()
register.tag('user_actions', user_actions)
When I run this, I get this error:
Caught AttributeError while rendering: 'Context' object has no attribute 'user'
The view that renders this looks like this:
return render_to_response('start/home.html', {}, context_instance=RequestContext(request))
Why doesn't the tag get a RequestContext object instead of the Context object? How can I get the tag to receive the RequestContext instead of the Context?
EDIT:
Whether or not it's possible to get a RequestContext inside a custom tag, I'd still be interested to know the "correct" or best way to determine a user's authentication state from within the custom tag. If that's not possible, then perhaps that kind of logic belongs elsewhere? Where?
Hi,
Is there a better way to write the following:
row_counter = 0
for item in iterable_sequence:
# do stuff with the item
counter += 1
if not row_counter:
# handle the empty-sequence-case
Please keep in mind that I can't use len(iterable_sequence) because 1) not all sequences have known lengths; 2) in some cases calling len() may trigger loading of the sequence's items into memory (as the case would be with sql query results).
The reason I ask is that I'm simply curious if there is a way to make above more concise and idiomatic. What I'm looking for is along the lines of:
for item in sequence:
#process item
*else*:
#handle the empty sequence case
(assuming "else" here worked only on empty sequences, which I know it doesn't)
I have a very simple application running on appengine that requests a web page every five minutes and parses for a specific piece of data.
Everything works fine except that the response I get back from the external request (using urllib2) doesn't reflect the latest changes to the page. Sometimes it takes a few minutes to get the latest, sometimes over an hour.
Is there a transparent layer of caching that appengine puts in place? Or is there something else I am missing here? I've looked at the caching headers of the requested page and there is no Expires or LastModified's sent.
Update:
Sometimes, it will get the new version of the page for a number of requests and then randomly later get an old out of date version.
I am using matplotlib to subplot in a loop. For instance, i would like to subplot 49 data sets, and from the doc, i implemented it this way;
import numpy as np
import matplotlib.pyplot as plt
X1=list(range(0,10000,1))
X1 = [ x/float(10) for x in X1 ]
nb_mix = 2
parameters = []
for i in range(49):
param = []
Y = [0] * len(X1)
for j in range(nb_mix):
mean = 5* (1 + (np.random.rand() * 2 - 1 ) * 0.5 )
var = 10* (1 + np.random.rand() * 2 - 1 )
scale = 5* ( 1 + (np.random.rand() * 2 - 1) * 0.5 )
Y = [ Y[k] + scale * np.exp(-((X1[k] - mean)/float(var))**2) for k in range(len(X1)) ]
param = param + [[mean, var, scale]]
ax = plt.subplot(7, 7, i + 1)
ax.plot(X1, Y)
parameters = parameters + [param]
ax.show()
However, i have an index out of range error from i=0 onwards.
Where can i do better to have it works ?
Thanks
I want to display a gtk.Image with a high level of zoom, but scale the image to a new pixbuf with the pixfuf methods waste a lot of memory and processor.
Are there some simply way to display a zoomed image?
if i have an nested list such as:
m=[[34,345,232],[23,343,342]]
if i write m.remove(345) it gives an error message saying element not in the list.
i want to know how to remove an element from the nested list,easily??
My friend said, "Pylons is so much better for web services."
My other friend said, "You can modify Django in a way to do exactly whatever you like."
In Django, what is necessary to be modified (urls.py? models classes? settings?) in order to do "web services" with APIs and REST and versioning, etc etc.?
i want to upload zip folder from file input in form the i want to extract the contents of this uploaded zip folder,and store the contents (files)of this zip in the blobstore in order to download them after putting these files in one folder,but the problem is that i can't deal with the zip folder directly(to read it), i tried as this:
form = cgi.FieldStorage()
file_upload = form['file']
zip1=file_upload.filename
zipstream=StringIO.StringIO(zip1.read())
But the problem still that i can't read the zip as previous,also i tried to read zip folder directly like this:
z1=zipfile.ZipFile(zip1,"r")
But there was an error in this way.Please can any one help me.Thanks in advance.
I think small exercises would be the baest way for me to learn programming. I am the begginer and I am willing to give plenty of time to this.
To explain, to my opinion exercises should be something to write not long programs (10-30lines), to say what the program will print or that is the mistake.
Who can help me and say where to maybe a website with such stuff?
Thanks
I have an array like:
a = array([[1,2,3],[3,4,5],[4,5,6]])
what's the most efficient way to slice out a 1x2 array out of this that has only the first two columns of "a"?
I.e.,
array([[2,3],[4,5],[5,6]]) in this case.
thanks.
I need to highlight an email addresses in text but not highlight them if contained in HTML tags, content, or attributes.
For example, the string [email protected] must be converted to <a href="mailto:[email protected]">[email protected]</a>
But email addresses in the string <a href="mailto:[email protected]">[email protected]</a> must not be processed.
I've tried something like this regexp:
(?<![":])[a-zA-Z0-9._%-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}(?!")
but it doesn't work properly.
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.
I have two tables on different servers, and I'd like some help finding an efficient way to combine and match the datasets. Here's an example:
From server 1, which holds our stories, I perform a query like:
query = """SELECT author_id, title, text
FROM stories
ORDER BY timestamp_created DESC
LIMIT 10
"""
results = DB.getAll(query)
for i in range(len(results)):
#Build a string of author_ids, e.g. '1314,4134,2624,2342'
But, I'd like to fetch some info about each author_id from server 2:
query = """SELECT id, avatar_url
FROM members
WHERE id IN (%s)
"""
values = (uid_list)
results = DB.getAll(query, values)
Now I need some way to combine these two queries so I have a dict that has the story as well as avatar_url and member_id.
If this data were on one server, it would be a simple join that would look like:
SELECT *
FROM members, stories
WHERE members.id = stories.author_id
But since we store the data on multiple servers, this is not possible.
What is the most efficient way to do this?
Thanks.
Can someone suggest some basic advice on dealing with web applications that interact with configuration files like httpd.conf, bind zone files, etc.
I understand that it's bad practice, in fact very dangerous to allow arbitrary execution of code without fully validating it and so on. But say you are tasked to write a small app that allows one to add vhosts to an apache configuration.
Do you have your code execute with full privileges, do you write future variables into a database and have a cron job (with full privileges) execute a script that pulls the vars from the database and throws them into a template config file, etc.
Some thoughts & contributions on this issue would be appreciated.
tl;dr - how can you securely write a web app to update/create entries in a config file like apache's httpd.conf, etc.
I'm a computer science teacher trying to create a little gradebook for myself using NumPy. But I think it would make my code easier to write if I could create an ndarray that uses field names for both the rows and columns. Here's what I've got so far:
import numpy as np
num_stud = 23
num_assign = 2
grades = np.zeros(num_stud, dtype=[('assign 1','i2'), ('assign 2','i2')]) #etc
gv = grades.view(dtype='i2').reshape(num_stud,num_assign)
So, if my first student gets a 97 on 'assign 1', I can write either of:
grades[0]['assign 1'] = 97
gv[0][0] = 97
Also, I can do the following:
np.mean( grades['assign 1'] ) # class average for assignment 1
np.sum( gv[0] ) # total points for student 1
This all works. But what I can't figure out how to do is use a student id number to refer to a particular student (assume that two of my students have student ids as shown):
grades['123456']['assign 2'] = 95
grades['314159']['assign 2'] = 83
...or maybe create a second view with the different field names?
np.sum( gview2['314159'] ) # total points for the student with the given id
I know that I could create a dict mapping student ids to indices, but that seems fragile and crufty, and I'm hoping there's a better way than:
id2i = { '123456': 0, '314159': 1 }
np.sum( gv[ id2i['314159'] ] )
I'm also willing to re-architect things if there's a cleaner design. I'm new to NumPy, and I haven't written much code yet, so starting over isn't out of the question if I'm Doing It Wrong.
I am going to be needing to sum all the assignment points for over a hundred students once a day, as well as run standard deviations and other stats. Plus, I'll be waiting on the results, so I'd like it to run in only a couple of seconds.
Thanks in advance for any suggestions.
So, it seems one cannot do the following (it raises an error, since axes does not have a set_linewidth method):
axes_style = {'linewidth':5}
axes_rect = [0.1, 0.1, 0.9, 0.9]
axes(axes_rect, **axes_style)
and has to use the following old trick instead:
rcParams['axes.linewidth'] = 5 # set the value globally
... # some code
rcdefaults() # restore [global] defaults
Is there an easy / clean way (may be one can set x- and y- axes parameters individually, etc)?
P.S. If no, why?
This is the code I have so far
d = {}
counter = 0
for lines in words:
counter += 1
for word in text1:
if word not in words:
d[word] = [counter]
else:
d[word].append(counter)
print(word, d[counter])
words = my text file
text1 is my misspelled words
But this gives me an error. What I want to do is print the word and the line number e.g.
togeher 5 7
cache.set(key, Biglist, 3600)
print cache.get(key)
When my "Biglist" is a huge list of lots of content, it doesn't seem to store.
But when I change it to small text like "abc", it stores.
What do I have to configure so that I can set my memcache to accept unlimited size of key/value?
If I should be approaching this problem through a different method, please suggest so. I am creating an item based collaborative filter. I populate the db with the LinkRating2 class and for each link there are more than a 1000 users that I need to call and collect their ratings to perform calculations which I then use to create another table. So I need to call more than 1000 entities for a given link.
For instance lets say there are over a 1000 users rated 'link1' there will be over a 1000 instances of this class for the given link property that I need to call.
How would I complete this example?
class LinkRating2(db.Model):
user = db.StringProperty()
link = db.StringProperty()
rating2 = db.FloatProperty()
query =LinkRating2.all()
link1 = 'link string name'
a = query.filter('link = ', link1)
aa = a.fetch(1000)##how would i get more than 1000 for a given link1 as shown?
##keybased over 1000 in other post example i need method for a subset though not key
class MyModel(db.Expando):
@classmethod
def count_all(cls):
"""
Count *all* of the rows (without maxing out at 1000)
"""
count = 0
query = cls.all().order('__key__')
while count % 1000 == 0:
current_count = query.count()
if current_count == 0:
break
count += current_count
if current_count == 1000:
last_key = query.fetch(1, 999)[0].key()
query = query.filter('__key__ > ', last_key)
return count
I have a Django form that is working fine. I'd like to save the data it submits to a CSV file. Is there a "best practice" way to do this?
I need to include blank fields in the CSV file where the user has not filled in a "required=False" field
The problem is how to invert alternate bits of a number, starting from the LSB. Currently what I am doing is first doing a
count = -1
while n:
n >>= 1
count += 1
to first find the position of the leftmost set bit, then running a loop to invert every alternate bit:
i = 0
while i <= count:
num ^= 1<<i
i += 2
Is there a quick hack solution instead of this rather boring loop solution? Of course, the solution can't make any asumption about the size of the integer.
I was thinking I'd try to make my sqlite db connection a function instead of copy/pasting the ~6 lines needed to connect and execute a query all over the place.
I'd like to make it versatile so I can use the same function for create/select/insert/etc...
Below is what I have tried. The 'INSERT' and 'CREATE TABLE' queries are working, but if I do a 'SELECT' query, how can I work with the values it fetches outside of the function?
Usually I'd like to print the values it fetches and also do other things with them.
When I do it like below I get an error
Traceback (most recent call last):
File "C:\Users\steini\Desktop\py\database\test3.py", line 15, in <module>
for row in connection('testdb45.db', "select * from users"):
ProgrammingError: Cannot operate on a closed database.
So I guess the connection needs to be open so I can get the values from the cursor, but I need to close it so the file isn't always locked.
Here's my testing code:
import sqlite3
def connection (db, arg):
conn = sqlite3.connect(db)
conn.execute('pragma foreign_keys = on')
cur = conn.cursor()
cur.execute(arg)
conn.commit()
conn.close()
return cur
connection('testdb.db', "create table users ('user', 'email')")
connection('testdb.db', "insert into users ('user', 'email') values ('joey', 'foo@bar')")
for row in connection('testdb45.db', "select * from users"):
print row
How can I make this work?