content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Showing "Please choose:" in a Django's `Select` widget
I'm making a Django form and using ChoiceField which generates a <select> box with the different options. I would like that <select> box's first option to be "Please choose:", and that if the user submits the form without choosing, he'll get an error.
What wou... | Showing "Please choose:" in a Django's `Select` widget | I'm making a Django form and using ChoiceField which generates a <select> box with the different options. I would like that <select> box's first option to be "Please choose:", and that if the user submits the form without choosing, he'll get an error.
What would be a good way to do this?
| [
"Seems like Django doesn't have built-in support for such a request. You can achieve it by subclassing ChoiceField and making it accept a blank_choice argument. e.g.\nfrom django import forms\n\n\nclass ChoiceField(forms.ChoiceField):\n def __init__(self, *args, **kwargs):\n self.blank_choice = kwargs.pop... | [
4
] | [] | [] | [
"django",
"forms",
"python",
"validation"
] | stackoverflow_0005522339_django_forms_python_validation.txt |
Q:
SQLalchemy error: ConcurrentModificationError
I keep having the following error when using SQLalchemy:
ConcurrentModificationError: Updated rowcount 0 does not match number of objects updated 1
What's the reason behind this error? I get this error while using the merge method in sessions objects with postgresql. ... | SQLalchemy error: ConcurrentModificationError | I keep having the following error when using SQLalchemy:
ConcurrentModificationError: Updated rowcount 0 does not match number of objects updated 1
What's the reason behind this error? I get this error while using the merge method in sessions objects with postgresql. No other threads are doing access to the db.
| [
"Posting the question exactly into Google gives you \n\"\"\"\nGuys,\nI am using SA with MySQL. I am trying to update a record by making\na call to session.update(obj). In response I am getting\n\"ConcurrentModificationError: Updated rowcount 0 does not match\nnumber of objects updated 1\"\nWhat are the possible rea... | [
0
] | [] | [] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0005522471_python_sql_sqlalchemy.txt |
Q:
'module' object is not callable - Bio.IUPAC
When I try,
from Bio.Alphabet import IUPAC
from Bio import Seq
my_prot = Seq("AGTACACTGGT", IUPAC.protein)
Why do I encounter the following error:
TypeError: 'module' object is not callable
PS: this is an Example from the BioPython's Cookbook
A:
In the BioPython sour... | 'module' object is not callable - Bio.IUPAC | When I try,
from Bio.Alphabet import IUPAC
from Bio import Seq
my_prot = Seq("AGTACACTGGT", IUPAC.protein)
Why do I encounter the following error:
TypeError: 'module' object is not callable
PS: this is an Example from the BioPython's Cookbook
| [
"In the BioPython source code the \"Seq\" class is located in the file \"Seq.py\" in the path \"/Seq/Seq.py\"\nMeaning... You need to import Seq (a file) which means its a \"Module\" and then call the class \"Seq\" within the 'Module' 'Seq'\nSo try this:\nfrom Bio.Alphabet import IUPAC\nfrom Bio import Seq\nmy_prot... | [
8,
1
] | [] | [] | [
"biopython",
"python"
] | stackoverflow_0005519081_biopython_python.txt |
Q:
How to make my code more simple using python
this is my code:
def set_floor_point(self,floor_point=None):
if self.data.get('stage'):
self.data['stage'] = {}
stage_number = self.get_stage_number()
floor_number = self.get_floor_number()
if self.data['stage'].get(stage_number):
self.... | How to make my code more simple using python | this is my code:
def set_floor_point(self,floor_point=None):
if self.data.get('stage'):
self.data['stage'] = {}
stage_number = self.get_stage_number()
floor_number = self.get_floor_number()
if self.data['stage'].get(stage_number):
self.data['stage'][stage_number] = {}
if self.data[... | [
"data = collections.defaultdict(lambda: collections.defaultdict(\n lambda: collections.defaultdict(dict)))\ndata['stage'][3]['floor_point'][2] = 5\nprint data\n\n",
"I'm not sure what you want to achieve. A recurring theme in your code is:\nif some_dict.get(key):\n some_dict[key] = {}\n\nThat means: if some_d... | [
2,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0005522629_dictionary_python.txt |
Q:
Scraping parameterized url with scrapy
I have a spider running using python scrapy, which is scraping all pages apart from pages with parameters(i.e. & symbols), such as, http://www.amazon.co.uk/gp/product/B003ZDXHSG/ref=s9_simh_gw_p23_d0_i3?pf_rd_m=A3P5ROKL5A1OLE&pf_rd_s=center-2&pf_rd_r=1NWN2VXCA63R7TDYC3KQ&pf_r... | Scraping parameterized url with scrapy | I have a spider running using python scrapy, which is scraping all pages apart from pages with parameters(i.e. & symbols), such as, http://www.amazon.co.uk/gp/product/B003ZDXHSG/ref=s9_simh_gw_p23_d0_i3?pf_rd_m=A3P5ROKL5A1OLE&pf_rd_s=center-2&pf_rd_r=1NWN2VXCA63R7TDYC3KQ&pf_rd_t=101&pf_rd_p=467128533&pf_rd_i=468294.
Th... | [
"To respond to my own answer, all my code were fine. The reason it was failing is the way I was calling the scrapy. It breaks in & as I was using single quote.\nUsing the double quote to call the spider is the solution.\n",
"Your expression matches the url as far as re.serach() is concerned. Have you tried using ... | [
1,
0
] | [] | [] | [
"python",
"scrapy"
] | stackoverflow_0005499143_python_scrapy.txt |
Q:
Python: Opening a unicode named xls file from the script
How do you open a unicode named file (with spaces) from within a Python script under Windows?
filename for example: Hello עולם.xls
For a non-unicode non-spaced xls file, os.system(filename) works well.
For a non-unicode spaced xls file, os.system('"'+fil... | Python: Opening a unicode named xls file from the script | How do you open a unicode named file (with spaces) from within a Python script under Windows?
filename for example: Hello עולם.xls
For a non-unicode non-spaced xls file, os.system(filename) works well.
For a non-unicode spaced xls file, os.system('"'+filename+'"') works well.
But for a unicode spaces xls file...
bo... | [
"os.startfile() as mentioned by Bradley (+1), but make sure to pass a Unicode string in, and not a byte string.\nWindows NT filenames are natively Unicode, and Python on Windows has (unlike most other scripting languages) specific support built in for passing Unicode-strings into APIs that expect filenames:\nos.sta... | [
6,
4
] | [] | [] | [
"os.system",
"python",
"subprocess",
"unicode",
"windows"
] | stackoverflow_0005522524_os.system_python_subprocess_unicode_windows.txt |
Q:
Altering which class is instantiated based off initialization parameters
What is the best way to vary what class is instantiated based off parameters to an initialization function in Python? For example, for a quadtree, if the number of elements is below a certain threshold, you want to return a leaf rather than a... | Altering which class is instantiated based off initialization parameters | What is the best way to vary what class is instantiated based off parameters to an initialization function in Python? For example, for a quadtree, if the number of elements is below a certain threshold, you want to return a leaf rather than a branch. Another example would be a graph which can either be backed by a adja... | [
"Have a look into __new__. Documentation\n",
"You can use __new__, but a factory function is the nice pythonic way to go.\n",
"In his Advanced C++ Programming Styles and Idioms book, James Coplien discusses how to simulate virtual constructors in C++ (pdf version). They have to be simulated because the language... | [
2,
2,
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0005521463_oop_python.txt |
Q:
Why do these two implementations produce different results?
I asked this question and got an excellent answer (thanks!). Part of the problem to be solved involved taking a word and de-interlacing it, so that you get two words, one containing the even-indexed characters of the original word, the other containing t... | Why do these two implementations produce different results? | I asked this question and got an excellent answer (thanks!). Part of the problem to be solved involved taking a word and de-interlacing it, so that you get two words, one containing the even-indexed characters of the original word, the other containing the odd-indexed characters.
The responder used the following code ... | [
"Because index(c) asks the index of the first occurrance of the letter in the word — so you are creating a single “bucket” for each letter. So if the first 'a' is odd, then all of the 'a' letters also get stuffed into the \"odd\" string. To fix this, you should just use enumerate() to count:\nfor i, c in enumerate(... | [
10
] | [] | [] | [
"python"
] | stackoverflow_0005523296_python.txt |
Q:
want to use distutils to install my python app with a "one-click" launcher file
I'm trying to figure out how to make my program installable via distutils. My end goal is to make a .deb installer for ubuntu users. The main issue is getting a "one-click" launcher file to work.
My program uses pygtk and sqlite3 for t... | want to use distutils to install my python app with a "one-click" launcher file | I'm trying to figure out how to make my program installable via distutils. My end goal is to make a .deb installer for ubuntu users. The main issue is getting a "one-click" launcher file to work.
My program uses pygtk and sqlite3 for the gui and database. I've used glade to help build my gui and so my program ties into... | [
"I've solved the main issue I had here. The over all problem was that my data files weren't being included. In the setup.py file I needed to have the following calls set like...\nsetup(\n packages = [\"RTcore\"], \n package_dir = {\"RTcore\": \"src/RTcore\"}, \n package_data = {\"RTcore\": [\"ui/*\"]}, \n data_... | [
0
] | [] | [] | [
"distutils",
"linux",
"python",
"setup.py"
] | stackoverflow_0005359581_distutils_linux_python_setup.py.txt |
Q:
How can I convert an RFC 822 timestamp into a human readable format in Python?
Does anyone know of a Python module that will convert an RFC 822 timestamp into a human readable format (like Twitter does) in Python?
I found parsedatetime, which seems to do the reverse.
A:
In python, you can use rfc822 module. This... | How can I convert an RFC 822 timestamp into a human readable format in Python? | Does anyone know of a Python module that will convert an RFC 822 timestamp into a human readable format (like Twitter does) in Python?
I found parsedatetime, which seems to do the reverse.
| [
"In python, you can use rfc822 module. This module provides the parsedate method.\n\nAttempts to parse a date according to the rules in RFC 2822.\n\nHowever, this module is deprecated.\n\nDeprecated since version 2.3: The email package should be used in preference to the rfc822 module. This module is present only t... | [
8,
2,
0
] | [] | [] | [
"python",
"rfc822"
] | stackoverflow_0005523751_python_rfc822.txt |
Q:
Python: Does 'unittest' have something that 'doctest' hasn't?
The question is quite clear, ... note however that I am NOT asking about a feature comparison (there are a lot of them already), nor am I asking about which one you prefer !
I have myself a clear preference for doctests, I use them for everything, even ... | Python: Does 'unittest' have something that 'doctest' hasn't? | The question is quite clear, ... note however that I am NOT asking about a feature comparison (there are a lot of them already), nor am I asking about which one you prefer !
I have myself a clear preference for doctests, I use them for everything, even if those are not to be used for documentation. But what I am wonder... | [
"There is a widespread misconception that doctest is for testing your code. doctest is intended for testing your documentation. doctest is intended to test that your documentation matches what the function/class/module is actually doing, and alerts you if sample code in your documentation becomes obsolete as the mo... | [
5,
3,
0,
0
] | [] | [] | [
"doctest",
"python",
"unit_testing"
] | stackoverflow_0005522334_doctest_python_unit_testing.txt |
Q:
Importing Sqlite data into Google App Engine
I have a relatively extensive sqlite database that I'd like to import into my Google App Engine python app.
I've created my models using the appengine API which are close, but not quite identical to the existing schema. I've written an import script to load the data fro... | Importing Sqlite data into Google App Engine | I have a relatively extensive sqlite database that I'd like to import into my Google App Engine python app.
I've created my models using the appengine API which are close, but not quite identical to the existing schema. I've written an import script to load the data from sqlite and create/save new appengine objects, bu... | [
"I would make suitable CSV files from the Sqlite data, in a separate script, then use bulk loading to push the data from the CSV files up to app engine.\n",
"If you need to access your datastore outside of the App Engine environment (like if you need to use libraries not present in App Engine or do other things A... | [
5,
1,
0,
0
] | [] | [] | [
"google_app_engine",
"python",
"sqlite"
] | stackoverflow_0002870379_google_app_engine_python_sqlite.txt |
Q:
How to optimize this Python code (from ThinkPython, Exercise 10.10)
I'm working through Allen Downey's How To Think Like A Computer Scientist, and I've written what I believe to be a functionally correct solution to Exercise 10.10. But it took just over 10 hours (!) to run, so I'm wondering if I'm missing some re... | How to optimize this Python code (from ThinkPython, Exercise 10.10) | I'm working through Allen Downey's How To Think Like A Computer Scientist, and I've written what I believe to be a functionally correct solution to Exercise 10.10. But it took just over 10 hours (!) to run, so I'm wondering if I'm missing some really obvious and helpful optimization.
Here's the Exercise:
"Two words 'i... | [
"Do it the other way around: Iterate through all words and split them into two words by taking the odd and even letters. Then look up those two words in the dictionary.\nAs a side node, the two words that interlock must not necessarily have the same length -- the lengths might also differ by 1.\nSome (untested) co... | [
15,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005523058_python.txt |
Q:
Running "IDLE3.2 -s" from the "Finder" in OS X 10.6
I want to run IDLE3.2 with the argument "-s" so it can read ".pythonstartup" and export relevant modules, change the working directory and etc. Here is what I have tried:
Created a shell script:
/usr/local/bin/idle3.2 -s
this works allright, however running the... | Running "IDLE3.2 -s" from the "Finder" in OS X 10.6 | I want to run IDLE3.2 with the argument "-s" so it can read ".pythonstartup" and export relevant modules, change the working directory and etc. Here is what I have tried:
Created a shell script:
/usr/local/bin/idle3.2 -s
this works allright, however running the script from the Finder opens up the Terminal, which is n... | [
"I think your do shell script \"/bin/bash; cd /usr/local/bin; ./idle3.2 -s\" is doing extra work, and can probably be done more simply. Try:\ndo shell script \"/usr/local/bin/idle3.2 -s\"\n\n",
"thanks to @lain the following applescript solves the problem:\ndo shell script \"source ~/.profile; idle3.2 -s\"\n\nwhe... | [
2,
2
] | [] | [] | [
"macos",
"python",
"shell"
] | stackoverflow_0005520658_macos_python_shell.txt |
Q:
Python: How to move a file with unicode filename to a unicode folder
I'm having hell with moving a unicode named file between unicode named folders in a Python script under Windows...
What syntax would you use to find all files of type *.ext in a folder and move them to a relative location?
Assume files and folder... | Python: How to move a file with unicode filename to a unicode folder | I'm having hell with moving a unicode named file between unicode named folders in a Python script under Windows...
What syntax would you use to find all files of type *.ext in a folder and move them to a relative location?
Assume files and folders are unicode.
| [
"The basic problem is the unconverted mix between Unicode and byte strings. The solutions can be converting to a single format or avoiding the problems using some trickery. All of my solutions include the glob and shutil standard library.\nFor the sake of example, I have some Unicode filenames ending with ods, and ... | [
15,
3
] | [] | [] | [
"file_manipulation",
"python",
"unicode"
] | stackoverflow_0005523373_file_manipulation_python_unicode.txt |
Q:
How to detect motion between two PIL images? (wxPython webcam integration example included)
Does anyone have any suggestions as to how I might do image comparison in python to detect changes within an image? I'm currently working on an app that will monitor my area with my webcam, I would like to figure out how to... | How to detect motion between two PIL images? (wxPython webcam integration example included) | Does anyone have any suggestions as to how I might do image comparison in python to detect changes within an image? I'm currently working on an app that will monitor my area with my webcam, I would like to figure out how to compare the images taken each frame to see if any motion has been detected. In the long run I wo... | [
"This might be a naive approach, but it's a simple place to begin. I'm sure you will be influenced by camera noise and you may want to distinguish changes in lighting from changes in image composition. But here's what came to my mind:\nYou can use PIL ImageChops to efficiently take a difference between images. T... | [
13
] | [] | [] | [
"python",
"python_imaging_library",
"video_capture",
"webcam",
"wxpython"
] | stackoverflow_0005524179_python_python_imaging_library_video_capture_webcam_wxpython.txt |
Q:
Avoiding redundant code in mobile/desktop with Django sites framework
According to the Django docs, the best practice for serving a mobile and desktop application would appear to be the following:
views.py
from django.contrib.sites.models import Site
def my_view(request):
current_site = Site.objects.get_curr... | Avoiding redundant code in mobile/desktop with Django sites framework | According to the Django docs, the best practice for serving a mobile and desktop application would appear to be the following:
views.py
from django.contrib.sites.models import Site
def my_view(request):
current_site = Site.objects.get_current()
if current_site.domain == 'foo.com':
# Render desktop hom... | [
"Have you looked at this app: http://pypi.python.org/pypi/django-mobility?\nUsing a middleware for detecting the device and decorators to switch templates depending on the incoming device are a good approach to avoid redundant if/else constructs.\nAnd if you look at the examples given for django-mobility they look ... | [
2,
1
] | [] | [] | [
"django",
"mobile",
"python"
] | stackoverflow_0005516051_django_mobile_python.txt |
Q:
How to know if javac compiled cleanly using system() in python
In python, how can I tell if a certain system() call is successful? In the program I am writing I need to know if a java program compiled correctly using javac, which is called using system() (in the python program). So I need to know if javac threw an... | How to know if javac compiled cleanly using system() in python | In python, how can I tell if a certain system() call is successful? In the program I am writing I need to know if a java program compiled correctly using javac, which is called using system() (in the python program). So I need to know if javac threw any exceptions, if there were any syntax problems with the java progra... | [
"You need to use subprocess module, os.system has been deprecated. \nAn exit code of 0 indicates successful termination, a non-zero exit code means an error occurred.\nThere are many convenience functions available, let's take an example of subprocess.call\n>>> subprocess.call(['ls', '-a'])\n0\n\nSuccessful, as ls ... | [
4,
0
] | [] | [] | [
"java",
"python"
] | stackoverflow_0005524863_java_python.txt |
Q:
Python - posting checkbox to web form
i use this code in python to post something to a form in a web page.
but i dont just want to send some text as an input textbox, i also want to decide if a checkbox in the form is checked or not.
what value do i have to give to the 'checkbox' parameter in the "web_form"?
web_f... | Python - posting checkbox to web form | i use this code in python to post something to a form in a web page.
but i dont just want to send some text as an input textbox, i also want to decide if a checkbox in the form is checked or not.
what value do i have to give to the 'checkbox' parameter in the "web_form"?
web_form = [('textbox', text),('checkbox', ?????... | [
"You question is pretty broad since you did not mention with web framework you are using.\nApplication code could check either for the existence of the checkbox key in the request or check for a particular value...unless you provide further informations: try setting it to something like '1' and see what's happening... | [
0
] | [] | [] | [
"checkbox",
"python",
"urllib2",
"webforms"
] | stackoverflow_0005524845_checkbox_python_urllib2_webforms.txt |
Q:
file I/O with google app engine
I want to provide a field in my html file so that people can upload their XML files to be imported to the datastore. How can I read and process this file inside the app engine once it is uploaded ? (I dont want to store the file with blobstore. Just want to read, process and throw i... | file I/O with google app engine | I want to provide a field in my html file so that people can upload their XML files to be imported to the datastore. How can I read and process this file inside the app engine once it is uploaded ? (I dont want to store the file with blobstore. Just want to read, process and throw it away) Thanks
| [
"Use a StringIO when you need a file-like object for use with libraries that act on files. (Although I believe most XML parsers will happily accept a string instead of requiring a file-like object.)\n"
] | [
1
] | [] | [] | [
"datastore",
"google_app_engine",
"html",
"python",
"xml"
] | stackoverflow_0005524991_datastore_google_app_engine_html_python_xml.txt |
Q:
Guessing a number, true or false? Python
I want to assign something a value and then try and get someone to guess that value. I have tried something along the lines of this but I can't seem to get it to work...:
foo = 1
guessfoo = input('Guess my number: ')
if foo == guessfoo:
print('Well done, You... | Guessing a number, true or false? Python | I want to assign something a value and then try and get someone to guess that value. I have tried something along the lines of this but I can't seem to get it to work...:
foo = 1
guessfoo = input('Guess my number: ')
if foo == guessfoo:
print('Well done, You guessed it!')
if foo != guessfoo:
p... | [
"With python version 3 :\ninput() returns a 'str' (string) object. A string compares to an integer returns False :\n1 == '1'\nFalse\n\nYou must cast your input like that :\nguessfoo = int(input('Guess my number: '))\n\nDon't forget to try...except if the result of the input cannot be casted into an int.\nFull examp... | [
4,
0,
0,
0,
0,
0
] | [] | [] | [
"boolean",
"numbers",
"python"
] | stackoverflow_0005524990_boolean_numbers_python.txt |
Q:
All in one Django/Python editor
I know this is probably a question that is asked a ton on here but I haven't been able to find exactly what I'm looking for. I'm a JAVA developer that is learning Python and Django and I'm looking for a good development environment. I would like to be able to edit python code, css... | All in one Django/Python editor | I know this is probably a question that is asked a ton on here but I haven't been able to find exactly what I'm looking for. I'm a JAVA developer that is learning Python and Django and I'm looking for a good development environment. I would like to be able to edit python code, css, html and javascript all in the same... | [
"If your familiar with eclipse, by all means try Pydev first. I was the opposite, I was/am a Python developer who switched to Java. There was no real difference between using Eclipse for Java and Eclipse for Python (Pydev), you still get inline docs, debugging, code completion, the whole bit. You also get a lot of ... | [
4,
2,
2,
1,
1
] | [] | [] | [
"django",
"ide",
"python"
] | stackoverflow_0003169879_django_ide_python.txt |
Q:
Efficient transfer protocol for mobile equipment
I am working on a platform having a GPRS data connection. What I have now is a custom protocol over TCP or UDP which I'm thinking to change. The device in the current state sends small chunks of data periodically (let's say 30seconds or 5 minutes - this can, and pro... | Efficient transfer protocol for mobile equipment | I am working on a platform having a GPRS data connection. What I have now is a custom protocol over TCP or UDP which I'm thinking to change. The device in the current state sends small chunks of data periodically (let's say 30seconds or 5 minutes - this can, and probably will, change). My concern is that the data being... | [
"Given your constraints, properly encoded JSON sounds reasonable.\n\nIt is fairly light-weight (size of data + quotes and {})\nIt is extensible. You don't need to decide on a fixed format up front. Adding keys is trivial for both the transmission and receiving.\nYou can use eval() to get a Python dictionary (since ... | [
2,
0
] | [] | [] | [
"mobile",
"network_protocols",
"optimization",
"python"
] | stackoverflow_0005523889_mobile_network_protocols_optimization_python.txt |
Q:
Put docstrings on special methods?
I'm trying to decide what information to put in the class docstring and what to put in the __init__ method docstring. Up until now I've been putting an overview of the class and how to work with it in the class docstring, while stuff directly related to initialization (argument d... | Put docstrings on special methods? | I'm trying to decide what information to put in the class docstring and what to put in the __init__ method docstring. Up until now I've been putting an overview of the class and how to work with it in the class docstring, while stuff directly related to initialization (argument details etc.) I put in the __init__ docst... | [
"Straight from PEP 257:\n\nPublic methods (including the __init__ constructor) should also have docstrings.\n\n[...]\n\nThe class constructor should be documented in the docstring for its __init__ method.\n\n"
] | [
9
] | [] | [] | [
"docstring",
"python"
] | stackoverflow_0005525501_docstring_python.txt |
Q:
Returning to menu after command? Python
I know all my questions are really easy but I'm a beginner so here it is...
I have been developing the guessing number thing after everyones help, but I want to then return to a menu which has just been left. Here's the code:
import time
import random
animalmenu()
def anima... | Returning to menu after command? Python | I know all my questions are really easy but I'm a beginner so here it is...
I have been developing the guessing number thing after everyones help, but I want to then return to a menu which has just been left. Here's the code:
import time
import random
animalmenu()
def animalmenu():
print()
print()
print()
... | [
"because the you convert your input into integer and store it into guessleg which means guessleg is also an integer. However, 'back' is a string. You can't compare the string with integer. the 3 == 'back'means nothing. \nand syntax error may because of your indent. \nUPDATE: \nif you want to return to the top men... | [
0,
0
] | [] | [] | [
"callback",
"loops",
"menu",
"python"
] | stackoverflow_0005525483_callback_loops_menu_python.txt |
Q:
Python script runs with double-click and IDLE but not windows CMD shell
I'm have a problem where if I double click my script (.py), or open it with IDLE, it will compile and run correct. However, if I try to run the script in my windows command line, using
C:\> "C:\Software_Dev\Python 2.7.1\python.exe" C:\path\to\... | Python script runs with double-click and IDLE but not windows CMD shell | I'm have a problem where if I double click my script (.py), or open it with IDLE, it will compile and run correct. However, if I try to run the script in my windows command line, using
C:\> "C:\Software_Dev\Python 2.7.1\python.exe" C:\path\to\script\script.py
I get...
Traceback (most recent call last):
File "C:\path... | [
"The script is trying to write into a file in the current directory. In the example above, you're starting it from C:\\ where you probably don't have write permissions.\ncd to a directory that you own, and you should be able to run that command just fine.\n",
"This is because when you double-click the file (or wh... | [
1,
0
] | [] | [] | [
"command_line",
"python",
"windows_7"
] | stackoverflow_0005525525_command_line_python_windows_7.txt |
Q:
How do you make it possible to make accounts? Python
I want to make a simple game on python, all text based. Sort of an interactive story with puzzles etc. but it is likely to be long. I want to be able to it possible for poeple to sort of, 'Save Progress'. Perhaps assign them selves a name etc? I am new to Python... | How do you make it possible to make accounts? Python | I want to make a simple game on python, all text based. Sort of an interactive story with puzzles etc. but it is likely to be long. I want to be able to it possible for poeple to sort of, 'Save Progress'. Perhaps assign them selves a name etc? I am new to Python and am wondering if it is possible to set up a bank conta... | [
"You should check out the pickle module. It allows you to store/retrieve any python object. One way to do this would be to have your game take place in a class, where all of the states/etc were members of that class (or derived classes). When they wanted to save you would just pickle your class!\nYou are pretty ... | [
2,
1,
0
] | [] | [] | [
"authentication",
"load",
"python"
] | stackoverflow_0005525630_authentication_load_python.txt |
Q:
is there ever a reason to use "is"?
Instead of "=="? I know what "is" is, it is comparing the identity of the variable. But when would you ever want to do that? All it has ever done for me is cause problems. After using it for a while (because I felt it made my code more readable), I am not declaring war on "i... | is there ever a reason to use "is"? | Instead of "=="? I know what "is" is, it is comparing the identity of the variable. But when would you ever want to do that? All it has ever done for me is cause problems. After using it for a while (because I felt it made my code more readable), I am not declaring war on "is".
Does anyone use it for something that... | [
"Yes, there is a reason.\nWhen you want to compare object-identity (\"same object\") and not object-equality (\"same value\"). In almost all cases == (object-equality) is the correct operator to use. (As pointed out in the comments, the trivial case I skipped entirely is the x is None idiom -- None is the sole inha... | [
7,
4
] | [] | [] | [
"comparison_operators",
"operators",
"python",
"syntax"
] | stackoverflow_0005525676_comparison_operators_operators_python_syntax.txt |
Q:
SQLAlchemy: Any way to convert MetaData to Table statements?
For various reasons, I'd like to write out my MetaData object as a python script containing SQLAlchemy Table declarations.
Stated a different way, given a well-designed, but completely unknown database, what's the best way to write an SQLAlchemy definiti... | SQLAlchemy: Any way to convert MetaData to Table statements? | For various reasons, I'd like to write out my MetaData object as a python script containing SQLAlchemy Table declarations.
Stated a different way, given a well-designed, but completely unknown database, what's the best way to write an SQLAlchemy definition of the database Table's in a fully automated way? It seems like... | [
"SQLAlchemy Migrate has the create_model command, see http://packages.python.org/sqlalchemy-migrate/versioning.html#experimental-commands . It has experimental status but I found it useful on several occasions.\n"
] | [
1
] | [] | [] | [
"database",
"ddl",
"python",
"sqlalchemy"
] | stackoverflow_0005525203_database_ddl_python_sqlalchemy.txt |
Q:
Reference list item as key in sorted for loop
Sorry for boring question but I can't figure this out:
for f in sorted(os.listdir('.')): print f
Output:
p1.html
p10.html
p11.html
p12.html
p13.html
p14.html
p15.html
p16.html
p17.html
p18.html
p19.html
p2.html
p20.html
p21.html
p22.html
p3.html
p4.html
...
Obviously... | Reference list item as key in sorted for loop | Sorry for boring question but I can't figure this out:
for f in sorted(os.listdir('.')): print f
Output:
p1.html
p10.html
p11.html
p12.html
p13.html
p14.html
p15.html
p16.html
p17.html
p18.html
p19.html
p2.html
p20.html
p21.html
p22.html
p3.html
p4.html
...
Obviously I want to sort by number and I can do it with this... | [
"You'd need a lambda expression:\nsorted(os.listdir('.'), key=lambda f: int(f.split('.')[0][1:]))\n\n"
] | [
1
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0005526073_list_python_sorting.txt |
Q:
Google appengine Send local gif as an email attachment
I'm trying to send a local gif as an email attachment on Google appengine. The email will send but without an attachment.
message = mail.EmailMessage(sender="My image <whomever@gmail.com>",
subject="image")
message.to = "Jim <whomever@gmail.com>"
message.bod... | Google appengine Send local gif as an email attachment | I'm trying to send a local gif as an email attachment on Google appengine. The email will send but without an attachment.
message = mail.EmailMessage(sender="My image <whomever@gmail.com>",
subject="image")
message.to = "Jim <whomever@gmail.com>"
message.body = my_body_text
message.html = my_body_html
image = open(... | [
"You forgot to set the attachments field on your message, and made a local variable you didn't use instead. Simply change\nattachments=[(image.name, image.read())]\n\nto\nmessage.attachments=[(image.name, image.read())]\n\n"
] | [
9
] | [] | [] | [
"email_attachments",
"gif",
"google_app_engine",
"image",
"python"
] | stackoverflow_0005526272_email_attachments_gif_google_app_engine_image_python.txt |
Q:
Is there a way to tell where your python file is?
(Python2.7-3.2 on WindowsXP)
I used to use sys.arg[0], but now I'm executing it from a batch script(for determining if the user has python)
Thanks ^^
~ps: Suggest if you know a better way to find out if the user has Python
A:
Maybe you are looking for
os.path.dir... | Is there a way to tell where your python file is? | (Python2.7-3.2 on WindowsXP)
I used to use sys.arg[0], but now I'm executing it from a batch script(for determining if the user has python)
Thanks ^^
~ps: Suggest if you know a better way to find out if the user has Python
| [
"Maybe you are looking for\nos.path.dirname(__file__)\n\n",
"You can read the variable __file__ to find out the path to the current Python file being interpreted.\n",
"os.path.normpath(os.path.abspath(os.path.dirname(__file__)))\n\n",
"you could take a look at this posting that checks the registry\nbatch file... | [
7,
1,
0,
0,
0
] | [] | [] | [
"python",
"python_2.7",
"python_3.x",
"windows"
] | stackoverflow_0005525544_python_python_2.7_python_3.x_windows.txt |
Q:
Separate objects and put them into pairs
So I have a variable a which contains:
WOOP:2,DERV:2,WHAT:2,MATE:1
And I would like to separate these so it would look like this:
[('WOOP',2),('DERV',2),('WHAT',2),('MATE',1)]
A:
this one-liner would do it
L = [(f1, int(f2)) for x in a.split(",") for f1, f2 in (x.split... | Separate objects and put them into pairs | So I have a variable a which contains:
WOOP:2,DERV:2,WHAT:2,MATE:1
And I would like to separate these so it would look like this:
[('WOOP',2),('DERV',2),('WHAT',2),('MATE',1)]
| [
"this one-liner would do it\nL = [(f1, int(f2)) for x in a.split(\",\") for f1, f2 in (x.split(\":\"),)]\n\nhowever I'd probably write instead\nL = []\nfor x in a.split(\",\"):\n f1, f2 = x.split(\":\")\n L.append((f1, int(f2)))\n\n",
"Try this:\nl = [ tuple(s.split(':')) for s in a.split(',') ]\nl = [ (t[0... | [
3,
2,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0005526040_python_string.txt |
Q:
Query progressbar in sqlite and python
I want to create a progressbar for queries, say i have a query that will take 40 seconds, i'd like to give some feedback to users on how long this will take and i found this code from oracle that is exactly matches what i want. Is there a same thing in sqlite?
from timemachin... | Query progressbar in sqlite and python | I want to create a progressbar for queries, say i have a query that will take 40 seconds, i'd like to give some feedback to users on how long this will take and i found this code from oracle that is exactly matches what i want. Is there a same thing in sqlite?
from timemachine import oracle
guesser=oracle(guess="SQL")... | [
"Perhaps the set_progress_handler() method of the sqlite3.Connection objects could be of use?\n"
] | [
0
] | [] | [] | [
"progress_bar",
"python",
"sqlite"
] | stackoverflow_0005526417_progress_bar_python_sqlite.txt |
Q:
Cluster Graph Visualization using python
I am assembling different visualization tools that are available in python language. I found the Treemap. (http://pypi.python.org/pypi/treemap/1.05)
Can you suggest some other tools that are available. I am exploring different ways of visualization of web data.
A:
The N... | Cluster Graph Visualization using python | I am assembling different visualization tools that are available in python language. I found the Treemap. (http://pypi.python.org/pypi/treemap/1.05)
Can you suggest some other tools that are available. I am exploring different ways of visualization of web data.
| [
"The Nodebox Graph library is specifically designed for graph visualization and analysis: well worth considering.\n",
"If you would be ok with using jython there are some good visualization libraries for java including:\n\nPrefuse\nPiccolo\n\nIf you are using Python on the server and want to use Javascript or Fla... | [
4,
4,
2,
0
] | [] | [] | [
"data_visualization",
"python",
"visualization"
] | stackoverflow_0002838707_data_visualization_python_visualization.txt |
Q:
Python version differences
I got a book for python 2.5 but up until now I've been using 2.7. Will there be any huge barriers to overcome?
A:
No, Python 2.7 is compatible with 2.5. There were a few features that were added, but everything you learned from 2.5 should work in 2.7.
Python 3, on the other hand, makes... | Python version differences | I got a book for python 2.5 but up until now I've been using 2.7. Will there be any huge barriers to overcome?
| [
"No, Python 2.7 is compatible with 2.5. There were a few features that were added, but everything you learned from 2.5 should work in 2.7.\nPython 3, on the other hand, makes some big changes that are not compatible with 2.5.\n",
"The 2.x versions are (generally - if 2.x had a bug somewhere and some fool writes c... | [
5,
4,
0
] | [] | [] | [
"python",
"version"
] | stackoverflow_0005526666_python_version.txt |
Q:
Need regex help: Match if certain string doesn't start with certain sub-patterns AND certain character should not be there
I need to come up with a regular expression for a mini-project.
The string should not start with:
"/wiki"
and it should also not have the following pattern
"/.*:.*" (basically pattern star... | Need regex help: Match if certain string doesn't start with certain sub-patterns AND certain character should not be there | I need to come up with a regular expression for a mini-project.
The string should not start with:
"/wiki"
and it should also not have the following pattern
"/.*:.*" (basically pattern starts with char '/' and there is any occurrence of ':' after that)
and it also cannot have a certain character '#'
So basically all... | [
"^(/(?!wiki)[^:#]*|[^#/][^#]*)$ should be ok, as tested here, of course I might be missing something, but this appears to follow your specification.\n",
"This tested script implements a commented regex which precisely matches your stated requirements:\nimport re\ndef check_str(subject):\n \"\"\"Retturn True if... | [
5,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005526616_python_regex.txt |
Q:
Python conversion from list to tuple
I have a variable x (list)that looks like ['JACKIE:34', 'MATT:444', 'CEN:12', 'PETE:12', 'RANDY:92', 'MITCH:2', 'JAN:2']
which then i would like to convert to tuple (in pairs)so it would look like
[('JACKIE',34), ('MATT',444), ('CEN',12), ('PETE',12), ('RANDY',92), ('MITCH',2),... | Python conversion from list to tuple | I have a variable x (list)that looks like ['JACKIE:34', 'MATT:444', 'CEN:12', 'PETE:12', 'RANDY:92', 'MITCH:2', 'JAN:2']
which then i would like to convert to tuple (in pairs)so it would look like
[('JACKIE',34), ('MATT',444), ('CEN',12), ('PETE',12), ('RANDY',92), ('MITCH',2), ('JAN',2)]Note that the number is an int.... | [
"Numbers as ints, as requested\nbefore = ['JACKIE:34', 'MATT:444', 'CEN:12', 'PETE:12', 'RANDY:92', 'MITCH:2', 'JAN:2']\nafter = [(name, int(value)) for name, value in (x.split(':') for x in before)]\nprint after\n\n",
"a = ['JACKIE:34', 'MATT:444', 'CEN:12', 'PETE:12', 'RANDY:92', 'MITCH:2', 'JAN:2']\nb = [x.spl... | [
7,
2
] | [] | [] | [
"list",
"python",
"tuples"
] | stackoverflow_0005526754_list_python_tuples.txt |
Q:
Celery, Django.. making a Task / thread launch sub-task / threads?
I'm using celery with django and am trying to get a Task, like the one below:
class task1 (Task)
def run (self):
launch_some_other_task.delay()
But it doesn't seem to be working, I can go into more detail as far as my code but figured I w... | Celery, Django.. making a Task / thread launch sub-task / threads? | I'm using celery with django and am trying to get a Task, like the one below:
class task1 (Task)
def run (self):
launch_some_other_task.delay()
But it doesn't seem to be working, I can go into more detail as far as my code but figured I would just ask first if this sort of thing will work as doesn't seem to b... | [
"Make sure you've added the following to your urls.py:\nimport djcelery\ndjcelery.setup_loader()\n\n"
] | [
0
] | [] | [] | [
"celery",
"django",
"multithreading",
"python"
] | stackoverflow_0003862008_celery_django_multithreading_python.txt |
Q:
upload the image on s3 using boto
Here I have an image url. filename is image url
def upload(filename, content)
conn = S3Connection(aws_access_key, aws_secret_key)
b = Bucket(conn, bucket_name)
k = Key(b)
k.key = filename..split('/')[::-1][0]
k.set_metadata("Content-Type", 'images/jpeg')
k.... | upload the image on s3 using boto | Here I have an image url. filename is image url
def upload(filename, content)
conn = S3Connection(aws_access_key, aws_secret_key)
b = Bucket(conn, bucket_name)
k = Key(b)
k.key = filename..split('/')[::-1][0]
k.set_metadata("Content-Type", 'images/jpeg')
k.set_contents_from_string(content)
k... | [
"I'm pretty sure images/jpeg is a typo. The correct mimetype is:\nimage/jpeg\n\n",
"k.key = filename..split('/')[::-1][0]\n\nThis line has some syntax error. replace .. with . \nCheck your file permission for the image file you are trying to read. From the error message it seems like you, or at least your progra... | [
5,
2
] | [] | [] | [
"amazon_s3",
"boto",
"file_upload",
"python"
] | stackoverflow_0004212173_amazon_s3_boto_file_upload_python.txt |
Q:
Starting value for Pythonic generator over possible letter combinations
I am trying to (1) iterate over all possible combinations of letters and (2) remembering where I left of.
E.g. a,b, c, d, ... z, aa, ab, ac, ad, ..., zz, aaa, ...
The first part is working, using the following code:
def xselections(items, n):... | Starting value for Pythonic generator over possible letter combinations | I am trying to (1) iterate over all possible combinations of letters and (2) remembering where I left of.
E.g. a,b, c, d, ... z, aa, ab, ac, ad, ..., zz, aaa, ...
The first part is working, using the following code:
def xselections(items, n):
if n==0: yield []
else:
for i in xrange(len(items)):
... | [
"This should do the job:\nimport itertools\n\nletters = [ chr(l) for l in range(ord('a'), ord('z')+1) ]\n\ndef combinations(skip_to=None):\n combinations = ( itertools.combinations_with_replacement(letters, k) for k in range(1, len(letters)+1) )\n flat = itertools.chain.from_iterable( combinations )\n retu... | [
2,
2
] | [] | [] | [
"counter",
"generator",
"persistence",
"python"
] | stackoverflow_0005526678_counter_generator_persistence_python.txt |
Q:
Prepopulate initial values for fields in the Django Admin without slugifying
In the Django admin, I can set a slug field to fill in automatically using prepopulated_fields. How can I set a field to fill in using a different function, for example just basic concatenation instead of lowercase and spaces-to-hyphens ... | Prepopulate initial values for fields in the Django Admin without slugifying | In the Django admin, I can set a slug field to fill in automatically using prepopulated_fields. How can I set a field to fill in using a different function, for example just basic concatenation instead of lowercase and spaces-to-hyphens ?
| [
"There is no out of the box support for this (assuming you're talking replacing the exact, live editing that preopulated_fields provides).\nThe slug function is written in JavaScript, in django/contrib/admin/media/js/urlify.js\nYou could potentially insert a new script in the ModelAdmin extra JS property, but make ... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005526820_django_python.txt |
Q:
Can you pickle methods python method objects using any pickle module?
I've got a long-running script, and the operations that it performs can be broken down into independent, but order-sensitive function calls. In addition, the pattern here is a bread-first walk over a graph, and restarting a depth after a crash i... | Can you pickle methods python method objects using any pickle module? | I've got a long-running script, and the operations that it performs can be broken down into independent, but order-sensitive function calls. In addition, the pattern here is a bread-first walk over a graph, and restarting a depth after a crash is not a happy option.
So then, my idea is as follows: as the script runs, ... | [
"You can pickle plain functions. Python stores the name and module and uses that to reload it. If you want to do the same with methods and such that's a little bit trickier. It can be done by breaking such objects down into component parts and pickling those.\n",
"If the arguments are all that matters, why not st... | [
2,
0
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0005526981_pickle_python.txt |
Q:
Why does Python json module represent floats in dictionary keys as strings?
See the following code:
>>> import json
>>> m = {}
>>> m[0.0] = 1.0
>>> json.dumps(m)
'{"0.0": 1.0}'
In the value of the JSON, we have 1.0. But in the key we have "0.0" (a Json string).
This ambiguous handling of floats just cost me some... | Why does Python json module represent floats in dictionary keys as strings? | See the following code:
>>> import json
>>> m = {}
>>> m[0.0] = 1.0
>>> json.dumps(m)
'{"0.0": 1.0}'
In the value of the JSON, we have 1.0. But in the key we have "0.0" (a Json string).
This ambiguous handling of floats just cost me some debugging time. Does anyone know why python's json module does this?
| [
"Because a JSON key must be a string. See the RFC.\n"
] | [
7
] | [] | [] | [
"floating_point",
"json",
"python"
] | stackoverflow_0005526995_floating_point_json_python.txt |
Q:
Inconsistent connection failure with Twisted after py2exe
My first question here, so go easy on me.
This is my situation:
I am creating a networked game in Python using the Twisted framework. The game connects to a master server via TCP on one port (the connection is kept alive for authentication), and then you ca... | Inconsistent connection failure with Twisted after py2exe | My first question here, so go easy on me.
This is my situation:
I am creating a networked game in Python using the Twisted framework. The game connects to a master server via TCP on one port (the connection is kept alive for authentication), and then you can join a network server on another port. Currently both the net... | [
"This sounds like a problem with your Windows network stack. Have you installed something that intentionally breaks networking, like AVG antivirus? If you have, your network may be broken :).\n"
] | [
1
] | [] | [] | [
"networking",
"ogre",
"python",
"timeout",
"twisted"
] | stackoverflow_0005238378_networking_ogre_python_timeout_twisted.txt |
Q:
Is it possible to embed jasper reports into a Python application?
If not, what other reporting alternatives would you recommend (free)?
A:
There is a jasper server out there you might want to have a look at.
I quote from its homepage: "JasperServer is the free, open source report server for JasperReports and OL... | Is it possible to embed jasper reports into a Python application? | If not, what other reporting alternatives would you recommend (free)?
| [
"There is a jasper server out there you might want to have a look at.\n\nI quote from its homepage: \"JasperServer is the free, open source report server for JasperReports and OLAP analysis.\"\n"
] | [
1
] | [] | [] | [
"jasper_reports",
"java",
"python",
"report"
] | stackoverflow_0005527318_jasper_reports_java_python_report.txt |
Q:
Some questions about Regex in Python
I would like to do some text conversion, such as reading in from a text file:
CONTENTS
1. INTRODUCTION
1.1 The Linear Programming Problem 2
1.2 Examples of Linear Problems 7
and writing to another text file:
("CONTENTS" "#")
("1. INTRODUCTION" "#")
("1.1 The Linear Programmi... | Some questions about Regex in Python | I would like to do some text conversion, such as reading in from a text file:
CONTENTS
1. INTRODUCTION
1.1 The Linear Programming Problem 2
1.2 Examples of Linear Problems 7
and writing to another text file:
("CONTENTS" "#")
("1. INTRODUCTION" "#")
("1.1 The Linear Programming Problem 2" "#11")
("1.2 Examples of L... | [
"With your regex you are searching for a line that ends with a number (and maybe trailing whitespace). You could make the number optional: ^(.+?(\\d+)?) *$ and make sure your group 2 reference inside zaa can handle an empty string. \ndef zaa(mat):\n return '(\"%s\" \"#%s\")' % (mat.group(1), (str(int(mat.group(2... | [
3,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005527223_python_regex.txt |
Q:
Python: Spaces to Tabs?
I have a python file (/home/test.py) that has a mixture of spaces and tabs in it.
Is there a programmatic way (note: programmatic, NOT using an editor) to convert this file to use only tabs? (meaning, replace any existing 4-spaces occurrences with a single tab)?
Would be grateful for either... | Python: Spaces to Tabs? | I have a python file (/home/test.py) that has a mixture of spaces and tabs in it.
Is there a programmatic way (note: programmatic, NOT using an editor) to convert this file to use only tabs? (meaning, replace any existing 4-spaces occurrences with a single tab)?
Would be grateful for either a python code sample or a li... | [
"Sounds like a task for sed:\nsed -e 's/ /\\t/g' test.py > test.new\n\n[Put a real tab instead of \\t]\nHowever...\n\nUse 4 spaces per indentation level.\n\n--PEP 8 -- Style Guide for Python Code\n",
"you can try iterating the file and doing replacing eg\nimport fileinput\nfor line in fileinput.FileInput(\"fil... | [
8,
1
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0005527589_linux_python.txt |
Q:
Store a file metadata in an extra file
I have a bunch of image files (mostly .jpg). I would like to store metadata about these files (e.g. dominant color, color distribution, maximum gradient flow field, interest points, ...). These data fields are not fixed and are not available in all images.
Right now I am stor... | Store a file metadata in an extra file | I have a bunch of image files (mostly .jpg). I would like to store metadata about these files (e.g. dominant color, color distribution, maximum gradient flow field, interest points, ...). These data fields are not fixed and are not available in all images.
Right now I am storing the metadata for each file as a separate... | [
"I would suggest that you store such metadata within the image files themselves.\nMost image formats support storing metadata. I think that .jpeg support it through Exif.\nIf you're on Windows you can use the WIC to store and retrieve metadata in a unified manner.\n",
"Why protocol buffers and not XML or INI file... | [
2,
1,
0,
0
] | [] | [] | [
"c++",
"computer_vision",
"linux",
"python",
"serialization"
] | stackoverflow_0005524027_c++_computer_vision_linux_python_serialization.txt |
Q:
printing while process works in python
Is there any way to print out, say a period, for every second (or whatever unit) a process works (like compiling a java program (note: javac is called from my python program))?
A:
Blueprint:
start your process using subprocess.Popen(...)
Popen.poll() for checking the state... | printing while process works in python | Is there any way to print out, say a period, for every second (or whatever unit) a process works (like compiling a java program (note: javac is called from my python program))?
| [
"Blueprint:\n\nstart your process using subprocess.Popen(...)\nPopen.poll() for checking the state of the process\nuse something like http://pypi.python.org/pypi/progressbar/2.3-dev for rendering a progressbar (or search on PyPI for something similar) while polling\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0005527546_python.txt |
Q:
Why did I get this [1, 2, 4, 8, 16, 1, 16, 8, 4, 2, 1]?
Through much trial and error I found the following lines of python code,
for N in range(2**1,2**3):
print [(2**n % (3*2**(2*N - n))) % (2**N-1) for n in range(2*N+1)]
which produce the following output,
[1, 2, 1, 2, 1]
[1, 2, 4, 1, 4, 2, 1]
[1, 2, 4, 8, ... | Why did I get this [1, 2, 4, 8, 16, 1, 16, 8, 4, 2, 1]? | Through much trial and error I found the following lines of python code,
for N in range(2**1,2**3):
print [(2**n % (3*2**(2*N - n))) % (2**N-1) for n in range(2*N+1)]
which produce the following output,
[1, 2, 1, 2, 1]
[1, 2, 4, 1, 4, 2, 1]
[1, 2, 4, 8, 1, 8, 4, 2, 1]
[1, 2, 4, 8, 16, 1, 16, 8, 4, 2, 1]
[1, 2, 4, ... | [
"First of all, as others have said, there are much simpler implementations possible, and you should probably use these.\nBut to answer your question, here's why you get this result:\nWhen n<N:\n2n % (3*22N-n) = 2n, because 2n < 3*22N-n. Then 2n % (2N-1) = 2n, giving the expected result.\nWhen n=N:\n2N % (3*22N-N) =... | [
13,
6,
1
] | [] | [] | [
"algorithm",
"language_agnostic",
"math",
"number_theory",
"python"
] | stackoverflow_0005488959_algorithm_language_agnostic_math_number_theory_python.txt |
Q:
Iterating the lines of a text file and then returning a dictionary in python?
I'm supposed to write a function that will open a data file, where each data file resembles this:
WH239, Mountain Bike Wheel, 5000
Where the id is WH239, the description is 'Mountain Bike Wheel' and the cost is 5000
The func... | Iterating the lines of a text file and then returning a dictionary in python? | I'm supposed to write a function that will open a data file, where each data file resembles this:
WH239, Mountain Bike Wheel, 5000
Where the id is WH239, the description is 'Mountain Bike Wheel' and the cost is 5000
The function then assigns the id as a key in a dictionary and the description and price as ... | [
"you should try something like \ndoc = open('your file')\nfor line in doc.readline():\n if len(line) != 0:\n line.split(',')\n\n",
"code:\n import sys,os\n lis = []\n my_dict = {}\n\n def load():\n doc = open('/home/sahil/python/file.txt','U')\n data = doc.read()\n data ... | [
3,
0
] | [] | [] | [
"file",
"loops",
"python"
] | stackoverflow_0005527454_file_loops_python.txt |
Q:
Triangular contour with meshgrid
I'm trying to recreate the diagram (or just a contour plot would be okay) for the Dirichlet distribution that's on Wikipedia using matplotlib and numpy. I am having trouble easily generating a triangular contourf. The first problem is that meshgrid doesn't return a triangle of po... | Triangular contour with meshgrid | I'm trying to recreate the diagram (or just a contour plot would be okay) for the Dirichlet distribution that's on Wikipedia using matplotlib and numpy. I am having trouble easily generating a triangular contourf. The first problem is that meshgrid doesn't return a triangle of points. Even if I get a triangle of poi... | [
"You do not need a rectilinear meshgrid to create a contour plot. You can define the perimeter and perform a Delaunay triangulation. The coordinates, of course will still be rectilinear and (it appears) you'll need to do a transformation. This example should be enough to create a 2D contour. I have produced som... | [
2
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0005526743_matplotlib_numpy_python.txt |
Q:
Python IRC bot help
Possible Duplicate:
Python IRC bot question
How do I implement functionality into an existing Python IRC bot framework that ill accept Python source a line at a time, accepting multi-line statements and preserving the results for later use? Like, if I want to define a function from my IRC wi... | Python IRC bot help |
Possible Duplicate:
Python IRC bot question
How do I implement functionality into an existing Python IRC bot framework that ill accept Python source a line at a time, accepting multi-line statements and preserving the results for later use? Like, if I want to define a function from my IRC window and then be able to... | [
"I'd look at eval(), as it runs strings as Python code:\neval('print 3 + 1') # Outputs: 4\n\nYou can use this function to evaluate strings as Python code (in your case lines of IRC chat). Be very careful with this, as it allows arbitrary access to the Python interpreter, which can 'splode your computer if someone e... | [
1
] | [] | [] | [
"bots",
"function",
"irc",
"linux",
"python"
] | stackoverflow_0005527728_bots_function_irc_linux_python.txt |
Q:
customize django runserver output
I want edit out put of django runserver ... i want add now object address like apps.views.index
add all query in this request
how can change code for this setting?
A:
I wouldn't recommend modifying the runserver command, but...
django-devserver has a replacement for the manage.... | customize django runserver output | I want edit out put of django runserver ... i want add now object address like apps.views.index
add all query in this request
how can change code for this setting?
| [
"I wouldn't recommend modifying the runserver command, but...\ndjango-devserver has a replacement for the manage.py runserver command that allows extending the output to show any information you're interested in.\nThe instructions on the page linked above show how to install, and near the bottom there is a \"Buildi... | [
2,
1,
0
] | [] | [] | [
"django",
"logging",
"python"
] | stackoverflow_0005472771_django_logging_python.txt |
Q:
Python / BeautifulSoup: How to look directly beneath a code comment?
I'm parsing some webpages with BeautifulSoup and trying to work within the library (instead of trying to solve everything with a brute forced regex..)
The page I'm looking at is structured like this:
<!--comment-->
<div>a</div>
<div>b</div>
<div... | Python / BeautifulSoup: How to look directly beneath a code comment? | I'm parsing some webpages with BeautifulSoup and trying to work within the library (instead of trying to solve everything with a brute forced regex..)
The page I'm looking at is structured like this:
<!--comment-->
<div>a</div>
<div>b</div>
<div>c</div>
<!--comment-->
<div>a</div>
<div>b</div
<div>c</div
I want to p... | [
"Comments are nodes, like anything else:\nfrom BeautifulSoup import BeautifulSoup\nfrom BeautifulSoup import Comment\nfrom BeautifulSoup import NavigableString\n\ntext = BeautifulSoup(\"\"\"<!--comment--><div>a</div><div>b</div><div>c</div>\n <!--comment--><div>a</div><div>b</div><div>c</div>... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0005527935_beautifulsoup_python.txt |
Q:
Google Data/OAuth/AppEngine/Python - Properly Registering a Web Application
I'm creating a webapp with this combination of tools. I'm authenticating with App Engine in the following manner:
class googleLogin(webapp.RequestHandler):
def get(self):
callbackURL = 'http://%s/googleLoginCallback' % getHost()
... | Google Data/OAuth/AppEngine/Python - Properly Registering a Web Application | I'm creating a webapp with this combination of tools. I'm authenticating with App Engine in the following manner:
class googleLogin(webapp.RequestHandler):
def get(self):
callbackURL = 'http://%s/googleLoginCallback' % getHost()
#Create a client service
gdClient = gdata.docs.service.DocsService()
gd... | [
"Solved.\nThe culprit is this line from above:\nextra_parameters={'xoauth_displayname': APP_NAME})\n\nSetting this value for a registered application intentionally triggers a warning to users, as indicated by the Google documentation:\n\nxoauth_displayname:\n(optional) String identifying the\napplication. This stri... | [
3,
0
] | [] | [] | [
"google_app_engine",
"google_data_api",
"iphone",
"oauth",
"python"
] | stackoverflow_0005527116_google_app_engine_google_data_api_iphone_oauth_python.txt |
Q:
Very basic persistence or data storage for a Python script
I have a script which processes a list of URLs. The script may be called at any time with a fresh list of URLs. I want to avoid processing an URL which has already been processed at any time in the past.
At this point, all I want to match are URLs, which a... | Very basic persistence or data storage for a Python script | I have a script which processes a list of URLs. The script may be called at any time with a fresh list of URLs. I want to avoid processing an URL which has already been processed at any time in the past.
At this point, all I want to match are URLs, which are really long strings, against all previously processed URLs, t... | [
"Store the URLs in a set, which assures O(1) for finding items, and shelve it. At this amount of URLs, storing and restoring will take very little time and memory:\nimport shelve\n\n# Write URLS to shelve\nurls= ['http://www.airmagnet.com/', 'http://www.alcatel-lucent.com/',\n 'http://www.ami.com/', 'http://w... | [
1,
1,
0
] | [] | [] | [
"persistence",
"python",
"shelve"
] | stackoverflow_0005528518_persistence_python_shelve.txt |
Q:
Script to convert unicode characters in format to their ASCII equivalents
Im doing some changes in Linux locale files /usr/share/i18n/locales (like pt_BR), to change the default format of dates, time, numbers, etc. But since unicode chars are presented as strings in the <U9999> format, text is very hard to read.
... | Script to convert unicode characters in format to their ASCII equivalents | Im doing some changes in Linux locale files /usr/share/i18n/locales (like pt_BR), to change the default format of dates, time, numbers, etc. But since unicode chars are presented as strings in the <U9999> format, text is very hard to read.
Here is a snippet of it:
LC_TIME
abday "<U0044><U006F><U006D>";"<U0053><U0065>... | [
"Using Fields\n#!/bin/bash\n\nawk -F'<U0+|>' '{\n for(i=1;i<=NF;i++)\n if($i ~ \"^[0-9A-F]+$\")\n $i=sprintf(\"%c\", strtonum(\"0x\"$i))\n}1' OFS=\"\" /path/to/infile\n\nExplanation\n\n-F'<U0+|>': This is the magic that makes this script so short. We tell awk that the field separator is either ... | [
2,
1
] | [] | [] | [
"bash",
"python",
"unicode",
"xml"
] | stackoverflow_0005527122_bash_python_unicode_xml.txt |
Q:
sorting a file?
I need to read a existing file that i wrote using a empty list for users raw_input. Not exactly sure on how I sort the file after reading. After sorting, i need to save it under a different file name and print.
This is what I have so far:
Names=[]
while 1:
Input = raw_input("Enter a name or p... | sorting a file? | I need to read a existing file that i wrote using a empty list for users raw_input. Not exactly sure on how I sort the file after reading. After sorting, i need to save it under a different file name and print.
This is what I have so far:
Names=[]
while 1:
Input = raw_input("Enter a name or press 'v' to quit:")
... | [
"you can just sort the list of names .... names.sort()\n>>> names=[\"John\",\"Angel\",\"Luis\"]\n>>> names.sort()\n>>> names\n['Angel', 'John', 'Luis']\n\nEdit: comment answer\nwritelines doesn't add line separators therefore\nwhen you do text_file.writelines(Names) you are writing just one line.\nTo write line sep... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005528768_python.txt |
Q:
Change values of a table using urllib
I am trying to change the values in a table using urllib. I believe the way to do this is by using post request. However I am having no success whatsoever and am completely lost.
Any help you can share is appreciated.
Here is the page I am trying to edit (editme.php)
<html>
<... | Change values of a table using urllib | I am trying to change the values in a table using urllib. I believe the way to do this is by using post request. However I am having no success whatsoever and am completely lost.
Any help you can share is appreciated.
Here is the page I am trying to edit (editme.php)
<html>
<body>
<div>
<table>
... | [
"Em... sorry, but there is no way you'll change that table value via urllib, unless the php script does that. And the editme.php is a \"pure\" html file. \n",
"Does not make any sense what you are asking. You have to change the template or whatever is rendering your table on the SERVER and not through download/up... | [
0,
0
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0005528807_python_urllib.txt |
Q:
struct in python
I have been unable to understand the working of pack in struct in python.
For example I need to make 4 bytes of data together into one struct.
Suppose the first byte has the value 4 in it while the second has 5 and then 6 and last 7.
so i make it as
a = chr(4 & 0x0f)
b = chr(5 & 0x0f)
c = chr(6 &... | struct in python | I have been unable to understand the working of pack in struct in python.
For example I need to make 4 bytes of data together into one struct.
Suppose the first byte has the value 4 in it while the second has 5 and then 6 and last 7.
so i make it as
a = chr(4 & 0x0f)
b = chr(5 & 0x0f)
c = chr(6 & 0x0f)
d = chr(7 & 0x0... | [
"You can accomplish that with this\nimport struct\nstruct.pack('4B', 4, 6, 7, 8,)\n\nstruct is some kind of printf for building bytes structures is very handy\nwhen you are dealing with a low-level protocol, you can use the references of the \nmodule for the string formating, take a look at this wol script\nthat I ... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0005528875_python.txt |
Q:
Django: how to cache dynamic pages flexibly?
I was trying to set up cache for my Django application but it seems that Django's caching framework is based on TIMEOUT: set a cache and it'll remain valid for the TIMEOUT amount of seconds.
That seems pretty useless for most situations. Most webpages would have some us... | Django: how to cache dynamic pages flexibly? | I was trying to set up cache for my Django application but it seems that Django's caching framework is based on TIMEOUT: set a cache and it'll remain valid for the TIMEOUT amount of seconds.
That seems pretty useless for most situations. Most webpages would have some user contributed contents such as comments or votes ... | [
"There's a way to manually delete cached items in django. Search in the documentation for cache.delete and cache.delete_many. In your django views you could programatically decide when to invalidate (or delete) the cached item based on whatever rules you want. To avoid the TIME_OUT issue just give an enough long ti... | [
2
] | [] | [] | [
"caching",
"django",
"django_cache",
"python"
] | stackoverflow_0005528910_caching_django_django_cache_python.txt |
Q:
Handle large data pools in python
I'm working on an academic project aimed at studying people behavior.
The project will be divided in three parts:
A program to read the data from some remote sources, and build a local data pool with it.
A program to validate this data pool, and to keep it coherent
A web interf... | Handle large data pools in python | I'm working on an academic project aimed at studying people behavior.
The project will be divided in three parts:
A program to read the data from some remote sources, and build a local data pool with it.
A program to validate this data pool, and to keep it coherent
A web interface to allow people to read/manipulate ... | [
"Sounds that the main functionality needed can be found from:\npytables\nand\nscipy/numpy\n",
"Go with a NoSQL database like MongoDB which is much easier to handle data in such a case than having to learn SQL.\n",
"Since you aren't an expert I recommend you to use mysql database as the backend of storing your d... | [
5,
3,
1
] | [] | [] | [
"database",
"large_data",
"python"
] | stackoverflow_0005529075_database_large_data_python.txt |
Q:
How to check if the key the i want is existing in python
I have a tuple of objects that looks like this:
('MATE555', ([('Wdfd',7), ('dfs', 2), ('Tdfs77', 2), ('Fsf1', 1), ('s01', 1), ('Bdf1', 1), ('fs01', 1)],))and i want function created which would check if the name key exist.if it exist it would return the 2nd ... | How to check if the key the i want is existing in python | I have a tuple of objects that looks like this:
('MATE555', ([('Wdfd',7), ('dfs', 2), ('Tdfs77', 2), ('Fsf1', 1), ('s01', 1), ('Bdf1', 1), ('fs01', 1)],))and i want function created which would check if the name key exist.if it exist it would return the 2nd part of the tuple, if not it would return 'no key'.
example
g... | [
"Why are you using tuple object for 'key -> value' data model ?\nPython has a HashMap class called \"Dictionary\" which should be used instead of tuple for 'key -> value' data model as it offers more flexibility than tuple:\nCreating dict from list: \nyour_dict = dict([(key1, value1), (key2, value2), (key3, value3... | [
2,
1
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0005529128_python_tuples.txt |
Q:
Using gethostbyaddr with app engine
I am trying to user gethostbyaddr in Google App Engine - Python.
I have
import socket
and then
class BeatMail(webapp.RequestHandler):
def get(self):
refer = self.request.remote_addr
referName = socket.gethostbyaddr(refer)
self.response.out.write(ref... | Using gethostbyaddr with app engine | I am trying to user gethostbyaddr in Google App Engine - Python.
I have
import socket
and then
class BeatMail(webapp.RequestHandler):
def get(self):
refer = self.request.remote_addr
referName = socket.gethostbyaddr(refer)
self.response.out.write(referName)
But I'm getting erros on socket.... | [
"socket is disabled in the AppEngine API. See runtime docs.\n",
"gethostbyaddr is unluckily not supported yet, there's an open feature request here.\n"
] | [
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005526834_google_app_engine_python.txt |
Q:
query to app engine database coming up blank
i have this issue with app engine's datastore. In interactive console, I always get no entities when i ask if a url already exists in my db. When I execute the following code....
from google.appengine.ext import db
class shortURL(db.Model):
url = db.TextProperty... | query to app engine database coming up blank | i have this issue with app engine's datastore. In interactive console, I always get no entities when i ask if a url already exists in my db. When I execute the following code....
from google.appengine.ext import db
class shortURL(db.Model):
url = db.TextProperty()
date = db.DateTimeProperty(auto_now_add=Tru... | [
"TextProperty values are not indexed, and cannot be used in filters or sort orders.\nYou might want to try with StringProperty if you don't need more than 500 characters.\n",
"I think .fetch() is missing . you can do a fetch before you do some manipulation on a model.\nAlso. I don't think you need db.TextProperty... | [
1,
0
] | [] | [] | [
"datastore",
"google_app_engine",
"python"
] | stackoverflow_0005527779_datastore_google_app_engine_python.txt |
Q:
Comparing string in Python: String X is ASCII, and String Y is UTF
I have a rather weird problem:
How do I compare strings (using Python ) that where String X is ASCII and String Y is in UTF or Unicode?
Currently, when I am comparing strings, I receive the following issue:
UnicodeWarning: Unicode equal comparison ... | Comparing string in Python: String X is ASCII, and String Y is UTF | I have a rather weird problem:
How do I compare strings (using Python ) that where String X is ASCII and String Y is in UTF or Unicode?
Currently, when I am comparing strings, I receive the following issue:
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being... | [
"Convert all string using the underlaying encoding and compare them:\nprint unicode(s1, 'ascii') == unicode(s1, 'utf-8')\n\n"
] | [
6
] | [] | [] | [
"ascii",
"python",
"string_comparison",
"unicode",
"utf_8"
] | stackoverflow_0005529918_ascii_python_string_comparison_unicode_utf_8.txt |
Q:
Load image in new thread
I'm downloading image with urllib2 in python. The operations is called by timer, so sometimes it hangs my programm. Is it possible to work with urllib2 and threads?
My current code:
f = open('local-path', 'wb')
f.write(urllib2.urlopen('web-path').read())
f.close()
So, how to run this code... | Load image in new thread | I'm downloading image with urllib2 in python. The operations is called by timer, so sometimes it hangs my programm. Is it possible to work with urllib2 and threads?
My current code:
f = open('local-path', 'wb')
f.write(urllib2.urlopen('web-path').read())
f.close()
So, how to run this code in new thread?
| [
"Here's a very basic example of what I think you've asked for. And yes, as RestRisiko says, urllib2 is thread-safe, if that's actually all you're asking.\nimport threading\nimport urllib2\nfrom time import sleep\n\ndef load_img(local_path, web_path):\n f = open(local_path, 'wb')\n f.write(urllib2.urlopen(web_... | [
2
] | [] | [] | [
"multithreading",
"python",
"urllib2"
] | stackoverflow_0005529905_multithreading_python_urllib2.txt |
Q:
Downloading Swampy on Windows
I am a Windows user learning Python who wants to get Swampy working. I downloaded the .zip file, which went to my downloads folder. Where do I go from there to get it so it works with my Python 2.7.1?
A:
I would follow these instructions: Swampy: Installation Instructions.
| Downloading Swampy on Windows | I am a Windows user learning Python who wants to get Swampy working. I downloaded the .zip file, which went to my downloads folder. Where do I go from there to get it so it works with my Python 2.7.1?
| [
"I would follow these instructions: Swampy: Installation Instructions.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0005529992_python.txt |
Q:
Finding an element of a list when the list is in a dictionary?
This is homework, so I don't expect the answer, just a point in the right direction.
In python I have a dictionary that is like so:
{'bike101': ('Road Bike',
[('WH139', 2),
('TR102', 2),
('TU177', 2),
... | Finding an element of a list when the list is in a dictionary? | This is homework, so I don't expect the answer, just a point in the right direction.
In python I have a dictionary that is like so:
{'bike101': ('Road Bike',
[('WH139', 2),
('TR102', 2),
('TU177', 2),
('FR101', 1),
('FB101', 1),
('BB101'... | [
"Since you're asking for hints, I won't post working code.\nYour code is a list comprehension, so it outputs a list. If there is no result, the list will be empty. You can bind the list to a variable, use len() to check its length and return None if it is 0.\n",
"Using a list comprehension is perhaps not the most... | [
2,
2,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0005529672_dictionary_python.txt |
Q:
How to get linear descent random distribution?
Curently in django I implement showing person on main page randomly.
But now I need to show persons regarding their importance (which is number).
For example:
Name|Sortkey
John| 5
Tom | 8
John have to be shown more often linearly.
person_number = random.randrange(Pers... | How to get linear descent random distribution? | Curently in django I implement showing person on main page randomly.
But now I need to show persons regarding their importance (which is number).
For example:
Name|Sortkey
John| 5
Tom | 8
John have to be shown more often linearly.
person_number = random.randrange(Person.objects.count())
context = { 'person': Person.obj... | [
"I am guessing you mean a weighted random choice. Basically you need to:\n\nCreate the list with the accumulative sum of weights.\nChoose a random value [0, sum_of_weights-1]\nFind the index in which the random value fell.\n\nIn Python terms, with a functional approach (ireduce = scanl = partial_sum = ...), it coul... | [
5
] | [] | [] | [
"python",
"random"
] | stackoverflow_0005529835_python_random.txt |
Q:
Signal Not Emitted when selecting tab in Pyqt
I have a tab widget created with 3 tabs in it. I need to emit signals when I change the tab, Looking at the pyQt documentation currentChanged() is the signal that is emitted on Changing the tab but it does not work for me. So need your help on understanding the same,... | Signal Not Emitted when selecting tab in Pyqt | I have a tab widget created with 3 tabs in it. I need to emit signals when I change the tab, Looking at the pyQt documentation currentChanged() is the signal that is emitted on Changing the tab but it does not work for me. So need your help on understanding the same,
MY code is as follows:
main_tab_widget = QTabWidge... | [
"You're attempting to wire up the currentChanged signal from the wrong object. main_tab_object is the QTabWidget that emits this signal, but you're attempting to wire up this signal from self.cc_tab, a QWidget in one of the tabs.\nReplace the line\n self.connect(self.cc_tab, SIGNAL('currentChanged(int)'), self.... | [
6
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"tabbar",
"tabwidget"
] | stackoverflow_0005530113_pyqt_pyqt4_python_tabbar_tabwidget.txt |
Q:
Python: How to write a dictionary of tuple values to a csv file?
How do I print the following dictionary into a csv file?
maxDict = {'test1': ('alpha', 2), 'test2': ('gamma', 2)}
So, that the output CSV looks as follows:
test1, alpha, 2
test2, gamma, 2
A:
import csv
with open("data.csv", "wb") as f:
csv.wr... | Python: How to write a dictionary of tuple values to a csv file? | How do I print the following dictionary into a csv file?
maxDict = {'test1': ('alpha', 2), 'test2': ('gamma', 2)}
So, that the output CSV looks as follows:
test1, alpha, 2
test2, gamma, 2
| [
"import csv\nwith open(\"data.csv\", \"wb\") as f:\n csv.writer(f).writerows((k,) + v for k, v in maxDict.iteritems())\n\n",
"maxDict = {'test1': ('alpha', 2), 'test2': ('gamma', 2)}\ncsvData = []\nfor col1, (col2, col3) in maxDict.iteritems():\n csvData.append(\"%s, %s, %s\" % (col1, col2, col3))\nf = open('... | [
6,
2
] | [] | [] | [
"csv",
"dictionary",
"python",
"tuples"
] | stackoverflow_0005530619_csv_dictionary_python_tuples.txt |
Q:
E-mail confirmation implementation in Django
I have created a Django app. I have a registration page(simple HTML form) in the app,and it has an e-mail field while registering. Now i wanted to implement an email verification when the user registers. Like sending an email to the user (to email given in registration ... | E-mail confirmation implementation in Django | I have created a Django app. I have a registration page(simple HTML form) in the app,and it has an e-mail field while registering. Now i wanted to implement an email verification when the user registers. Like sending an email to the user (to email given in registration form). By googling i found there is a Django metho... | [
"I would use the django-registration app. You can find more documentation and tutorials through Google.\n",
"i think you should use Signals\nlike django-registration\n"
] | [
2,
0
] | [] | [] | [
"django",
"django_models",
"django_templates",
"javascript",
"python"
] | stackoverflow_0005495119_django_django_models_django_templates_javascript_python.txt |
Q:
Python web-scraping threaded performance
I have a web app that needs both functionality and performance tested, and part of the test suite that we plan on using is already written in Python. When I first wrote this, I used mechanize as my means of web-scraping, but it seems to be too bulky for what I'm trying to d... | Python web-scraping threaded performance | I have a web app that needs both functionality and performance tested, and part of the test suite that we plan on using is already written in Python. When I first wrote this, I used mechanize as my means of web-scraping, but it seems to be too bulky for what I'm trying to do (either that or I'm missing something).
The ... | [
"Threading causes problems with the GIL, more so with more cores. Try using mechanize with eventlet to achieve concurrency (via multiple processes) also check out multi-mechanize\n",
"Have you considered Twisted, the asynchronous library, for at least doing interaction with users?\n",
"I actually went without u... | [
1,
0,
0
] | [] | [] | [
"automated_tests",
"mechanize_python",
"python",
"urllib2",
"web_scraping"
] | stackoverflow_0005002986_automated_tests_mechanize_python_python_urllib2_web_scraping.txt |
Q:
How to refactor switch case statements in python?
This code is parts of Google app engine web apps. Any refactoring ideas of blow code?
def post(self):
user = User.all().filter("id =",self.request.get('id')).get()
for arg in self.request.arguments():
if arg == 'name':
user.name = self.r... | How to refactor switch case statements in python? | This code is parts of Google app engine web apps. Any refactoring ideas of blow code?
def post(self):
user = User.all().filter("id =",self.request.get('id')).get()
for arg in self.request.arguments():
if arg == 'name':
user.name = self.request.get(arg)
elif arg == 'sex':
... | [
"valid_args = set(('name', 'sex', 'age', 'interest', 'location', 'latitude', 'longitude'))\n\nfor arg in self.request.arguments():\n if arg in valid_args:\n setattr(user, arg, self.request.get(arg))\n\nLikely there are attributes of User objects that you don't want application users to be able to modify j... | [
8
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005529807_google_app_engine_python.txt |
Q:
Which mail server can I control from Python / Django?
I'm looking for a mail server that I can completely control from Python/Django. When I say "completely control", I'm just talking about basic administrative tasks like: (1)setting up new accounts, (2)changing account passwords, (3) setting / changing email forw... | Which mail server can I control from Python / Django? | I'm looking for a mail server that I can completely control from Python/Django. When I say "completely control", I'm just talking about basic administrative tasks like: (1)setting up new accounts, (2)changing account passwords, (3) setting / changing email forwarding, and perhaps some other basic account settings.
To ... | [
"i've never used lamson, but it's worth taking a look at it.\nhttp://lamsonproject.org/ it seems interesting for several reasons.\nbut in general, you can easily build a wrapper around any mail server that has commandline tools for configuration, and any mail server that can store users and aliases in a database, w... | [
0
] | [] | [] | [
"django",
"email",
"python"
] | stackoverflow_0005530343_django_email_python.txt |
Q:
multiply a matrix by an integer in python
I know how to multiply two matrices(under a class). Below I show my code. However I can not seem to figure out how to multiply a matrix and an integer in Python.
Update:
Example of a matrix.
L=[[1,2],[3,4],[5,6]]
3*L
# [[1,6],[9,12],[15,18]]
def __mul__(self,other):
'... | multiply a matrix by an integer in python | I know how to multiply two matrices(under a class). Below I show my code. However I can not seem to figure out how to multiply a matrix and an integer in Python.
Update:
Example of a matrix.
L=[[1,2],[3,4],[5,6]]
3*L
# [[1,6],[9,12],[15,18]]
def __mul__(self,other):
'''this will multiply two predefined matrices wh... | [
"Depends on what you mean by matrix, but with numpy, it would be just like:\nimport numpy as np\n\nM= np.arange(9).reshape(3, 3)\n# array([[0, 1, 2],\n# [3, 4, 5],\n# [6, 7, 8]])\n2* M\n# array([[ 0, 2, 4],\n# [ 6, 8, 10],\n# [12, 14, 16]])\n\nor\nM= np.matrix([[1, 2], [3, 4]])\n# mat... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0005530770_python.txt |
Q:
count cookies in python
I am struggling with python ,I want to Write a Python script that creates a cookie and Counts how many times the cookie is called during a session
I just have tried as per below:
import Cookie
import os
if os.environ.has_key('HTTP_COOKIE'):
cookie=SimpleCookie(os.environ['HTTP_COOKIE'])... | count cookies in python | I am struggling with python ,I want to Write a Python script that creates a cookie and Counts how many times the cookie is called during a session
I just have tried as per below:
import Cookie
import os
if os.environ.has_key('HTTP_COOKIE'):
cookie=SimpleCookie(os.environ['HTTP_COOKIE'])
cookie=SimpleCookie()
for ke... | [
"I'm confused by your question. What I believe you want to do is request some webpage and count how many times your cookie was found? You can gather cookies using a CookieJar:\nimport urllib, urllib2, cookielib\n\nurl = \"http://example.com/cookies\"\nform_data = {'username': '', 'password': '' }\n\njar = cookiel... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0005529894_python.txt |
Q:
How to convert time format into milliseconds and back in Python?
The reason is because I'm making a script to work with ffmpeg and I need to be able to add/subtract time in the format 00:00:00[.000]
The last 3 digits are optional and they mean milliseconds. A time string could look like any of the following
4:34.2... | How to convert time format into milliseconds and back in Python? | The reason is because I'm making a script to work with ffmpeg and I need to be able to add/subtract time in the format 00:00:00[.000]
The last 3 digits are optional and they mean milliseconds. A time string could look like any of the following
4:34.234
5.000
2:99:34
4:14
This would be easier if a lot of the digits wer... | [
"From string to milliseconds:\ns = \"4:34.234\"\nhours, minutes, seconds = ([\"0\", \"0\"] + s.split(\":\"))[-3:]\nhours = int(hours)\nminutes = int(minutes)\nseconds = float(seconds)\nmiliseconds = int(3600000 * hours + 60000 * minutes + 1000 * seconds)\n\nFrom milliseonds to string:\nhours, milliseconds = divmod(... | [
18
] | [
"from time import time\n\ntime_in_seconds = int(time())\ntime_in_miliseconds = int(time_in_seconds *1000)\n\nYou can also use str(x) to convert x to a string. From there you can use various methods to create the string you want, such as: (both of these assume you already have the variables hrs, min, sec, msec with... | [
-1
] | [
"datetime",
"python"
] | stackoverflow_0005531249_datetime_python.txt |
Q:
Python lists and iterables
in Python 3.2 How do I alter items in a list with a function and return the result of the function over the item and the item itself before altering? 10x
def some(func,seq):
# What to do here?
A:
Something like
def func(my_func,seq):
return seq, [my_func(n) for n in seq]
or
d... | Python lists and iterables | in Python 3.2 How do I alter items in a list with a function and return the result of the function over the item and the item itself before altering? 10x
def some(func,seq):
# What to do here?
| [
"Something like \ndef func(my_func,seq):\n return seq, [my_func(n) for n in seq]\n\nor\ndef func(my_func,seq):\n return [(my_func(n),n) for n in seq]\n\n... your description is not very clear in that regard.\nWhat's being used here is a list comprehension. my_func is called once for every element in seq and s... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0005531469_python.txt |
Q:
Sorting a dictionary which has values as list, and sorting based on the elements inside this list
I have a list
A={'k3': ['b', 3],'k2': ['a', 1],'k1': ['a', 3],'k4': ['c', 2],'k5': ['b', 2]}
I want to sort the above dictionary first by letters 'a','b' and 'c' in an ascending order
and then based on values 3,2,1 i... | Sorting a dictionary which has values as list, and sorting based on the elements inside this list | I have a list
A={'k3': ['b', 3],'k2': ['a', 1],'k1': ['a', 3],'k4': ['c', 2],'k5': ['b', 2]}
I want to sort the above dictionary first by letters 'a','b' and 'c' in an ascending order
and then based on values 3,2,1 in the descending order. So my output should look something like
A={'k1': ['a', 3],'k2': ['a', 1],'k3': ... | [
"Dictionaries are unordered, so you can't create a sorted dictionary.\nIf you just want a list of dictionary keys, sorted by the associated values, you could use sorted() like this:\n>>> keys = sorted(A, key=lambda k: (A[k][0], -A[k][1]))\n>>> keys\n['k1', 'k2', 'k3', 'k5', 'k4']\n\n",
"Python recently added an O... | [
2,
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005531489_python.txt |
Q:
Efficiently prepending text to a very large text file in Python
I have to prepend some arbitrary text to an existing, but very large (2 - 10 GB range) text file. With the file being so large, I'm trying to avoid reading the entire file in to memory. But am I being too conservative with a line-by-line iteration? Wo... | Efficiently prepending text to a very large text file in Python | I have to prepend some arbitrary text to an existing, but very large (2 - 10 GB range) text file. With the file being so large, I'm trying to avoid reading the entire file in to memory. But am I being too conservative with a line-by-line iteration? Would moving to a readlines(sizehint) approach give me much of a perfor... | [
"If this is on Windows NTFS, you can insert into the middle of a file. (Or so I'm told, I'm not a Windows developer).\nIf this is on a POSIX (Linux or Unix) system, you should use \"cat\" as someone else said. cat is wickedly efficient, using every trick in the book to get optimal performance (ie. voids copying b... | [
2,
1,
1,
0
] | [] | [] | [
"file_io",
"large_files",
"python"
] | stackoverflow_0004965111_file_io_large_files_python.txt |
Q:
How to show MessageBox with pygtk?
In gtk/python, what is the equivalent of MessageBox?
A:
That would be gtk.MessageDialog.
Example:
parent = None
md = gtk.MessageDialog(parent,
gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO,
gtk.BUTTONS_CLOSE, "Download completed")
md.run()
A:
You can follow this ... | How to show MessageBox with pygtk? | In gtk/python, what is the equivalent of MessageBox?
| [
"That would be gtk.MessageDialog.\nExample:\nparent = None\nmd = gtk.MessageDialog(parent, \n gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, \n gtk.BUTTONS_CLOSE, \"Download completed\")\nmd.run()\n\n",
"You can follow this tutorial about message dialogs with PyGTK :\nhttp://zetcode.com/tutorials/pygtktu... | [
3,
3
] | [] | [] | [
"gtk",
"messagebox",
"python"
] | stackoverflow_0005531624_gtk_messagebox_python.txt |
Q:
Value Error in polymorphism Django-Model association
I've followed Django ContentTypes, Then I created an app for tagging purpose.
Like django-taggit or tagging.
tagging.models.py:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generi... | Value Error in polymorphism Django-Model association | I've followed Django ContentTypes, Then I created an app for tagging purpose.
Like django-taggit or tagging.
tagging.models.py:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.template.defaultfilters import slugify
clas... | [
"You need to convert your tag strings into actual Tag objects.\nfor tag_name in tag_names:\n tag, created = Tag.objects.get_or_create(name=tag_name)\n tagged = TaggedItem(object=article, tag=tag)\ntagged.save()\n\n"
] | [
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0005531268_django_django_models_python.txt |
Q:
Obtain SSL certificate from peer without verification using Python
Am in the process of building a quick python script to periodically check my clients websites are working correctly. One of these checks is to ensure their SSL certificates are current, or to provide an alert if their certificate is about to expire... | Obtain SSL certificate from peer without verification using Python | Am in the process of building a quick python script to periodically check my clients websites are working correctly. One of these checks is to ensure their SSL certificates are current, or to provide an alert if their certificate is about to expire.
The ssl packages provides a way to obtain the peer certificate with th... | [
"It may be possible to use a shell script to grab the certificates and then use Python to iterate over certificate output files. Something like:\n$ openssl s_client -connect host:port -showcerts > certfile\n\nmight work. You might also read the documentation on pyOpenSSL's Connection object, which has a get_peer_ce... | [
3
] | [] | [] | [
"python",
"ssl"
] | stackoverflow_0005480544_python_ssl.txt |
Q:
How do I install modules in Python on Windows?
Possible Duplicate:
Installing modules in Python on Windows
The instructions in the documentation aren't helping. How do I install a module in Python?
A:
If there is setup.py source file in module directory, run windows command line utility, change current direct... | How do I install modules in Python on Windows? |
Possible Duplicate:
Installing modules in Python on Windows
The instructions in the documentation aren't helping. How do I install a module in Python?
| [
"If there is setup.py source file in module directory, run windows command line utility, change current directory to module directory and write\npython setup.py install\n\nmake sure that python bin directory is in your system path variable\n",
"The same as everywhere, use easy_install. (Still it is somewhat more ... | [
3,
2,
0
] | [] | [] | [
"module",
"python"
] | stackoverflow_0005532010_module_python.txt |
Q:
Python: creating a function from dictionary
How to create a function which calculates the total value from 2 given dictionary
A:
If you have your data in a something like this:
Part = collections.namedtuple('Part', 'key name price')
parts = {
'WH239': Part('WH239', 'Mountain Bike Wheel', 5000),
'TR202': ... | Python: creating a function from dictionary | How to create a function which calculates the total value from 2 given dictionary
| [
"If you have your data in a something like this:\nPart = collections.namedtuple('Part', 'key name price')\nparts = {\n 'WH239': Part('WH239', 'Mountain Bike Wheel', 5000),\n 'TR202': Part('TR202', 'Mountain Bike Tire', 2000),\n 'TU277': Part('TU277', 'Mountain Bike Tube', 2000),\n 'FR201': Part('FR201',... | [
2,
0
] | [] | [] | [
"dictionary",
"function",
"python"
] | stackoverflow_0005527757_dictionary_function_python.txt |
Q:
Possible error reading data from different threads
I currently program a program which uses multiple threads. To be able to share data across these threads I use Locks like threading.Lock to avoid access problem during run.
But the problem that I got is that I have to create huge amount locks for every data just f... | Possible error reading data from different threads | I currently program a program which uses multiple threads. To be able to share data across these threads I use Locks like threading.Lock to avoid access problem during run.
But the problem that I got is that I have to create huge amount locks for every data just for reading that data. Even if I 'group' data and use for... | [
"If all your threads just read data, there is no problem accessing the data simultaneously from different threads, as long as reading the data does not change it. Changing the read data can occur in some data structure, defaultdict being a tricky example.\nIf you have a consumer\\producer scenario, consider using Q... | [
0,
0,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0005531699_multithreading_python.txt |
Q:
python socket/port problem/question
I am writing 2 small programs (a server and a client) and whenever I run both, and have the client connect to the server, the server output says that I am connected on a port of which I didn't bind in the code. I binded both the server and the client socket to the localhost and ... | python socket/port problem/question | I am writing 2 small programs (a server and a client) and whenever I run both, and have the client connect to the server, the server output says that I am connected on a port of which I didn't bind in the code. I binded both the server and the client socket to the localhost and port 8000, but every time the server is c... | [
"The port number it's reporting is the one the client connected from. And it will be a random port number. If (as your question seems to imply) you have a bind call in the client that looks just like the one in the server, then I'm surprised it's succeeding since the server has already bound itself to that port and... | [
2,
0,
0
] | [] | [] | [
"networking",
"python"
] | stackoverflow_0005532081_networking_python.txt |
Q:
Is there a way to fetch past (or at least the last) "print" calls?
Consider:
print "Hello"
print "Goodbye"
Is there any way to fetch what was said in those print calls?
Example:
print "The last print was", output.previousMessage()
A:
>>> import sys
>>> last_print = None
>>>
>>> # this class will replace sys.std... | Is there a way to fetch past (or at least the last) "print" calls? | Consider:
print "Hello"
print "Goodbye"
Is there any way to fetch what was said in those print calls?
Example:
print "The last print was", output.previousMessage()
| [
">>> import sys\n>>> last_print = None\n>>>\n>>> # this class will replace sys.stdout\n>>> class PrintCatcher:\n... # catch and save writes (prints)\n... def write(self, data):\n... global last_print\n... if data != \"\\n\": last_print = data\n... \n... # write the data to the origin... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0005532213_python.txt |
Q:
Is there a clean way to get the n-th column of an html table using BeautifulSoup?
Say we look at the first table in a page, so:
table = BeautifulSoup(...).table
the rows can be scanned with a clean for-loop:
for row in table:
f(row)
But for getting a single column things get messy.
My question: is ther... | Is there a clean way to get the n-th column of an html table using BeautifulSoup? | Say we look at the first table in a page, so:
table = BeautifulSoup(...).table
the rows can be scanned with a clean for-loop:
for row in table:
f(row)
But for getting a single column things get messy.
My question: is there an elegant way to extract a single column, either by its position, or by its 'name' (... | [
"lxml is many times faster than BeautifulSoup, so you might want to use that.\nfrom lxml.html import parse\ndoc = parse('http://python.org').getroot()\nfor row in doc.cssselect('table > tr'):\n for cell in row.cssselect('td:nth-child(3)'):\n print cell.text_content()\n\nOr, instead of looping:\nrows = [ ... | [
5
] | [] | [] | [
"beautifulsoup",
"html_table",
"python"
] | stackoverflow_0005532307_beautifulsoup_html_table_python.txt |
Q:
trying to understand why a tuple is preferred over a list for a specific python example (from a tutorial)
I'm trying to learn what iterators and generators are in python, going through a tutorial i found online which used this fibonacci iterator as an example. I'm having trouble with the comment on lines 9-11. W... | trying to understand why a tuple is preferred over a list for a specific python example (from a tutorial) | I'm trying to learn what iterators and generators are in python, going through a tutorial i found online which used this fibonacci iterator as an example. I'm having trouble with the comment on lines 9-11. What does it mean that "the old values of self.fn1 and self.nf2 are used in assigning the new value"? I understa... | [
"These is no difference in functionality here between using a tuple versus a list. The point they are trying to make is that it's good to do it in one statement.\nIf you were to split that single line into multiple statements, you'd end up with something like:\noldfn2 = self.fn2\nself.fn2 = self.fn1\nself.fn1 = sel... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005532516_python.txt |
Q:
Problem with serving pictures in Django
I'm trying to create my first site in django and I've run into a problem. I'm trying to serve pictures,but it isn't working correctly. I have it set up in the following way:
In settings.py:
MEDIA_ROOT = 'C:/Users/John/Documents/My Dropbox/Infostuff/filmsite/media/'
MEDIA_U... | Problem with serving pictures in Django | I'm trying to create my first site in django and I've run into a problem. I'm trying to serve pictures,but it isn't working correctly. I have it set up in the following way:
In settings.py:
MEDIA_ROOT = 'C:/Users/John/Documents/My Dropbox/Infostuff/filmsite/media/'
MEDIA_URL = 'localhost:8000/static/'
ADMIN_MEDIA_P... | [
"What version of Django are you using? \nCan you post the generated HTML code? if the URL works when you copy and paste in the browser, it might be an html issue as well.\nHave you looked at this page yet?\nhttp://docs.djangoproject.com/en/dev/howto/static-files/\nUpdate:\nCan you post the model for a? is a.picture... | [
0,
0,
0,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0005532572_django_django_templates_python.txt |
Q:
AttributeError: 'search' object has no attribute 'status_code' in django project
I'm testing a django project using the test sever when it gives me the following exception
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.6/django/core/servers/basehttp.py", line 280, in run
self.result = ap... | AttributeError: 'search' object has no attribute 'status_code' in django project | I'm testing a django project using the test sever when it gives me the following exception
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.6/django/core/servers/basehttp.py", line 280, in run
self.result = application(self.environ, self.start_response)
File "/usr/lib/pymodules/python2.6/django... | [
"MusicGrep/musicgrep/views.py is not returning a HttpResponse instance\n",
"There are quite a few problems with your code, but the one that's causing the actual error you quote is that you don't instantiate your FormWizard subclass in your urlconf.\nAs the documentation shows, you need to actually call the search... | [
4,
2
] | [] | [] | [
"attributeerror",
"django",
"python"
] | stackoverflow_0005532546_attributeerror_django_python.txt |
Q:
Execute .jar from Python
I am trying to build a very simple python script to automate minifying/combining some css/js assets.
I am not sure how to properly handle the minification step. I use yui-compressor and usually call the jar directly from the command line.
Assuming the build script is in the same directory ... | Execute .jar from Python | I am trying to build a very simple python script to automate minifying/combining some css/js assets.
I am not sure how to properly handle the minification step. I use yui-compressor and usually call the jar directly from the command line.
Assuming the build script is in the same directory as rhino js.jar and yui-compre... | [
"I have a somewhat similar case, when I want a python program to build up some commands and then run them, with the output going to the user who fired off the script. The code I use is:\nimport subprocess\ndef run(cmd):\n call = [\"/bin/bash\", \"-c\", cmd]\n ret = subprocess.call(call, stdout=None, stderr=None... | [
3,
0
] | [
"Why would you want to do this in Python? For tasks like this, especially Java, you are better off using Apache Ant. Write commands in xml and then ant runs for you. \n"
] | [
-1
] | [
"java",
"os.system",
"python"
] | stackoverflow_0005532481_java_os.system_python.txt |
Q:
How do I easy_install Swampy?
Following the tutorial on python.org I tried to install Swampy in the following ways:
easy_install -f http://www.greenteapress.com/thinkpython/swampy/install.html
easy_install http://www.greenteapress.com/thinkpython/swampy/swampy-2.0.python.zip
easy_install swampy-2.0 (Swampy's fold... | How do I easy_install Swampy? | Following the tutorial on python.org I tried to install Swampy in the following ways:
easy_install -f http://www.greenteapress.com/thinkpython/swampy/install.html
easy_install http://www.greenteapress.com/thinkpython/swampy/swampy-2.0.python.zip
easy_install swampy-2.0 (Swampy's folder was already placed in the site-p... | [
"You may get this if you are running Python 3.x, and swampy is only compatible with Python 2.x. That would explain syntax errors (assuming the version of swampy on PyPI isn't broken for some other reason).\n"
] | [
0
] | [] | [] | [
"easy_install",
"installation",
"python",
"swampy"
] | stackoverflow_0005532634_easy_install_installation_python_swampy.txt |
Q:
How can I scrape an ASP.NET site that does all interaction as postbacks?
Using Python, I built a scraper for an ASP.NET site (specifically a Jenzabar course searching portlet) that would create a new session, load the first search page, then simulate a search by posting back the required fields. However, something... | How can I scrape an ASP.NET site that does all interaction as postbacks? | Using Python, I built a scraper for an ASP.NET site (specifically a Jenzabar course searching portlet) that would create a new session, load the first search page, then simulate a search by posting back the required fields. However, something changed, and I can't figure out what, and now I get HTTP 500 responses to eve... | [
"Without knowing any specifics, my hunch is that you are using a hardcoded session id and the web server's app domain recycled and created new encryption/decryption keys, rendering your hardcoded session id (which was encrypted by the old keys) useless.\n",
"You could try using Firebugs NET tab to monitor all req... | [
2,
0,
0
] | [] | [] | [
"asp.net",
"javascript",
"python",
"screen_scraping"
] | stackoverflow_0005532541_asp.net_javascript_python_screen_scraping.txt |
Q:
Session Variables with Cached Pages in Django
I'm building an app using someone else's API allowing the user to browse content from their site. The user can log into my project with their credentials from this other site in order to "favorite" content from their site.
When they log in, I get a user_token for them... | Session Variables with Cached Pages in Django | I'm building an app using someone else's API allowing the user to browse content from their site. The user can log into my project with their credentials from this other site in order to "favorite" content from their site.
When they log in, I get a user_token for them. To avoid having to create a user file for them, I... | [
"use {% cache %} tag to cache only parts of the page that are user-independent.\n",
"Modify the Vary header and django will generate a new cache key.\nUpdate: I think you should go for the cookie method, as the SessionMiddleware already sets the appropriate Vary headers which is why with Auth, the caching works c... | [
0,
0
] | [] | [] | [
"caching",
"django",
"python",
"session_variables"
] | stackoverflow_0005532651_caching_django_python_session_variables.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.