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:
python read data build association rules
I have two columns in a text file. I read them into Python into two separate lists. What I want to do is count the occurences of each pair and build association rules based on it.
Example:
colA = [a,b,c,d,...]
colB = [c,y,d,e,...]
I came only so far to read the data into ... | python read data build association rules | I have two columns in a text file. I read them into Python into two separate lists. What I want to do is count the occurences of each pair and build association rules based on it.
Example:
colA = [a,b,c,d,...]
colB = [c,y,d,e,...]
I came only so far to read the data into the two lists but what is the best way to coun... | [
"You can use a dictionary to create a mapping:\nmapping = {}\n\nfor key in colA:\n mapping[key] = colB.index(key)\n\nTo count the occurrences, just use .count():\ncolA.count('a')\n\nNote that the mapping will break if colB has two elements with the same name. This is because you're trying to build a bijection betw... | [
0,
0
] | [] | [] | [
"associations",
"python",
"rules"
] | stackoverflow_0008052276_associations_python_rules.txt |
Q:
Import error in the django tutorial
I'm trying to follow the django tutorial and create two tables where the unique key of table1 might appear several times on table2 (which has a different unique key)
CREATE TABLE "apples" (
"id1" integer NOT NULL PRIMARY KEY,
"value1" varchar(400) NOT NULL,
)
;
CREATE TA... | Import error in the django tutorial | I'm trying to follow the django tutorial and create two tables where the unique key of table1 might appear several times on table2 (which has a different unique key)
CREATE TABLE "apples" (
"id1" integer NOT NULL PRIMARY KEY,
"value1" varchar(400) NOT NULL,
)
;
CREATE TABLE "oranges" (
"id2" integer NOT NUL... | [
"If package is the project name and MyApp the app for that project you don't have to import package in your files, you can just:\nfrom MyApp.models import apples, oranges\n\np = apples.objects.get(id=1)\n...\n\nThis is an error too:\nfrom MyApp import models\nfrom MyApp import apples, oranges // ImportError\n\nappl... | [
3
] | [] | [] | [
"django",
"import",
"python"
] | stackoverflow_0008052151_django_import_python.txt |
Q:
wxPython: scope of menu key shortcuts and dynamic disabling
I'm using Python 2.7.2 and wxPython 2.8.12.1 on Arch Linux x86_64.
I'd like to make the following example work this way:
* when left TextCtrl (text_A) has focus, by pressing Shift+A it should execute do_A(), and by pressing Shift+B it should write B in th... | wxPython: scope of menu key shortcuts and dynamic disabling | I'm using Python 2.7.2 and wxPython 2.8.12.1 on Arch Linux x86_64.
I'd like to make the following example work this way:
* when left TextCtrl (text_A) has focus, by pressing Shift+A it should execute do_A(), and by pressing Shift+B it should write B in the text area; also, menu.foo.bar_B should be disabled (and menu.fo... | [
"I wrote up an article about menus a few years ago: http://www.blog.pythonlibrary.org/2008/07/02/wxpython-working-with-menus-toolbars-and-accelerators/\nIt talks about disabling menus in there. There's also an example in the wxPython demo package about this. I think you have to bind the menu events to the frame obj... | [
1
] | [] | [] | [
"keyboard_shortcuts",
"menu",
"python",
"wxpython"
] | stackoverflow_0008050375_keyboard_shortcuts_menu_python_wxpython.txt |
Q:
exponential moving sum in numpy / scipy?
I am looking for a function to calculate exponential moving sum in numpy or scipy. I want to avoid using python loops because they are really slow.
to be specific, I have two series A[] and T[]. T[i] is the timestamp of value A[i]. I define a half-decay period tau. For a g... | exponential moving sum in numpy / scipy? | I am looking for a function to calculate exponential moving sum in numpy or scipy. I want to avoid using python loops because they are really slow.
to be specific, I have two series A[] and T[]. T[i] is the timestamp of value A[i]. I define a half-decay period tau. For a given time t, the exponential moving sum is the... | [
"Take a look at numpy.convolve. The exponential moving sum is a convolution. \n",
"You can try to improve python loops by doing good \"practices\" (like avoiding dots).\nMaybe you can code you function in C (into a \"numpy library\") and call it from python.\n"
] | [
7,
0
] | [] | [] | [
"numpy",
"python",
"scipy",
"vectorization"
] | stackoverflow_0008052582_numpy_python_scipy_vectorization.txt |
Q:
Creating a Python webserver - layout and setup
am I going about this in the correct way? Ive never done anything like this before, so im not 100% sure on what I am doing. The code so far gets html and css files and that works fine, but images wont load, and will I have to create a new "if" for every different file... | Creating a Python webserver - layout and setup | am I going about this in the correct way? Ive never done anything like this before, so im not 100% sure on what I am doing. The code so far gets html and css files and that works fine, but images wont load, and will I have to create a new "if" for every different file type? or am I doing this a silly way...here is what... | [
"You are on the right track with it, though your ifs are very redundant. I suggest you refactor the code to check for type using a loop and a dict:\nmime = {\"html\":\"text/html\", \"css\":\"text/css\", \"png\":\"image/png\"}\nif RequestedFileType in mime.keys():\n self.send_response(200)\n self.send_header('... | [
4,
1
] | [] | [] | [
"html",
"http",
"http_headers",
"python",
"webserver"
] | stackoverflow_0008051506_html_http_http_headers_python_webserver.txt |
Q:
Handling errors in python
I'm writing a small parser class for a personal project. The class will essentially parse popular playlist files and return useful information.
Since the class will interact with files, I'm not sure about the best way to handle errors. I'm a Linux guy and generally do things in errno fash... | Handling errors in python | I'm writing a small parser class for a personal project. The class will essentially parse popular playlist files and return useful information.
Since the class will interact with files, I'm not sure about the best way to handle errors. I'm a Linux guy and generally do things in errno fashion but I'm wondering that whet... | [
"You want to use exceptions. And if you are using python 2.7, you want to use the with statement. \nThere is a good tutorial in the standard python documentation , but there are tons of other recources: wikibooks, dive into python, articles in blogs.\n"
] | [
1
] | [] | [] | [
"error_handling",
"file_io",
"python"
] | stackoverflow_0008051155_error_handling_file_io_python.txt |
Q:
Does this combinator have a name?
This function f accepts an argument list and returns another callable with the same argument list, so that other functions can be applied to it.
from operator import add, mul
def f(*a, **kw):
return lambda g: g(*a, **kw)
map(f(3, 10), (add, mul)) # -> [13, 30]
What do you ... | Does this combinator have a name? | This function f accepts an argument list and returns another callable with the same argument list, so that other functions can be applied to it.
from operator import add, mul
def f(*a, **kw):
return lambda g: g(*a, **kw)
map(f(3, 10), (add, mul)) # -> [13, 30]
What do you call f? Is this a combinator of some ki... | [
"The combinator is a curried form of apply. Compared to the (deprecated) built-in function apply, f reverses the order of the arguments to be more useful, providing what looks like a dual to the functools.partial function.\n",
"It is quite closely related to partial, but not the same.\npartial takes a function an... | [
4,
0
] | [] | [] | [
"combinators",
"function",
"python"
] | stackoverflow_0008052958_combinators_function_python.txt |
Q:
Why is putting the module level code into a function and then calling the function is faster in Python?
In Alex Martelli's response to Making a Python script Object-Oriented, he mentions that putting module level code into a function and then calling the function is faster in Python. Can someone explain why and w... | Why is putting the module level code into a function and then calling the function is faster in Python? | In Alex Martelli's response to Making a Python script Object-Oriented, he mentions that putting module level code into a function and then calling the function is faster in Python. Can someone explain why and whether it's true for all implementations of Python?
| [
"This is mostly due to variable look-up. Looking up a variable in the global scope requires a dictionary look-up. In contrast, the compiler determines local names statically and references them by index, so no dictionary look up is required.\nNote that in Python 2.x the presence of an exec statement inside a func... | [
8
] | [] | [] | [
"function",
"module",
"optimization",
"python"
] | stackoverflow_0008053608_function_module_optimization_python.txt |
Q:
Python appending to file
while True:
item = str(raw_input('Please enter the name of your item: '))
f = open('sample.txt', 'a')
f.write(item + '\n')
f.close()
My goal is to get this to keep adding items to a text document, sample.txt. However, each time I run the program, the old data that was appe... | Python appending to file | while True:
item = str(raw_input('Please enter the name of your item: '))
f = open('sample.txt', 'a')
f.write(item + '\n')
f.close()
My goal is to get this to keep adding items to a text document, sample.txt. However, each time I run the program, the old data that was appended is written over... How to... | [
"with open('sample.txt', 'a') as f:\n while True:\n item = raw_input('Please enter the name of your item: ')\n if item == '':\n break\n f.write(item + '\\n')\n\nKey points:\n\nWrite the item to the file, not the string 'item'\nClose the file outside the while loop\nProvide a 'sent... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0008053834_python.txt |
Q:
Can I define a scope anywhere in Python?
Sometimes I find that I have to use functions with long names such as os.path.abspath and os.path.dirname a lot in just a few lines of code. I don't think it's worth littering the global namespace with such functions, but it would be incredibly helpful to be able to define ... | Can I define a scope anywhere in Python? | Sometimes I find that I have to use functions with long names such as os.path.abspath and os.path.dirname a lot in just a few lines of code. I don't think it's worth littering the global namespace with such functions, but it would be incredibly helpful to be able to define a scope around the lines where I need those fu... | [
"Python doesn't have a temporary namespace tool like let in Lisp or Scheme.\nThe usual technique in Python is to put names in the current namespace and then take them out when you're done with them. This technique is used heavily in the standard library:\nabspath = os.path.abspath\ndirname = os.path.dirname\n# 15 ... | [
20,
5,
2,
1,
0,
0
] | [
"In general, typing is not the hard part of writing software, but if you insist:\nclass LocalNamespace(object):\n def __enter__(self, *args, **kwargs):\n pass\n def __exit__(self, *args, **kwargs):\n pass\n with LocalNamespace() as foo:\n abspath = os.path.abspath\n dirname = os.path.di... | [
-3
] | [
"python",
"scope"
] | stackoverflow_0008046142_python_scope.txt |
Q:
Running `chmod` after installing a package using `setup.py`
Let's assume I have a package which calls an executable file somewhere in the code (for example a third-party c/java-program). Let's further assume, the application is small/trivial enough to bundle with the package. For example a single executable file (... | Running `chmod` after installing a package using `setup.py` | Let's assume I have a package which calls an executable file somewhere in the code (for example a third-party c/java-program). Let's further assume, the application is small/trivial enough to bundle with the package. For example a single executable file (cfoo).
I could go ahead, and put the files into the following str... | [
"I'm promoting my comment to an answer:\nIf you install it using the scripts keyword, it will get the correct mode (and get installed in an appropriate bin/ directory).\n\nHow would you execute something on files contained inside a package after install?\n\nThis question would appear to address the same situation, ... | [
2
] | [] | [] | [
"distribute",
"distutils",
"python",
"setup.py",
"virtualenv"
] | stackoverflow_0008037205_distribute_distutils_python_setup.py_virtualenv.txt |
Q:
how to use ManytoManyField in djangorestframework
i'm using djangorestframework. the models one meeting could have many participates.
So i tried to use ManytoManyField of django:
class Meeting(models.Model):
name=models.CharField(max_length=100)
participates=models.ManyToManyField(Person)
by python manag... | how to use ManytoManyField in djangorestframework | i'm using djangorestframework. the models one meeting could have many participates.
So i tried to use ManytoManyField of django:
class Meeting(models.Model):
name=models.CharField(max_length=100)
participates=models.ManyToManyField(Person)
by python manager.py sqlall XXX the DB tables are:
CREATE TABLE "OA_me... | [
"see the docs on manytomany fields. You need to create the meeting and person objects separately first, and then do meeting.partcipates.add(person)\n(btw, i think the word you are looking for is participANts)\n"
] | [
3
] | [] | [] | [
"django",
"django_rest_framework",
"manytomanyfield",
"python"
] | stackoverflow_0008052478_django_django_rest_framework_manytomanyfield_python.txt |
Q:
How do I use my standard python path when running python scripts from xcode macros
I'm trying to run Python scripts using Xcode's User Scripts menu.
The issue I'm having is that my usual os.sys.path (taken from ~/.profile) does not seem to be imported when running scripts from XCode the way it is when running them... | How do I use my standard python path when running python scripts from xcode macros | I'm trying to run Python scripts using Xcode's User Scripts menu.
The issue I'm having is that my usual os.sys.path (taken from ~/.profile) does not seem to be imported when running scripts from XCode the way it is when running them at the Terminal (or with IPython). All I get is the default path, which means I can't d... | [
"On the mac, environment variables in your .profile aren't visible to applications outside of the terminal. \nIf you want an environment variable (like PATH, PYTHONPATH, etc) to be available to xcode apps, you should add it to a new plist file that you create at ~/.MacOSX/environment.plist.\nSee the EnvironmentVars... | [
4,
1,
1,
1,
0,
0
] | [] | [] | [
"macos",
"path",
"python",
"xcode"
] | stackoverflow_0000364655_macos_path_python_xcode.txt |
Q:
Python print server
I'm trying to find a solution to create a print server that Windows users can print to and format what they print to XML.
I found this python script: http://newcenturycomputers.net/projects/rawprintserver.html (download on right hand side; vertically). Upon installing and testing it out, it see... | Python print server | I'm trying to find a solution to create a print server that Windows users can print to and format what they print to XML.
I found this python script: http://newcenturycomputers.net/projects/rawprintserver.html (download on right hand side; vertically). Upon installing and testing it out, it seems to be getting the prin... | [
"the spooler.py file contains this snippet of code:\nclass printer(base_printer):\n def sendjob(self, fp, title = None):\n # title is irrelevant here\n out = os.popen(\"lpr -P'%s' >/dev/null 2>&1\" \\\n % self.printer_name, \"wb\")\n blk = fp.read(8192)\n while blk:\n ... | [
0
] | [] | [] | [
"printing",
"python"
] | stackoverflow_0008054312_printing_python.txt |
Q:
scipy -- how to insert an array of zeros into another array with different dimensions
If i have an array:
myzeros=scipy.zeros((c*pos,c*pos)) , c=0.1 , pos=100
and an array:
grid=scipy.ones((pos,pos))
How can i insert the zeros into the grid in random positions? The problem is with the dimensions.
I know that i... | scipy -- how to insert an array of zeros into another array with different dimensions | If i have an array:
myzeros=scipy.zeros((c*pos,c*pos)) , c=0.1 , pos=100
and an array:
grid=scipy.ones((pos,pos))
How can i insert the zeros into the grid in random positions? The problem is with the dimensions.
I know that in 1d you can do:
myzeros=sc.zeros(c*pos) # array full of (zeros)
grid=sc.ones(pos) ... | [
"There are several ways, but the easiest seems to be to first convert the 2D grid into a 1D grid and proceed as in the 1D case, then convert back to 2D:\nc = 0.1\npos = 100\nmyzeros=scipy.zeros((c*pos,c*pos))\nmyzeros1D = myzeros.ravel()\ngrid=scipy.ones((pos,pos))\ngrid1D = grid.ravel()\ndist=sc.random.permutation... | [
3
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0008053350_python_scipy.txt |
Q:
For regex, r'[!-\.&]' what does it mean?
Is it !-\ (characters from 33=ord('!') to 92=ord('\')
and '.' and '&' in a set?
I think my interpretation is incorrect based on my test.
But python reference doesn't say anything wrong with my interpretation.
http://docs.python.org/library/re.html
A:
In short, r'[!-\.&]' ... | For regex, r'[!-\.&]' what does it mean? | Is it !-\ (characters from 33=ord('!') to 92=ord('\')
and '.' and '&' in a set?
I think my interpretation is incorrect based on my test.
But python reference doesn't say anything wrong with my interpretation.
http://docs.python.org/library/re.html
| [
"In short, r'[!-\\.&]' is just a complicated form of writing r'[!-.]'.\nIt matches all characters with ord between 33 = ord('!') and 46 = ord('.'), i.e. any of the following:\n!\"#$%&\\'()*+,-.\n\nThe escaping backslash before . is ignored in character classes; it is unnecessary (. matching all characters in a char... | [
4,
2,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008054108_python_regex.txt |
Q:
sqlite attribute execute is read-only
I am using sqlite to create and connect to a sqlite db foo.db
When I try to do an insert into the DB. I get the following AttributeError
AttributeError: 'sqlite3.Cursor' object attribute 'execute' is read-only
I can't seem to find any information on this error. Does anyone ha... | sqlite attribute execute is read-only | I am using sqlite to create and connect to a sqlite db foo.db
When I try to do an insert into the DB. I get the following AttributeError
AttributeError: 'sqlite3.Cursor' object attribute 'execute' is read-only
I can't seem to find any information on this error. Does anyone have any idea what this exception means?
I am... | [
"You're trying to modify an attribute of the cursor. You want to call a method of the cursor.\nIt should be\n cur.execute('insert into user_reg (username,pwdhash,email,initial_date)\\\n values (?,?,?,?)',\n [username,\n pwdhash,\n emai... | [
5,
1
] | [] | [] | [
"exception",
"python",
"sqlite"
] | stackoverflow_0008054582_exception_python_sqlite.txt |
Q:
Error 252 : b"2.1.5 Send some mail, I'll try my best f18sm1267047wiv.14"
Hi I've written a Python script to send a simple message. The script works with my university email address. However, with gmail there seems to be a problem. I've tried using both my email and just login as a login name - same result. The err... | Error 252 : b"2.1.5 Send some mail, I'll try my best f18sm1267047wiv.14" | Hi I've written a Python script to send a simple message. The script works with my university email address. However, with gmail there seems to be a problem. I've tried using both my email and just login as a login name - same result. The error I get is:
Error 252 : b"2.1.5 Send some mail, I'll try my best f18sm1267047... | [
"It's pretty straightforward. Nobody supports VRFY because it's such an aid to spam. Pull out that check and it should work OK.\n"
] | [
0
] | [] | [] | [
"email",
"gmail",
"python",
"smtplib"
] | stackoverflow_0008054711_email_gmail_python_smtplib.txt |
Q:
How to play a simple song using PyQt's Phonon?
I'm trying to play a single mp3 file on my software when a button is pressed.
Here's how i did it:
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), playsong)
and the function:
def playsong():
m_media = Phonon.MediaObj... | How to play a simple song using PyQt's Phonon? | I'm trying to play a single mp3 file on my software when a button is pressed.
Here's how i did it:
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), playsong)
and the function:
def playsong():
m_media = Phonon.MediaObject()
m_media.setCurrentSource(Phonon.MediaS... | [
"I use phonon on pyqt and my code has a few more lines:\noutput = Phonon.AudioOutput(Phonon.MusicCategory)\nm_media = Phonon.MediaObject()\nPhonon.createPath(m_media, output)\nm_media.setCurrentSource(Phonon.MediaSource(\"files/song.mp3\"))\nm_media.play()\n\nBut honestly, I've found out that phonon is not able to ... | [
5,
4
] | [] | [] | [
"phonon",
"playback",
"pyqt",
"python",
"qt"
] | stackoverflow_0008050050_phonon_playback_pyqt_python_qt.txt |
Q:
How to set a __str__ method for all ctype Structure classes?
[Since asking this question, I've found: http://www.cs.unc.edu/~gb/blog/2007/02/11/ctypes-tricks/ which gives a good answer.]
I just wrote a __str__ method for a ctype-generated Structure class 'foo' thus:
def foo_to_str(self):
s = []
for i in foo._f... | How to set a __str__ method for all ctype Structure classes? | [Since asking this question, I've found: http://www.cs.unc.edu/~gb/blog/2007/02/11/ctypes-tricks/ which gives a good answer.]
I just wrote a __str__ method for a ctype-generated Structure class 'foo' thus:
def foo_to_str(self):
s = []
for i in foo._fields_:
s.append('{}: {}'.format(i[0], foo.__getattribute__(se... | [
"Unfortunately there is no such way. Attempting to modify the Structure class itself results in\nTypeError: can't set attributes of built-in/extension type '_ctypes.Structure'\n\nThe closest you can get is a wrapper class that you apply yourself to each return Structure you care about which delegates non overridde... | [
1
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0004642774_ctypes_python.txt |
Q:
change (eg) 8 to 08...python
I am reading data from a csv file, and there are date elements in it, but there is an inconsistency in the dates.
For example: sometimes the date element is like 1/1/2011 and sometimes it is like 01/01/2011
Since I am plotting this data later.. this causes a great deal of noise in my p... | change (eg) 8 to 08...python | I am reading data from a csv file, and there are date elements in it, but there is an inconsistency in the dates.
For example: sometimes the date element is like 1/1/2011 and sometimes it is like 01/01/2011
Since I am plotting this data later.. this causes a great deal of noise in my plots. The following is my date cla... | [
"You definitely want to be using datetime. Here's some code that will get a datetime from either string type:\nfrom datetime import datetime\n\ndef strToDatetime(dateStr):\n return datetime.strptime(dateStr, \"%d/%m/%Y\")\n\nThen, you can print a datetime out in the format you want with:\nstrToDatetime(\"1/3/20... | [
7
] | [] | [] | [
"algorithm",
"date",
"file",
"python"
] | stackoverflow_0008055185_algorithm_date_file_python.txt |
Q:
How to manage a 2D Fourier Transform(FFT) on a 3D numpy masked array?
I am having problems with doing 2D Fast Fourier Transforms on a 3D array. They are of a mathematical nature and of an 'understanding python/numpy' nature.
EDIT: For clarification, the core questions are:
How does numpy.fft deal with masked arra... | How to manage a 2D Fourier Transform(FFT) on a 3D numpy masked array? | I am having problems with doing 2D Fast Fourier Transforms on a 3D array. They are of a mathematical nature and of an 'understanding python/numpy' nature.
EDIT: For clarification, the core questions are:
How does numpy.fft deal with masked arrays?
Can I average over an axis and then do an fft and get the same result a... | [
"After looking at the documentation briefly, I think numpy.fft may just ignore the mask. I would try using the ma.filled() function to put some other value in all the masked entries.\nSomething like this (taken from your example code):\nft_type_1 = np.log(np.abs(np.fft.fft2(ma.mean(carbon_flux.filled(cflux_fill_val... | [
5
] | [] | [] | [
"fft",
"math",
"numpy",
"python"
] | stackoverflow_0008052721_fft_math_numpy_python.txt |
Q:
Good library for encoding videos in a dynamic language?
I'm looking for an effective library for encoding videos. I would prefer something in one of the Ruby/Python ilk type languages, but I'd use libraries in C or PHP that were good. Essentially, I'm looking for something that wraps ffmpeg, and would allow me to ... | Good library for encoding videos in a dynamic language? | I'm looking for an effective library for encoding videos. I would prefer something in one of the Ruby/Python ilk type languages, but I'd use libraries in C or PHP that were good. Essentially, I'm looking for something that wraps ffmpeg, and would allow me to convert H.264 .mp4's into .theora.ogv, .webm, and (this would... | [
"For Python there is PyMedia and pyffmpeg.\nIf you need a raw usage example, see this.\n"
] | [
9
] | [] | [] | [
"ffmpeg",
"python",
"ruby",
"video",
"video_encoding"
] | stackoverflow_0008055351_ffmpeg_python_ruby_video_video_encoding.txt |
Q:
Check MI for Python
Is there an application similar to Java's CheckMI for Python?
A:
Python code checkers include PyFlakes, PyLint, PyChecker, and others.
| Check MI for Python | Is there an application similar to Java's CheckMI for Python?
| [
"Python code checkers include PyFlakes, PyLint, PyChecker, and others.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004976345_python.txt |
Q:
Reference where a python script is located if being run from another location
I'm trying to run a python script from a different location than where it is located but I need to reference files where the python script is located. I tried the following:
os.chdir(os.getcwd())
But unfortunately that gets the current ... | Reference where a python script is located if being run from another location | I'm trying to run a python script from a different location than where it is located but I need to reference files where the python script is located. I tried the following:
os.chdir(os.getcwd())
But unfortunately that gets the current working dir of where I ran the script from, not where the script currently lives.
T... | [
"You can use\nos.path.dirname(__file__)\n\nto get the directory your script is located in.\n"
] | [
5
] | [] | [] | [
"python",
"working_directory"
] | stackoverflow_0008055681_python_working_directory.txt |
Q:
Weird issue with multiple Python installations on Windows
I have 3 versions of Python (2.5, 2.7, 3.2) installed on a Windows machine, 2.5 being the default one (first in PATH and default for open action).
Now the weird thing appear when I run a python script with filename.py (without specifying the interpreter) or... | Weird issue with multiple Python installations on Windows | I have 3 versions of Python (2.5, 2.7, 3.2) installed on a Windows machine, 2.5 being the default one (first in PATH and default for open action).
Now the weird thing appear when I run a python script with filename.py (without specifying the interpreter) or by clicking the file in Explorer: Python 2.5 is running the sc... | [
"Looking closely, it seems you have various versions of Python in your PATH environment variable.\nThe standard Python installer for Windows doesn't add itself to the PATH; I always do this manually for the version of Python I want to use by default. If you're using a different Python installer (such as ActiveState... | [
1,
1,
0
] | [] | [] | [
"python",
"pythonw"
] | stackoverflow_0008050417_python_pythonw.txt |
Q:
How can you easily select between PyQt or PySide at runtime?
I would like to do something like this in one source file, QT.py:
import sys
import PyQt4
sys.modules["Qt"] = PyQt4
Then import this file in the other source files, and use it like this:
import QT
from Qt.QtCore import *
So I can change from PyQt4 to ... | How can you easily select between PyQt or PySide at runtime? | I would like to do something like this in one source file, QT.py:
import sys
import PyQt4
sys.modules["Qt"] = PyQt4
Then import this file in the other source files, and use it like this:
import QT
from Qt.QtCore import *
So I can change from PyQt4 to PySide in QT.py without touching all the source files (with a poss... | [
"Use an import hook:\ndef set_qt_bindings(package):\n if package not in ('PyQt4', 'PySide'):\n raise ValueError('Unknown Qt Bindings: %s' % package)\n import __builtin__\n __import__ = __builtin__.__import__\n def hook(name, globals=None, locals=None, fromlist=None, level=-1):\n root, sep,... | [
4,
2,
0
] | [] | [] | [
"pyqt",
"pyside",
"python",
"python_module"
] | stackoverflow_0008052386_pyqt_pyside_python_python_module.txt |
Q:
How do I use a default namespace in an lxml xpath query?
I have an xml document in the following format:
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gsa="http://schemas.google.com/gsa/2007">
...
<entry>
<id>https://ip.ad.dr.ess:8000/feeds/diagn... | How do I use a default namespace in an lxml xpath query? | I have an xml document in the following format:
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gsa="http://schemas.google.com/gsa/2007">
...
<entry>
<id>https://ip.ad.dr.ess:8000/feeds/diagnostics/smb://ip.ad.dr.ess/path/to/file</id>
<updated>2011-... | [
"Something like this should work:\nimport lxml.etree as et\n\nns = {\"atom\": \"http://www.w3.org/2005/Atom\"}\ntree = et.fromstring(xml)\nfor node in tree.xpath('//atom:entry', namespaces=ns):\n print node\n\nSee also http://lxml.de/xpathxslt.html#namespaces-and-prefixes.\nAlternative:\nfor node in tree.xpath(\... | [
48,
2
] | [] | [] | [
"lxml",
"python",
"xml",
"xpath"
] | stackoverflow_0008053568_lxml_python_xml_xpath.txt |
Q:
Passing different number of arguments into function
I have a function:
def save(self, text, *index):
file.write(text + '\nResults:\n')
if index == (): index = (range(len(self.drinkList)))
for x in index:
for y in self.drinkList[x].ing:
file.write('min: ' + str(y.min) + ' max: ' + s... | Passing different number of arguments into function | I have a function:
def save(self, text, *index):
file.write(text + '\nResults:\n')
if index == (): index = (range(len(self.drinkList)))
for x in index:
for y in self.drinkList[x].ing:
file.write('min: ' + str(y.min) + ' max: ' + str(y.max) + ' value: ' + str(y.perc) + '\n')
file... | [
"The save(self, text, *index) syntax means that index is itself a\ntuple with all the arguments passed to save after the text one.\nSo, for instance, if you have in your code:\nmyobject.save(\"sample text\", 1, 2, 3)\n\nthen index will be the tuple (1, 2, 3) and the for x in\nindex will correctly loop over values 1... | [
5,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008056139_python.txt |
Q:
How to work with very long strings in Python?
I'm tackling project euler's problem 220 (looked easy, in comparison to some of the
others - thought I'd try a higher numbered one for a change!)
So far I have:
D = "Fa"
def iterate(D,num):
for i in range (0,num):
D = D.replace("a","A")
D = D.repl... | How to work with very long strings in Python? | I'm tackling project euler's problem 220 (looked easy, in comparison to some of the
others - thought I'd try a higher numbered one for a change!)
So far I have:
D = "Fa"
def iterate(D,num):
for i in range (0,num):
D = D.replace("a","A")
D = D.replace("b","B")
D = D.replace("A","aRbFR")
... | [
"The trick is in noticing which patterns emerge as you run the string through each iteration. Try evaluating iterate(D,n) for n between 1 and 10 and see if you can spot them. Also feed the string through a function that calculates the end position and the number of steps, and look for patterns there too.\nYou can t... | [
3,
2,
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0000353152_python.txt |
Q:
How do you recursively call a constructor (__init__) in Python?
My question is probably easiest to see in code. I would like to do the following
class A():
def __init__(self, i):
self.i = i
if i > 0:
self.a = A(i-1)
The idea is that I want to create a class of type A that can recur... | How do you recursively call a constructor (__init__) in Python? | My question is probably easiest to see in code. I would like to do the following
class A():
def __init__(self, i):
self.i = i
if i > 0:
self.a = A(i-1)
The idea is that I want to create a class of type A that can recursively call its own constructor. If I code the above and attempt to c... | [
"Seems to work fine for me when I do a = A(3), why is yours a = Test(3)? I'm guessing that is the issue, if you named your class Test then you should use self.a = Test(i-1).\n>>> class A():\n... def __init__(self, i):\n... self.i = i\n... if i > 0:\n... self.a = A(i-1)\n... \n>>> a ... | [
4,
3
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0008055364_python_recursion.txt |
Q:
Login and accessing wikipedia API using pywikipedia
I am new to python.
I have a task to access wikipedia.
For this I am using the client pywikipedia to access mediawiki api.
WHen I am running login.py it is asking me password. how will I get the password?
has somebody worked on pywikipedia tool?
Any suggestion wh... | Login and accessing wikipedia API using pywikipedia | I am new to python.
I have a task to access wikipedia.
For this I am using the client pywikipedia to access mediawiki api.
WHen I am running login.py it is asking me password. how will I get the password?
has somebody worked on pywikipedia tool?
Any suggestion which client can I use?
| [
"pywikipedia asks for your Wikipedia login. You can register an account on Wikipedia, as well as any other MediaWiki wiki, to assign your edits. When you use pywikipedia, it usually expects you to use an account (instead of editing anonymously).\nNote that some wikis may have special requirements for people to run ... | [
4
] | [] | [] | [
"mediawiki",
"python",
"pywikibot",
"wikipedia_api"
] | stackoverflow_0008056315_mediawiki_python_pywikibot_wikipedia_api.txt |
Q:
django save() method does nothing when called from within a function
I am having some troubles with Django's save() method.
1 / I have this simple Model :
class User (models.Model):
userId = models.IntegerField()
appInstance = models.TextField(null=True, blank=True)
2 / Then in a view, I check if the appI... | django save() method does nothing when called from within a function | I am having some troubles with Django's save() method.
1 / I have this simple Model :
class User (models.Model):
userId = models.IntegerField()
appInstance = models.TextField(null=True, blank=True)
2 / Then in a view, I check if the appInstance does exist and if not I call a function:
if not u.appInstance:
... | [
"Try changing the class name from User to MyUser or something like that, you may be having troubles with the User model defined in Django.\n",
"How about to use autoAddApplication as a private function inside the view?\n def _auto_add_application(session):\n user = get_object_or_404(User, user_id = sess... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008049642_django_django_models_python.txt |
Q:
python get unicode string size
I have a binary file. This file contains an UTF-8 string. Moreover, it is guaranteed that this string is just a single word.
In python, how can I get number of letters in this string?
Let's say, I opened this file and read bytes:
bytes = open("1.dat", "rb").read()
What next have I t... | python get unicode string size | I have a binary file. This file contains an UTF-8 string. Moreover, it is guaranteed that this string is just a single word.
In python, how can I get number of letters in this string?
Let's say, I opened this file and read bytes:
bytes = open("1.dat", "rb").read()
What next have I to do to find out length (in letters,... | [
"unicode_string = bytes.decode(\"utf-8\")\nprint len(unicode_string)\n\n"
] | [
36
] | [] | [] | [
"binaryfiles",
"python",
"utf_8"
] | stackoverflow_0008056496_binaryfiles_python_utf_8.txt |
Q:
Implementing long asynchronous operations in synchronous way
I need to implement function which involves long async operation (send request to external server and periodically check if it is done) which needs to behave like synchronous operation. I'm doing that following way:
start_long_operation()
while True:
i... | Implementing long asynchronous operations in synchronous way | I need to implement function which involves long async operation (send request to external server and periodically check if it is done) which needs to behave like synchronous operation. I'm doing that following way:
start_long_operation()
while True:
if operation_finished():
return
sleep()
I wonder if this i... | [
"Depending on the nature of the asynchronous operation, there are various existing solutions which will allow you to do this more elegantly. For example, if you're waiting for a response from a server, you can use select on the socket to wait for a reply. You can also do this on several sockets at once.\nNote: You ... | [
2,
2
] | [] | [] | [
"asynchronous",
"python"
] | stackoverflow_0008055668_asynchronous_python.txt |
Q:
Python's nonlocal depends on level of hierarchy?
This question is a follow-up on a question about Python variable scope. Additional questions q1, q2 and answers can be found on SO, among even more.
The official Python documentation, and PEP 3104 are supposed to explain the details, but they don't seem fully self-e... | Python's nonlocal depends on level of hierarchy? | This question is a follow-up on a question about Python variable scope. Additional questions q1, q2 and answers can be found on SO, among even more.
The official Python documentation, and PEP 3104 are supposed to explain the details, but they don't seem fully self-explanatory to me.
The topic I'm trying to solve is ref... | [
"global and nonlocal are not meant to be combined. They mean different things:\n\nglobal means the name exists at the module level\nnonlocal means the name exists in an outer lexical function scope\n\nThe reason you are getting the original exception is because you told Python that var is nonlocal (meaning it is i... | [
22,
0
] | [] | [] | [
"closures",
"python",
"python_3.x",
"scope"
] | stackoverflow_0008050502_closures_python_python_3.x_scope.txt |
Q:
Python: efficient file io
What is the most efficient (fastest) way to simultaneously read in two large files and do some processing?
I have two files; a.txt and b.txt, each containing about a hundred thousand corresponding lines. My goal is to read in the two files and then do some processing on each line pair
def... | Python: efficient file io | What is the most efficient (fastest) way to simultaneously read in two large files and do some processing?
I have two files; a.txt and b.txt, each containing about a hundred thousand corresponding lines. My goal is to read in the two files and then do some processing on each line pair
def kernel:
a_file=open('a.txt... | [
"The below code does not accumulate data from the input files in memory, unless the process function does that by itself.\nfrom itertools import izip\n\ndef process(line1, line2):\n # process a line from each input\n\nwith open(file1, 'r') as f1:\n with open(file2, 'r') as f2:\n for a, b in izip(f1, f2):\n ... | [
2,
1,
1,
0
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0008045757_file_io_python.txt |
Q:
A* implementation slow Python
This is my implementation of A* in Python
class Node:
def __init__(self, (x, y), g, h, parent):
self.x = x
self.y = y
self.g = g
self.h = h
self.f = g+h
self.parent = parent
def __eq__(self, other):
if other != None:
... | A* implementation slow Python | This is my implementation of A* in Python
class Node:
def __init__(self, (x, y), g, h, parent):
self.x = x
self.y = y
self.g = g
self.h = h
self.f = g+h
self.parent = parent
def __eq__(self, other):
if other != None:
return self.x == other.x ... | [
"The problem with your implementation is not performance, but rather that it is actually incorrect - it never finishes for the second map!\nThere is an else: continue missing in the part where the node is removed from the closed set - if the node is already part of either set - it must not be added to the open set!... | [
3
] | [] | [] | [
"a_star",
"algorithm",
"python"
] | stackoverflow_0008021305_a_star_algorithm_python.txt |
Q:
Putting Buttons underneath listbox in wxpython?
i am trying to put buttons underneath the listbox however everything i try seems to distort or cause problems. I am hoping anyone can help me.
I want to put 2 buttons underneath the listbox and they should always change position depending on the size of the window (... | Putting Buttons underneath listbox in wxpython? | i am trying to put buttons underneath the listbox however everything i try seems to distort or cause problems. I am hoping anyone can help me.
I want to put 2 buttons underneath the listbox and they should always change position depending on the size of the window (so it doesn't dissapear), basicilly when you resize t... | [
"I'm not sure if this is what you mean or not, but try replacing your \"things1tab\" code with this and see if it works:\nclass things1tab(wx.Panel):\n def newAddImage(self,parent):\n things2_listbox.append('hi');\n self.listBox.Set(things2_listbox)\n self.listBox.SetSelection(len(things2_li... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008056596_python_wxpython.txt |
Q:
Packages "within" modules
I have a growing number of scripts that make up a program I am writing and decided it was time to clean up my source tree and package them up correctly. I'm sure this is a simple question but I can't find out how to do it.
If I have a group of modules, that fit together, but one should be... | Packages "within" modules | I have a growing number of scripts that make up a program I am writing and decided it was time to clean up my source tree and package them up correctly. I'm sure this is a simple question but I can't find out how to do it.
If I have a group of modules, that fit together, but one should be a top-level module and the oth... | [
"Everything in mystuff.py should be placed into mystuff/__init__.py instead.\n",
"You cannot have both a mystuff.py and a mystuff/ package. \nYou have two choices:\n\nput the code in mystuff.py into mystuff/__init__.py\nrename mystuff.py to, for example, mystuff/_stuff.py, and then import that into mystuff/__ini... | [
4,
4
] | [] | [] | [
"module",
"package",
"packaging",
"python",
"python_3.x"
] | stackoverflow_0008047750_module_package_packaging_python_python_3.x.txt |
Q:
__init__.so (instead of __init__.py) masks subpackages
I am writing some code in cython, and I have some "Packages “within” modules". — This is actually a follow up to my question there, and the structure should be the same. The problem is that this is cython, so I'm dealing with .so's not .py's.
Having __init__.... | __init__.so (instead of __init__.py) masks subpackages | I am writing some code in cython, and I have some "Packages “within” modules". — This is actually a follow up to my question there, and the structure should be the same. The problem is that this is cython, so I'm dealing with .so's not .py's.
Having __init__.so works to the extent that,
import mystuff
will work, but... | [
"Have your Cython code be in a different file than __init__.py, and import it into a normal python __init__.py See my answer to your previous question.\n",
"Probably the most simple solution to given problem would be to rename your __init__.so module into something like _native.so. Afterwards you can create __in... | [
2,
2
] | [] | [] | [
"cython",
"module",
"package",
"python",
"python_3.x"
] | stackoverflow_0008055665_cython_module_package_python_python_3.x.txt |
Q:
How do I use DownloadUrl with AJAX and Google App Engine?
The snippet of JavaScript that I am having trouble with looks like this:
var content_value = encodeURI(document.getElementById("chattext").value)
downloadUrl("/getchats", "POST", "content=" + content_value, onChatsReturned);
This code works, but it only po... | How do I use DownloadUrl with AJAX and Google App Engine? | The snippet of JavaScript that I am having trouble with looks like this:
var content_value = encodeURI(document.getElementById("chattext").value)
downloadUrl("/getchats", "POST", "content=" + content_value, onChatsReturned);
This code works, but it only posts the content. How would I have to change this in order to po... | [
"It's quite hard to say anything for certain since I can't know what downloadUrl() function actually does, but here is a solution that at might solve your problem (if it just passes the 3rd argument to the backend).\ndownloadUrl(\"/getchats\", \"POST\", \"content=\" + content_value + \"&description=\" + desciption_... | [
0
] | [] | [] | [
"ajax",
"javascript",
"python"
] | stackoverflow_0008054015_ajax_javascript_python.txt |
Q:
SciPy and NumPy on Mac OS 10.6.8
I have installed Python 2.7.2 on my Mac, and it's working fine. I downloaded the binary for SciPy (http://sourceforge.net/projects/scipy/files/scipy/0.9.0/scipy-0.9.0-py2.7-python.org-macosx10.6.dmg) and NumPy (http://sourceforge.net/projects/numpy/files/NumPy/1.6.1/numpy-1.6.1-py2... | SciPy and NumPy on Mac OS 10.6.8 | I have installed Python 2.7.2 on my Mac, and it's working fine. I downloaded the binary for SciPy (http://sourceforge.net/projects/scipy/files/scipy/0.9.0/scipy-0.9.0-py2.7-python.org-macosx10.6.dmg) and NumPy (http://sourceforge.net/projects/numpy/files/NumPy/1.6.1/numpy-1.6.1-py2.7-python.org-macosx10.6.dmg) respecti... | [
"What you are looking for is numpy.__version__ with two underscores before and after the word version. By my inderstanding, that is the convention for private (or semi-private) variables in python.\n"
] | [
2
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0008057219_numpy_python_scipy.txt |
Q:
Python string append
I have a python method that takes a list of tuples of the form (string, float) and
returns a list of strings that, if combined, would not exceed a certain limit. I am not splitting sentences to preserve the output length, but making sure to stay within a sentence length from the desired output... | Python string append | I have a python method that takes a list of tuples of the form (string, float) and
returns a list of strings that, if combined, would not exceed a certain limit. I am not splitting sentences to preserve the output length, but making sure to stay within a sentence length from the desired output length.
For example:
s: [... | [
"First, I see no reason to defer the breaking out of loop if the maximum length is reached to the next iteration.\nSo, altering your code, I come up with the following code:\ns_tuples = [('Where are you',1),('What about the next day',2),('When is the next event',3)]\n\n\ndef get_words_number(s):\n return len(s.s... | [
2,
1,
1,
1,
0
] | [] | [] | [
"append",
"python",
"string"
] | stackoverflow_0008056648_append_python_string.txt |
Q:
Cannot Overlay over Gstreamer Video with Gtk.Overlay
I have a project with Python, PyGObject (Gtk 3), and GStreamer (0.11)
I have video in my application, so I'm using a Gtk.Overlay widget so I can put other visual elements over the video background. (I need this, trust me.) (Due to the number of widgets, and the ... | Cannot Overlay over Gstreamer Video with Gtk.Overlay | I have a project with Python, PyGObject (Gtk 3), and GStreamer (0.11)
I have video in my application, so I'm using a Gtk.Overlay widget so I can put other visual elements over the video background. (I need this, trust me.) (Due to the number of widgets, and the need for specific positioning and overlaying of these widg... | [
"Answer derived from GNOME Bugzilla Bug 663589, Comments 1-3.\nIt is vital to set the valign and halign of any object added via \"add_overlay\".\nTherefore, the revised code for declaring and adding the Gtk.Fixed object is as below.\nfixed = Gtk.Fixed()\n\n#The following two lines were added.\nfixed.set_halign(Gtk.... | [
1
] | [] | [] | [
"gtk",
"overlay",
"pygobject",
"python"
] | stackoverflow_0008012723_gtk_overlay_pygobject_python.txt |
Q:
Global variable assignment issue
I have a problem with assigning global variable names inside a function. Here's what the function looks like:
def nodegen(slabel, dlabel, sx, xy, dx, dy, num):
for i in range(1, num + 1):
label = slabel + (i - 1)*dlabel
global vars()["n" + str(label)]
vars()["... | Global variable assignment issue | I have a problem with assigning global variable names inside a function. Here's what the function looks like:
def nodegen(slabel, dlabel, sx, xy, dx, dy, num):
for i in range(1, num + 1):
label = slabel + (i - 1)*dlabel
global vars()["n" + str(label)]
vars()["n" + str(label)] = Node(label, (sx + i... | [
"You should treat globals() as a dictionary, like this:\ndef fun(name, value):\n globals()[name] = value\n\nOnce you execute this function it will add or update a global variable named name with value value, e.g. to add variable 'a1' with value 10 call fun('a1', 10).\nvars() without an argument acts the same as ... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008057472_python.txt |
Q:
Finding coordinates of brightest pixel in an image and entering them into an array
I have been asked to write a program to find 'stars' in an image by converting the image file to a numpy array and generating an array of the coordinates of the brightest pixels in the image above a specified threshold (representing... | Finding coordinates of brightest pixel in an image and entering them into an array | I have been asked to write a program to find 'stars' in an image by converting the image file to a numpy array and generating an array of the coordinates of the brightest pixels in the image above a specified threshold (representing background interference).
Once I have located the brightest pixel in the image I must ... | [
"There are a number of different ways to do it with just numpy, etc.\nThere's the \"brute force\" way:\nimport Image\nimport numpy as np\n\nim = Image.open('test.bmp')\ndata = np.array(im)\nthreshold = 200\nwindow = 5 # This is the \"half\" window...\nni, nj = data.shape \nnew_value = 0\n\nfor i, j in zip(*np.where... | [
3,
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0008056567_numpy_python.txt |
Q:
How do numbers work in Python?
So, I open terminal.
> python
> 1 / 3
0
> 1.0 / 3
0.33333333333333331
Could someone tell me what the rules are when it comes to decimals. Does it matter which number when being divided carries the decimal? Is there a best practice?
If I want more decimal points, or less for that mat... | How do numbers work in Python? | So, I open terminal.
> python
> 1 / 3
0
> 1.0 / 3
0.33333333333333331
Could someone tell me what the rules are when it comes to decimals. Does it matter which number when being divided carries the decimal? Is there a best practice?
If I want more decimal points, or less for that matter, do I need to use a function?
| [
"The division in Python < 3.0 works like in many different programming languages and the output is an integer:\n>>> 3 / 2\n1\n\nIf you use float for any of the parts, the output will be a float also:\n>>> 3.0 / 2\n1.5\n>>> 3 / 2.0\n1.5\n\nBut there is a solution, if you want to do division more precisely without th... | [
10,
4,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008057605_python.txt |
Q:
Paramiko: Piping blocks forever on read
I have a problem with getting piping to work with paramiko.
This works:
ssh = paramiko.SSHClient()
[...]
stdin, stdout, stderr = ssh.exec_command("find /tmp")
stdout.read()
This does not work (blocks forever on stdout.read()):
[...]
stdin, stdout, stderr = ssh.exec_command(... | Paramiko: Piping blocks forever on read | I have a problem with getting piping to work with paramiko.
This works:
ssh = paramiko.SSHClient()
[...]
stdin, stdout, stderr = ssh.exec_command("find /tmp")
stdout.read()
This does not work (blocks forever on stdout.read()):
[...]
stdin, stdout, stderr = ssh.exec_command("bash -")
stdin.write("find /tmp\n")
stdin.cl... | [
"With some investigation, it appears that stdin.close() does not actually end the bash session. To do that, you could use the bash command exit (stdin.write('exit\\n')) or dig into the paramiko Channel object underneath the stdin object:\nstdin.channel.shutdown_write()\n\nIf you'd like the bash session to continue... | [
14
] | [] | [] | [
"paramiko",
"python",
"ssh"
] | stackoverflow_0008052840_paramiko_python_ssh.txt |
Q:
Getting a GAE datastore single entity, which is more efficient
Which is more CPU efficient, 1, 2 or 3?
key = something.key()
id = something.key().id()
1) db.GqlQuery("select.....").fetch(1)[0]
2) db.get(key)
3) get_by_id(id)
A:
Option 1 is less efficient, because it requires a query. Incidentally, note that if ... | Getting a GAE datastore single entity, which is more efficient | Which is more CPU efficient, 1, 2 or 3?
key = something.key()
id = something.key().id()
1) db.GqlQuery("select.....").fetch(1)[0]
2) db.get(key)
3) get_by_id(id)
| [
"Option 1 is less efficient, because it requires a query. Incidentally, note that if you want exactly one result, you can call get() on the Query, which will return the first result, or None if there are none.\n2 and 3 are identical; get_by_id is just syntactic sugar for constructing a key and fetching it with get.... | [
5
] | [] | [] | [
"datastore",
"google_app_engine",
"python"
] | stackoverflow_0008057740_datastore_google_app_engine_python.txt |
Q:
How to expand a wx.StaticBox horizontally?
I am having troubles expanding a StaticBox.
Here is the code i am using:
self.images_area = wx.StaticBox(self, -1, '')
self.sizerBox = wx.BoxSizer(wx.HORIZONTAL)
self.sizerBox.Add(self.images_area, 0, wx.EXPAND|wx.ALL, 10)
self.SetSizer(self.sizerBox)
It appears to be wo... | How to expand a wx.StaticBox horizontally? | I am having troubles expanding a StaticBox.
Here is the code i am using:
self.images_area = wx.StaticBox(self, -1, '')
self.sizerBox = wx.BoxSizer(wx.HORIZONTAL)
self.sizerBox.Add(self.images_area, 0, wx.EXPAND|wx.ALL, 10)
self.SetSizer(self.sizerBox)
It appears to be working vertically however it does not expand hori... | [
"use\nself.sizerBox.Add(self.images_area, 1, wx.EXPAND|wx.ALL, 10)\n\nYou have some indications in the wxPyWiki (point 8) of how EXPAND and the proportion parameters work to give the behavior of your widget. \n"
] | [
0
] | [] | [] | [
"boxsizer",
"python",
"wxpython"
] | stackoverflow_0008058293_boxsizer_python_wxpython.txt |
Q:
Free Python programming environement with autocompletion
I've looked at most of the IDE's out there. I've set up vim to use autocompletion and I'm using it right now. However, I can't seem to get it to work like Visual Studio with .NET. Autocompletion seems to work only in certain cases and it only shows methods a... | Free Python programming environement with autocompletion | I've looked at most of the IDE's out there. I've set up vim to use autocompletion and I'm using it right now. However, I can't seem to get it to work like Visual Studio with .NET. Autocompletion seems to work only in certain cases and it only shows methods and not what parameters they take. It's pretty much unusable to... | [
"You won't get the kind of autocompletion in a dynamic language like Python that you get in more explicitly typed languages. Consider:\n def MyFunction(MyArg):\n MyArg.\n\nWhen you type the \".\" in MyArg., you expect the editor to provide a list of methods with arguments. That can't happen in Python because... | [
6,
3,
3
] | [] | [] | [
"autocomplete",
"ide",
"python",
"visual_studio"
] | stackoverflow_0008058016_autocomplete_ide_python_visual_studio.txt |
Q:
Why is this displaying None?
def characterLine(firstChar,secondChar,phrase):
'\n' + ((str(firstChar)+str(secondChar))*(len(phrase)/2)+len(phrase)%2* firstChar)
So the second part of the code will display but when I try to concatenate it with a line skip, it displays "None."
Can someone explain to me as to wh... | Why is this displaying None? | def characterLine(firstChar,secondChar,phrase):
'\n' + ((str(firstChar)+str(secondChar))*(len(phrase)/2)+len(phrase)%2* firstChar)
So the second part of the code will display but when I try to concatenate it with a line skip, it displays "None."
Can someone explain to me as to why this is happening?
| [
"if you are trying to print the return value of characterLine(..), i.e.\nprint characterLine(...)\n\nthis will print None because you are not using the return keyword in front of your expression. Setting\ndef characterLine(firstChar,secondChar,phrase):\n return '\\n' + ((str(firstChar)+str(secondChar))*(len(phra... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0008058019_python.txt |
Q:
Yaml file addressing in GAE using Python
Here is the file structure :
--src
-----\app.yaml
-----\bl
-----\bl\calc.html
-----\calc.py
-----\Main.py
I want to get to this address "localhost/bl/calc.html" and here is my yaml file:
- url: /bl
static_dir: bl
- url: /bl/.*
script: calc.py
- url: /.*
... | Yaml file addressing in GAE using Python | Here is the file structure :
--src
-----\app.yaml
-----\bl
-----\bl\calc.html
-----\calc.py
-----\Main.py
I want to get to this address "localhost/bl/calc.html" and here is my yaml file:
- url: /bl
static_dir: bl
- url: /bl/.*
script: calc.py
- url: /.*
script: Main.py
In the Main.py I have this... | [
"Directives in app.yaml are evaluated in order, top to bottom. Because you have a static_dir directive for /bl/ before the script handlers for /bl/ and .*, any requests for that path will be satisfied by the static directory, not the script. Decide which you want - static or script - and add only that to app.yaml.\... | [
2,
0
] | [] | [] | [
"google_app_engine",
"python",
"yaml"
] | stackoverflow_0008049080_google_app_engine_python_yaml.txt |
Q:
Python - corner coordinates of n-dimensional cube
I'm trying to get the coordinates of an n-dimensional cube from a list of the mins and maxes for each dimension. I'm able to get the corners using for loops but I would like to generalize for any number of dimensions.
So for instance:
mins = [-1,-2,-3]
maxes = [1,2... | Python - corner coordinates of n-dimensional cube | I'm trying to get the coordinates of an n-dimensional cube from a list of the mins and maxes for each dimension. I'm able to get the corners using for loops but I would like to generalize for any number of dimensions.
So for instance:
mins = [-1,-2,-3]
maxes = [1,2,3]
would give the coordinates:
(-1, -2, -3), (-1, -2,... | [
"You were pretty close, *zip( ... ) is what you were looking for:\n>>> list(itertools.product(*zip([-1,-2,-3],[1,2,3])))\n[(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3), (1, -2, -3), (1, -2, 3), (\n, 2, -3), (1, 2, 3)]\n\n"
] | [
11
] | [] | [] | [
"hypercube",
"python",
"python_itertools"
] | stackoverflow_0008058491_hypercube_python_python_itertools.txt |
Q:
How to prevent 301 code from redirecting website?
I am trying to connect to websites with Python and get the HTTP status codes. As answers on this other question of mine suggest, the reason that HTTP status code for websites such as google.com are 301 or 302 (permanently moved) is that these servers are redirectin... | How to prevent 301 code from redirecting website? | I am trying to connect to websites with Python and get the HTTP status codes. As answers on this other question of mine suggest, the reason that HTTP status code for websites such as google.com are 301 or 302 (permanently moved) is that these servers are redirecting. However, I would like to be able to connect to them ... | [
"I assume what you want is for your code to follow the 301/302s to the end url which returns a 200?\nIf so you could try using urllib, or better still use requests which you can install with pip.\nBoth urllib and more reliably requests should follow 301's and 302's and give you the final page that returns a 200.\nI... | [
2
] | [] | [] | [
"http",
"ironpython",
"pycurl",
"python"
] | stackoverflow_0008057365_http_ironpython_pycurl_python.txt |
Q:
How to add data to mongoDB in python
I am a python noob (working with it for less than a few hours). I'm trying to read in twitter data and store it in a mongo database, but I am getting the following error:
Traceback (most recent call last):
File "twit_test.py", line 8, in on_receive
db.posts.insert(data)
... | How to add data to mongoDB in python | I am a python noob (working with it for less than a few hours). I'm trying to read in twitter data and store it in a mongo database, but I am getting the following error:
Traceback (most recent call last):
File "twit_test.py", line 8, in on_receive
db.posts.insert(data)
File "/Library/Python/2.6/site-packages/... | [
"PyMongo's insert method takes a dictionary, not a string. The error you're seeing is where PyMongo attempts to assign an ObjectId for the new record (since it doesn't yet have one) before sending to the database.\nI think the error is in your on_receive function. Unless pycurl is converting the JSON for you automa... | [
2,
2,
0
] | [] | [] | [
"mongodb",
"python"
] | stackoverflow_0008004720_mongodb_python.txt |
Q:
Is there an easily hackable open-source Tivo media server?
Series 2 and later Tivos have a "Music on [computername]" option under "Music, Photos & Showcases" which lets you play music that's hosted on some other machine. This option seems to appear for each computer on the local network with a compatible server ru... | Is there an easily hackable open-source Tivo media server? | Series 2 and later Tivos have a "Music on [computername]" option under "Music, Photos & Showcases" which lets you play music that's hosted on some other machine. This option seems to appear for each computer on the local network with a compatible server running. For example, a Windows PC running Tivo Desktop can show u... | [
"I've never done this, but there's a package called pyTiVo which claims to serve videos, music, and photos. (Here's a blog post of how someone set it up in an old version of Ubuntu.)\n",
"There is JavaHMO which is GPL. I haven't used it in ages but it should be worth investigating.\nUpdated:\nJust after writing ... | [
1,
1,
1
] | [] | [] | [
"java",
"linux",
"python",
"tivo"
] | stackoverflow_0003925979_java_linux_python_tivo.txt |
Q:
How to add widgets inside a StaticBox, wxPython?
it is possible to add things into a StaticBox, in wxPython?
I know this is a rather simple question however I cannot seem to find anything on Google.
I would like to actually be able to add things into the StaticBox, such as buttons.
A:
Looking at the code from on... | How to add widgets inside a StaticBox, wxPython? | it is possible to add things into a StaticBox, in wxPython?
I know this is a rather simple question however I cannot seem to find anything on Google.
I would like to actually be able to add things into the StaticBox, such as buttons.
| [
"Looking at the code from one of my old projects, it looks like I used a StaticBoxSizer, and added the elements to this sizer.\nQuick test:\napp = wx.App(redirect=False)\nframe = wx.Frame(None)\nstatic_box = wx.StaticBox(frame, label='Label')\nsizer = wx.StaticBoxSizer(static_box, wx.VERTICAL)\n\nfor i in range(5):... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008058432_python_wxpython.txt |
Q:
Why can't my regular expression find the result?
The data is like this:
post date='2008-7' postCount='8' viewCount='24308' questionCount='5' answerCount='76' answeredQuestion='5'
and here is my code for the task:
p1 = re.compile(r"post date")
m1 = p1.search(postline)
if m1:
month = re.search(r'post date="([\... | Why can't my regular expression find the result? | The data is like this:
post date='2008-7' postCount='8' viewCount='24308' questionCount='5' answerCount='76' answeredQuestion='5'
and here is my code for the task:
p1 = re.compile(r"post date")
m1 = p1.search(postline)
if m1:
month = re.search(r'post date="([\d\W]+)"', postline).group(1)
| [
"You're searching for double qoutes \" whereas your example is with single qoutes '.\nre.search(r'post date=\"([\\d\\W]+)\"'\n ^ ^\n\n.\npost date='2008-7' postCount='8' viewCount='24308' questionCount='5' answerCount='76' answeredQuestion='5'\n ^ ^\n\nEdit: The problem is... | [
4,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008058731_python_regex.txt |
Q:
Feed URL from HTML using Python
The RSS feed URL is available a site's meta data (if one available). Is there a way to extract the feed URL(S) of a page using urllib2 or HTMLParser modules? Or is there a better module available?
Thanks.
A:
I prefer lxml. It has a very nice API, and it's XPath support makes this ... | Feed URL from HTML using Python | The RSS feed URL is available a site's meta data (if one available). Is there a way to extract the feed URL(S) of a page using urllib2 or HTMLParser modules? Or is there a better module available?
Thanks.
| [
"I prefer lxml. It has a very nice API, and it's XPath support makes this fairly simple to accomplish:\nimport lxml.html\ndoc = lxml.html.parse(url_to_site)\nfeeds = doc.xpath('//link[@type=\"application/rss+xml\"]/@href') # list feed urls\n\n"
] | [
2
] | [] | [] | [
"html_parsing",
"python",
"urllib2"
] | stackoverflow_0008058777_html_parsing_python_urllib2.txt |
Q:
Native PyGame method for automatically scaling inputs to a surface resolution?
This question is related to this other one.
In my program (which uses pygame to draw objects on the video) I have two representation of my world:
A physical one that I use to make all the calculations involved in the simulation and in ... | Native PyGame method for automatically scaling inputs to a surface resolution? | This question is related to this other one.
In my program (which uses pygame to draw objects on the video) I have two representation of my world:
A physical one that I use to make all the calculations involved in the simulation and in which objects are located on a 1000x1000 metres surface.
A visual one which I use to... | [
"There is no native pygame way to do this.\nYou may be misunderstanding the function of pygame. It is not for drawing vector objects. It is for writing pixels into video surfaces.\nSince you have vector objects, you must define how they will be converted into pixels. Doing this is not a workaround - it's how you ar... | [
1,
1
] | [] | [] | [
"coordinate_systems",
"coordinates",
"drawing",
"pygame",
"python"
] | stackoverflow_0006807459_coordinate_systems_coordinates_drawing_pygame_python.txt |
Q:
Wanted Python to create a UTF-8 File, got an ANSI one. Why?
I have the following function:
def storeTaggedCorpus(corpus, filename):
corpusFile = codecs.open(filename, mode = 'w', encoding = 'utf-8')
for token in corpus:
tagged_token = '/'.join(str for str in token)
tagged_token = tagged_tok... | Wanted Python to create a UTF-8 File, got an ANSI one. Why? | I have the following function:
def storeTaggedCorpus(corpus, filename):
corpusFile = codecs.open(filename, mode = 'w', encoding = 'utf-8')
for token in corpus:
tagged_token = '/'.join(str for str in token)
tagged_token = tagged_token.decode('ISO-8859-1')
tagged_token = tagged_token.encod... | [
"When you open the file with codec.open('w', encoding='utf8'), there is no point in writing byte arrays (str objects) into the file. Instead, write unicode objects, like this:\ncorpusFile = codecs.open(filename, mode = 'w', encoding = 'utf-8')\n# ...\ntagged_token = '\\xdcml\\xe4ut'\ntagged_token = tagged_token.dec... | [
3,
1,
0
] | [] | [] | [
"python",
"python_2.6",
"unicode",
"utf_8",
"windows"
] | stackoverflow_0008058819_python_python_2.6_unicode_utf_8_windows.txt |
Q:
Looking for advice on how to develop applets for Gnome / Ubuntu
I am a linux (mostly ubuntu) user with a reasonable understanding of how the system works (although I am certainly not a linux guru!). In the past I have developed small cross-platform desktop applications in python/GTK and I delivered them to clients... | Looking for advice on how to develop applets for Gnome / Ubuntu | I am a linux (mostly ubuntu) user with a reasonable understanding of how the system works (although I am certainly not a linux guru!). In the past I have developed small cross-platform desktop applications in python/GTK and I delivered them to clients as self-contained filetrees, so that the only dependencies were Pyth... | [
"Well, you list python, so you'll want to have pynotify in your arsenal. It wraps DBus, and gives you a direct api for manipulating the osd-notification system.\n>>> import pynotify\n>>> pynotify.init(\"Lil' Applet\")\nTrue\n>>> note = pynotify.Notification(\n... pynotify.get_app_name(), \n... ... | [
3,
3,
1,
1
] | [] | [] | [
"dbus",
"gnome",
"linux",
"python",
"ubuntu"
] | stackoverflow_0001832150_dbus_gnome_linux_python_ubuntu.txt |
Q:
Python Print statement in a loop, generating prime numbers
Where can I put a print statement to print the final list but still retain the return, and are there any ways you can think of to improve this function. I wrote the function but am unsure as to its relative quality
def buildPrimeList ():
primeList = [... | Python Print statement in a loop, generating prime numbers | Where can I put a print statement to print the final list but still retain the return, and are there any ways you can think of to improve this function. I wrote the function but am unsure as to its relative quality
def buildPrimeList ():
primeList = [1, 2]
possiblePrime = 3
print "To display all prime valu... | [
"It's quite straight-forward to print result of a function:\nprint buildPrimeList()\n\nAlso I've noticed that you do not convert raw_input's result (which is string) to int:\nx = int(raw_input(\"Enter a number higher then 3 \"))\n\n\nAnother way to do the same thing in python might look like:\nfrom itertools impo... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008048581_python.txt |
Q:
Multiple Selenium port localhost Issue
My simple need:
I want to open two IE browsers on two different Selenium ports on localhost
My Setup
My Selenium Server Setup
Selenium server (2.2.0v) running on Win 7 at port 4444 and 4445
My Selenium Client Setup
Selenium Client - Selenium RC on Python 2.7 on same Win 7 whe... | Multiple Selenium port localhost Issue | My simple need:
I want to open two IE browsers on two different Selenium ports on localhost
My Setup
My Selenium Server Setup
Selenium server (2.2.0v) running on Win 7 at port 4444 and 4445
My Selenium Client Setup
Selenium Client - Selenium RC on Python 2.7 on same Win 7 where Selenium server is running
My code that j... | [
"I hate to be the bearer of bad news but this is because Firefox works under profiles but IE is a different beast, though this applies to Selenium Grid it definitely applies to your problem as well: http://svn.openqa.org/fisheye/browse/~raw,r=390/selenium-grid/website/src/main/webapp/faq.html#i_get_some_strange_err... | [
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0008002634_python_selenium.txt |
Q:
problems using cron to run a pymongo script
I'm running a simple python script sending data to a mongodb
#!/usr/bin/env python
import sys
import time
from datetime import datetime
import pymongo
from pymongo import Connection
today = { 'date and time' : datetime.today() }
connection = Connection()
db = connecti... | problems using cron to run a pymongo script | I'm running a simple python script sending data to a mongodb
#!/usr/bin/env python
import sys
import time
from datetime import datetime
import pymongo
from pymongo import Connection
today = { 'date and time' : datetime.today() }
connection = Connection()
db = connection.tests
collection = db.times
collection.insert... | [
"It is likely that the cron environment does not match your user's environment. In cron you can either set the path variable in crontab like\nPATH=$PATH:/usr/bin\n* * * * * /Users/MyUser/XX/YY/ZZ/timetest.py\n\nor you can just explicitly call the python binary on your script\n* * * * * /usr/bin/python /Users/MyUser... | [
1
] | [] | [] | [
"cron",
"crontab",
"mongodb",
"pymongo",
"python"
] | stackoverflow_0007506129_cron_crontab_mongodb_pymongo_python.txt |
Q:
How to document a duck type?
I'm having documentation bloat on me, as anytime I encounter a complex duck-type, I need some way to say "this duck type" but instead get caught in an endless cycle of "your function requires this of this input, but doesn't document it", and then documenting it. This results in bloated... | How to document a duck type? | I'm having documentation bloat on me, as anytime I encounter a complex duck-type, I need some way to say "this duck type" but instead get caught in an endless cycle of "your function requires this of this input, but doesn't document it", and then documenting it. This results in bloated, repetitive documentation, such a... | [
"The idea behind duck typing is that you document that you are expecting a duck, and it is up to other objects to fake being a duck.\nNowhere in the docs does any API specify that it accepts a StringIO object; however, we can use them in most places that expect a \"file-like object\".\nAlso, for the most part, the ... | [
8,
2,
1
] | [] | [] | [
"documentation",
"duck_typing",
"python"
] | stackoverflow_0008059649_documentation_duck_typing_python.txt |
Q:
What is the preferred way to add relations between users in Plone?
I'm making a social networking site powered by Plone and would like to set up relationships between users (friends, followers, etc.).
How can I achieve this in Plone 4?
A:
I'd suggest using annotations and creating multiple trees. For ex.:
import... | What is the preferred way to add relations between users in Plone? | I'm making a social networking site powered by Plone and would like to set up relationships between users (friends, followers, etc.).
How can I achieve this in Plone 4?
| [
"I'd suggest using annotations and creating multiple trees. For ex.:\nimport BTrees\nfrom zope import annotation\n\nFOLLOWERS_KEY = \"my.product.followers\"\nFOLLOWS_KEY = \"my.product.follows\"\nFRIENDS_KEY = \"my.product.friends\"\n\nportal = self.context.portal_url.getPortalObject()\nannotations = annotation.int... | [
4,
0
] | [] | [] | [
"plone",
"python",
"zope"
] | stackoverflow_0008046470_plone_python_zope.txt |
Q:
Programming a GUI Like Steam?
So I've been tinkering with a few different GUI's but I haven't been able to even find a point to begin researching this question:
How do I make a GUI like Steam (Digital distribution app) has? More specifically, I'm interested in how they manage to make their SHIFT+TAB menu pop up in... | Programming a GUI Like Steam? | So I've been tinkering with a few different GUI's but I haven't been able to even find a point to begin researching this question:
How do I make a GUI like Steam (Digital distribution app) has? More specifically, I'm interested in how they manage to make their SHIFT+TAB menu pop up in-game, without disrupting/pausing/e... | [
"The Steam overlay/notification system hooks into games via Direct3D or OpenGL in Windows (depending on the game) from my understanding (as it doesn't work for games that aren't Direct3d/OpenGL like Diablo). \nIt uses the same rendering libraries that the game uses and thus can overlay their menus natively. \nAs fo... | [
2
] | [
"Hmm, that looks very much like they are using Adobe AIR or maybe Flash.\n"
] | [
-2
] | [
"python",
"user_interface"
] | stackoverflow_0008059845_python_user_interface.txt |
Q:
socket.gethostbyname fails
I am trying to read host names from a file line by line and at the same time resolve each dns name to its IP address. I am using this very simple code:
import socket
path = "C:\Domain\domains.txt"
f = open(path, 'r')
for line in f:
print socket.gethostbyname(line)
But I get this ... | socket.gethostbyname fails | I am trying to read host names from a file line by line and at the same time resolve each dns name to its IP address. I am using this very simple code:
import socket
path = "C:\Domain\domains.txt"
f = open(path, 'r')
for line in f:
print socket.gethostbyname(line)
But I get this error:
Traceback (most recent ca... | [
"Read the documentation for gethostbyname:\n\nTranslate a host name to IPv4 address format. The IPv4 address is returned as a string, such as '100.50.200.5'.\n\nAnd the documentation for error 11004 says:\n\nThe requested name is valid and was found in the database, but it does not have the correct associated data ... | [
0
] | [
"Are you sure the line is in right format?\nfor line in f:\n print repr(line)\n print socket.gethostbyname(line)\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0008059942_python.txt |
Q:
Getting login credentials when using webapp
What is an accepted way to get authentication credentials (login and password) when using webapp?
I'm pretty sure that they get submitted and/or interpreted differently than the rest of the information coming through the request and I'm afraid I can't remember where exac... | Getting login credentials when using webapp | What is an accepted way to get authentication credentials (login and password) when using webapp?
I'm pretty sure that they get submitted and/or interpreted differently than the rest of the information coming through the request and I'm afraid I can't remember where exactly I'm supposed to get them from.
FYI: The reque... | [
"If you've got HTTPS enabled, sending them along with the request (usually a POST) is acceptable, and the \"standard\" method of logging in.\nIf you want to get clever, you could hash the password using SHA1 on the client end so that even an sslstrip won't reveal the password in plaintext (though it won't prevent r... | [
2,
1
] | [] | [] | [
"authentication",
"credentials",
"google_app_engine",
"python",
"web_applications"
] | stackoverflow_0008039374_authentication_credentials_google_app_engine_python_web_applications.txt |
Q:
Python/Django - Build list by Sum by day and Week
Hopefully I can explain what I am trying to accomplish. I have no problem achieving my result, but I know that this is probably not the best way to do it.
I have a table with some entries by date. I am trying to take those entries from the current month, and arrang... | Python/Django - Build list by Sum by day and Week | Hopefully I can explain what I am trying to accomplish. I have no problem achieving my result, but I know that this is probably not the best way to do it.
I have a table with some entries by date. I am trying to take those entries from the current month, and arrange them into a list by week, and then sum a value from t... | [
"I think you are probably looking for the defaultdict. A defaultdict is just like a dictionary, except when a KeyError would be thrown with dict, the factory function given upon initialization is used to create an initial value.\nIn your case, you'll need a defaultdict for days nested inside one for weeks. I thin... | [
1
] | [] | [] | [
"dayofweek",
"dictionary",
"django",
"python"
] | stackoverflow_0008060031_dayofweek_dictionary_django_python.txt |
Q:
Python: Algorithm Traverse Tree that expands at each node
I have a dictionary with id and multiple values for each ID which are strings. For each value in that for each Id I make a database query and get set results:
{111: Run, Jump, swim}
{222: Eat, drink}
so for each value lets say run I execute a query and it ... | Python: Algorithm Traverse Tree that expands at each node | I have a dictionary with id and multiple values for each ID which are strings. For each value in that for each Id I make a database query and get set results:
{111: Run, Jump, swim}
{222: Eat, drink}
so for each value lets say run I execute a query and it returns another set of data then pick each value of that set an... | [
"You can look at the categories/subcategories as a tree with N branches at each node (depending how many categories you have). From what I can gather you basically want to generate an in-order list of tree leaves. \nOne simple way of doing it is through generators (using the terminology from your original question)... | [
2,
0
] | [] | [] | [
"algorithm",
"disjoint_sets",
"python"
] | stackoverflow_0008060220_algorithm_disjoint_sets_python.txt |
Q:
How do I test whether a module is imported in Python for Test-Driven Development of a game?
I am about to make a game using python and libtcod roguelike game library.
More to the point, I am using PyMock because I am just starting to learn Test-Driven Development, and I am determined not to cheat. I really want t... | How do I test whether a module is imported in Python for Test-Driven Development of a game? | I am about to make a game using python and libtcod roguelike game library.
More to the point, I am using PyMock because I am just starting to learn Test-Driven Development, and I am determined not to cheat. I really want to get into the habit of doing it properly, and according to TDD I need a failing unit test before... | [
"1) 'your_module' in sys.modules.\nDon't actually use that, though:\n2) \nWhat should your library should do?\nIs it “have a dependency on libcotdpy”? I think not.\nYou've just made a design choice that wasn't test-driven!\nWrite a test that demonstrates how you want to use the library. Don't think about how you're... | [
7,
4,
1
] | [] | [] | [
"python",
"tdd",
"unit_testing"
] | stackoverflow_0008048066_python_tdd_unit_testing.txt |
Q:
In Python, how do I write unit tests that can access private attributes without exposing them?
I am trying to improve how I write my unit test cases for my Python programs. I am noticing in some cases, it would be really helpful to have access to private members to ensure that a method is functioning properly. An ... | In Python, how do I write unit tests that can access private attributes without exposing them? | I am trying to improve how I write my unit test cases for my Python programs. I am noticing in some cases, it would be really helpful to have access to private members to ensure that a method is functioning properly. An example case would be when trying to test a method for proper behavior that has no expected return v... | [
"Nothing is private in Python. If you are using the double underscore prefix on member variables, the name is simply mangled. You can access it by qualifying the name in the form _Class__member. This will access the __member variable in the class Class.\nSee also this question: Why are Python's 'private' methods no... | [
23,
4
] | [] | [] | [
"access_modifiers",
"python",
"tdd",
"testing",
"unit_testing"
] | stackoverflow_0008052814_access_modifiers_python_tdd_testing_unit_testing.txt |
Q:
Storing email into mongodb
I am encountering a really strange bug.
for emailid in item_ids:
resp, data = conn.fetch(emailid, "(RFC822)")
try:
db.emails.insert({'raw': data})
So I am fetching a bunch of data from gmail using oauth2.clients.imap. After fetching the email from gmail, I have decide... | Storing email into mongodb | I am encountering a really strange bug.
for emailid in item_ids:
resp, data = conn.fetch(emailid, "(RFC822)")
try:
db.emails.insert({'raw': data})
So I am fetching a bunch of data from gmail using oauth2.clients.imap. After fetching the email from gmail, I have decided to store it as "raw" first in ... | [
"Turns out you should do this: \noid = db.emails.insert({'raw': bson.binary.Binary(data)})\nSaving in binary ensures that the original content of the data is not changed.\n"
] | [
3
] | [] | [] | [
"mongodb",
"python"
] | stackoverflow_0008047773_mongodb_python.txt |
Q:
python ghostscript Popen cannot find file
import ghostscript
import sys, subprocess,os
output = subprocess.Popen(['gs', '-dSAFER', '-dNOPAUSE', '-dBATCH', '-sDEVICE=tiffg4', '-g6120x7920 ','-r720x720','-sOutputFile=C:\Python25\pdfmining\page_%03d.tif' 'C:\Python25\pdfmining\ae.pdf'])
WindowsError: [Error 2] The s... | python ghostscript Popen cannot find file | import ghostscript
import sys, subprocess,os
output = subprocess.Popen(['gs', '-dSAFER', '-dNOPAUSE', '-dBATCH', '-sDEVICE=tiffg4', '-g6120x7920 ','-r720x720','-sOutputFile=C:\Python25\pdfmining\page_%03d.tif' 'C:\Python25\pdfmining\ae.pdf'])
WindowsError: [Error 2] The system cannot find the file specified,
with a c... | [
"Try the shell=True parameter to Popen. I believe this will involve the shell path for executable programs.\n",
"For windows install ghostscript and set the path in enviornment variables and execute the following command. \ncommand = [\"gswin32c\",\n \"-q\",\n \"-g%dx%d\" % size,\n ... | [
2,
0
] | [] | [] | [
"ghostscript",
"python"
] | stackoverflow_0006330822_ghostscript_python.txt |
Q:
default python on osx lion
Problem is that default command python is used by osx python. That means for example if you install py-pil from macports, osx python won't find this module. after python27 installed with macports, I have command called python-2.7 available. Earlier there was utility called python_select ... | default python on osx lion | Problem is that default command python is used by osx python. That means for example if you install py-pil from macports, osx python won't find this module. after python27 installed with macports, I have command called python-2.7 available. Earlier there was utility called python_select now it's completely gone in a va... | [
"MacPorts removed the python_select functionality, use port select instead. \nSee:\n\nmacports didn't place python_select in /opt/local/bin\nmacports python_select command not found\n\n"
] | [
2
] | [] | [] | [
"macos",
"macports",
"python"
] | stackoverflow_0008060837_macos_macports_python.txt |
Q:
How to Perform a HTTP Post "directly" in Python
I do not know much about the difference between a HTTP Get and a HTTP Post so I am hoping to get some information from those more knowledgeable then me.
I have written the following code:
<form action="https://na.leagueoflegends.com/user/login" method="post">
<i... | How to Perform a HTTP Post "directly" in Python | I do not know much about the difference between a HTTP Get and a HTTP Post so I am hoping to get some information from those more knowledgeable then me.
I have written the following code:
<form action="https://na.leagueoflegends.com/user/login" method="post">
<input name="name" type="text" value="MYACCOUNTLOGINUSE... | [
"The most sophisticated library to use for this purpose is probably requests\n>>> import requests\n>>> response = requests.post(... your args here ...)\n\nCf. the documentation of requests.post.\n",
"import urllib\nimport urllib2\n\nurl = 'https://na.leagueoflegends.com/user/login'\nparams = urllib.urlencode({\n ... | [
2,
1,
1
] | [] | [] | [
"get",
"html",
"post",
"python"
] | stackoverflow_0008061280_get_html_post_python.txt |
Q:
How do I capture this warning message when the query is blocking?
When I do a query with isql I get the following message and the query blocks.
The transaction log in database foo is almost full. Your transaction is being suspended until space is made available in the log.
When I do the same from Python:
cursor... | How do I capture this warning message when the query is blocking? | When I do a query with isql I get the following message and the query blocks.
The transaction log in database foo is almost full. Your transaction is being suspended until space is made available in the log.
When I do the same from Python:
cursor.execute(sql)
The query blocks, but I would like see this message.
I t... | [
"Good question and I'm not sure I can completely answer it. Here are some ideas.\nSybase.py uses logging. Make sure you are using it. To \"bump\" the logging out I would do this:\nimport logging\nlogging.basicConfig(level = logging.INFO,\n format = \"%(asctime)s %(levelname)s [%(filename)s] (%... | [
1
] | [
"Your query may be large which is overflowing the transaction log (e.g. you are inserting large binary files). Or you may not be truncating your transaction logs often enough if that's an option.\nDuring runtime you will want to have an except statement that catches the exception Error.\nSee the Sybase Python docum... | [
-1,
-2
] | [
"python",
"sap_ase"
] | stackoverflow_0007522932_python_sap_ase.txt |
Q:
Return value from Python subprocess
I would like to get the output (print statements) and return status from a python subprocess along with displaying logging info. I am using Python 2.5 on Windows XP. How do I get the return code as well? Here in this extract, I am reading output so that I can redirect it to disp... | Return value from Python subprocess | I would like to get the output (print statements) and return status from a python subprocess along with displaying logging info. I am using Python 2.5 on Windows XP. How do I get the return code as well? Here in this extract, I am reading output so that I can redirect it to display in a wxPython TextCtrl in a separate ... | [
"The returncode gets returned by the poll call, and is also (once poll did not return None) accessible via the returncode attribute. You are already using this in your code, so I'm not sure what your problem with that is.\nWhen you want to update your control while your process is running, use readline instead of r... | [
7
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0008060878_python_subprocess.txt |
Q:
Python lxml the E-Factory
I've been using the lxml "E-Factory" (aka. ElementMaker) for creating xml documents. I'm trying to generate an xml document similar to this:
<url>
<date-added>2011-11-11</date-added>
</url>
However, using the E-factory, I'm not sure how to specify the dash in the 'data-added' eleme... | Python lxml the E-Factory | I've been using the lxml "E-Factory" (aka. ElementMaker) for creating xml documents. I'm trying to generate an xml document similar to this:
<url>
<date-added>2011-11-11</date-added>
</url>
However, using the E-factory, I'm not sure how to specify the dash in the 'data-added' element. It seems to be interpretin... | [
"Explanation: What you put after E. needs to be a valid Python identifier. This includes underscores but not hyphens. E.date-added is compiled \"successfully\" as if it were (E.date) - added but then fails at run time because (in your case) added was not defined.\nAlternatives: \n(1) The E.tag is just a cosmetic tr... | [
9,
7
] | [] | [] | [
"elementtree",
"lxml",
"python",
"xml"
] | stackoverflow_0008061250_elementtree_lxml_python_xml.txt |
Q:
Django login using custom backend
I am working on a store based authentication system using Django, i am trying to make it so that the url is the one that specifies which store the user is trying to log in. Ex
login/store-name
then login the user in to the requested store. My question is, is there a way to do thi... | Django login using custom backend | I am working on a store based authentication system using Django, i am trying to make it so that the url is the one that specifies which store the user is trying to log in. Ex
login/store-name
then login the user in to the requested store. My question is, is there a way to do this using django's built in login form/me... | [
"I think you could do this just in urls.py\nurlpatterns = patterns('',\n url(r'^login/store-name-1/$', login, name=\"login\"),\n url(r'^login/store-name-2/$', login, name=\"login\"),\n url(r'^accounts/logout/$', logout, {'next_page': '/',}, name='logout')\n)\n\nI'm not exactly clear on what you want to do?... | [
1,
1,
1
] | [] | [] | [
"django",
"django_authentication",
"django_login",
"python"
] | stackoverflow_0008057431_django_django_authentication_django_login_python.txt |
Q:
Plotting A Hyperboloid
Teacher in class gave this formula
w = x**2 + y**2 - z**2
and showed its 3d graphic in class seen below. How do I plot this using Matplotlib (minus the intersecting plane)? I guess first a specific value for w needs to be selected, for example 10, otherwise 3d plotting would not be possibl... | Plotting A Hyperboloid | Teacher in class gave this formula
w = x**2 + y**2 - z**2
and showed its 3d graphic in class seen below. How do I plot this using Matplotlib (minus the intersecting plane)? I guess first a specific value for w needs to be selected, for example 10, otherwise 3d plotting would not be possible. Then should I convert to ... | [
"Got it. Found some good stuff here, and following the formulas presented, I have the Python code below.\nhttp://msenux.redwoods.edu/Math4Textbook/Plotting/ParametricSurfaces.pdf\nfrom __future__ import division\n\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfig =... | [
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008062248_matplotlib_python.txt |
Q:
Applying machine learning to a guessing game?
I have a problem with a game I am making. I think I know the solution(or what solution to apply) but not sure how all the ‘pieces’ fit together.
How the game works:
(from How to approach number guessing game(with a twist) algorithm? )
users will be given items with a... | Applying machine learning to a guessing game? | I have a problem with a game I am making. I think I know the solution(or what solution to apply) but not sure how all the ‘pieces’ fit together.
How the game works:
(from How to approach number guessing game(with a twist) algorithm? )
users will be given items with a value(values change every day and the program is a... | [
"Like you've said, this problem can be described with a HMM. You are essentially interested in maintaining a distribution over latent, or hidden, states which would be the true quantities at each time point. However, it seems you are confusing the problem of learning the parameters for a HMM opposed to simply doi... | [
16
] | [] | [] | [
"artificial_intelligence",
"machine_learning",
"python"
] | stackoverflow_0008057936_artificial_intelligence_machine_learning_python.txt |
Q:
Python - Open TXT, Randomize, Save as New File
I've been messing around with randomizing in python for awhile now but for some reason I'm stuck here. Maybe it's just too late at night...
Anyway, I'm looking for a quick an easy method in Python to;
Open TXT File
Randomize Lines
Save as new TXT File
I'm feeling ki... | Python - Open TXT, Randomize, Save as New File | I've been messing around with randomizing in python for awhile now but for some reason I'm stuck here. Maybe it's just too late at night...
Anyway, I'm looking for a quick an easy method in Python to;
Open TXT File
Randomize Lines
Save as new TXT File
I'm feeling kinda dumb here...
Any help is appreciated! Thanks!
| [
"Use random.shuffle to randomize a sequence:\nimport random\n\nwith open('filename', 'rb') as infile:\n lines = infile.readlines()\n\nrandom.shuffle(lines)\n\nwith open('newfilename', 'wb') as outfile:\n outfile.writelines(lines)\n\nEdit: The method of shuffling suggested in the other answer is wrong. See the... | [
6
] | [] | [] | [
"lines",
"python",
"random"
] | stackoverflow_0008062815_lines_python_random.txt |
Q:
how to map float to 32 bit integer in python
From the AR Drone Developer's guide:
The number −0.8 is stored in memory as a 32-
bit word whose value is BF 4CCCCD (16) , according to the IEEE-754 format. This 32-bit word
can be considered as holding the 32-bit integer value −1085485875 (10).
Is there an "easy... | how to map float to 32 bit integer in python | From the AR Drone Developer's guide:
The number −0.8 is stored in memory as a 32-
bit word whose value is BF 4CCCCD (16) , according to the IEEE-754 format. This 32-bit word
can be considered as holding the 32-bit integer value −1085485875 (10).
Is there an "easy way" (built-in functions/existing modules) to do ... | [
"maybe not the best method, but it works.\nimport struct\ns = struct.pack(\"f\", -0.8)\ni = struct.unpack(\"i\", s)\nprint i\n\n"
] | [
6
] | [] | [] | [
"floating_point",
"python"
] | stackoverflow_0008063645_floating_point_python.txt |
Q:
How to access a For variable from a Jinja2 contextfilter
I've developed a custom i18n system in Jinja2 based on the following filter (simplified):
@contextfilter
def render(context, value):
"""
Renders the filtered value as a string template, using the context
and environment of the caller template.
... | How to access a For variable from a Jinja2 contextfilter | I've developed a custom i18n system in Jinja2 based on the following filter (simplified):
@contextfilter
def render(context, value):
"""
Renders the filtered value as a string template, using the context
and environment of the caller template.
"""
mini_template = _environment.from_string(value)
... | [
"Ok, I've fixed it using kwargs (although it's more verbose than its equivalente in Django templates).\nFilter:\n@contextfilter\ndef render(context, value, **kwargs):\n \"\"\"\n Renders the filtered value as a string template, using the context\n and environment of the caller template.\n \"\"\"\n if ... | [
2
] | [] | [] | [
"filter",
"internationalization",
"jinja2",
"python",
"templates"
] | stackoverflow_0008056516_filter_internationalization_jinja2_python_templates.txt |
Q:
Related to model( each song need each artist)
I have created this model. But I need each song need each artist How Is it possible?
I have no idea. Here is my model screenshot Can you please help me ? thank you
class Song(models.Model):
title = models.CharField(max_length=100,help_text="Album Name")
slug... | Related to model( each song need each artist) | I have created this model. But I need each song need each artist How Is it possible?
I have no idea. Here is my model screenshot Can you please help me ? thank you
class Song(models.Model):
title = models.CharField(max_length=100,help_text="Album Name")
slug = models.SlugField(unique = True,help_text="Must b... | [
"In the Song class, add a field:\nartist = models.ForeignKey(Artist)\n\nThen each song will have only one artist, but the artists can have many songs. If you want a song to have many artists, use ManyToManyField.\n",
"You have to create relations between artists, songs and albums.\nIn your case a ForeignKey ist p... | [
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008061688_django_python.txt |
Q:
Gevent incremental process through non blocking joinall()
Here I want to make some modificatins for my setting.
I want response from multiple API calls within a single request made to my server. from all these API calls I want to combine results and return them as a response. Until here pretty much everything fol... | Gevent incremental process through non blocking joinall() | Here I want to make some modificatins for my setting.
I want response from multiple API calls within a single request made to my server. from all these API calls I want to combine results and return them as a response. Until here pretty much everything follows as given in examples of gevent documentation and over here... | [
"If you want to collect results from multiple greenlets, then modify print_head() to return the result and then use .get() method to collect them all.\nPut this after joinall():\ntotal_result = [x.get() for x in jobs]\n\nActually, joinall() is not even necessary in this case.\nIf print_head() looks like this:\ndef ... | [
1
] | [] | [] | [
"gevent",
"monkeypatching",
"python",
"urllib"
] | stackoverflow_0008063415_gevent_monkeypatching_python_urllib.txt |
Q:
os.mkdir's rights assigning doesn't work as expected
I'm trying to create directory with 777 rights.
os.mkdir(Xmldocument.directory, 0777)
However what I get is 775
drwxrwxr-x. 2 mwysoki mwysoki 4096 Nov 9 11:38 VeloDBBrowser
I'm sure that I have appropriate rights because chmod 777 works just fine.
A:
The cu... | os.mkdir's rights assigning doesn't work as expected | I'm trying to create directory with 777 rights.
os.mkdir(Xmldocument.directory, 0777)
However what I get is 775
drwxrwxr-x. 2 mwysoki mwysoki 4096 Nov 9 11:38 VeloDBBrowser
I'm sure that I have appropriate rights because chmod 777 works just fine.
| [
"The current umask is applied here as well.\nNormally, files are created with 0777 (if executable or directory) or 0666 (other files.)\nThen the OS applies the current umask to this value, resulting into 0755 resp. 0644 seen on most files, as the most usual umask is 0022.\nYour solution would be to set the umask to... | [
7
] | [] | [] | [
"python",
"unix"
] | stackoverflow_0008063836_python_unix.txt |
Q:
Python, regex negative lookbehind behavior
I have a regular experssion that should find up to 10 words in a line. THat is, it should include the word just preceding the line feed but not the words after the line feed. I am using a negative lookbehind with "\n".
a = re.compile(r"((\w)+[\s /]){0,10}(?<!\n)")
r = a.s... | Python, regex negative lookbehind behavior | I have a regular experssion that should find up to 10 words in a line. THat is, it should include the word just preceding the line feed but not the words after the line feed. I am using a negative lookbehind with "\n".
a = re.compile(r"((\w)+[\s /]){0,10}(?<!\n)")
r = a.search("THe car is parked in the garage\nBut the ... | [
"I don't know why you would use negative lookahead. You are saying that you want a maximum of 10 words before a linefeed. The regex below should work. It uses a positive lookahead to ensure that there is a linefeed after the words. Also when searching for words use `b\\w+\\b` instead of what you were using.\n/(\\b\... | [
0,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008062033_python_regex.txt |
Q:
How do I put a progress bar in a messagebox in tkinter in python?
I am trying to put a progress bar in a message box to display the progress of downloading of files; something like this:
(Image taken from here.)
So for the progress bar I will use this :
pbar=ttk.Progressbar(app,orient='horizontal',length=200,mode... | How do I put a progress bar in a messagebox in tkinter in python? | I am trying to put a progress bar in a message box to display the progress of downloading of files; something like this:
(Image taken from here.)
So for the progress bar I will use this :
pbar=ttk.Progressbar(app,orient='horizontal',length=200,mode='determinate')
pbar.pack()
And maybe I could use a text widget, but I... | [
"I think you have an error: in your code, pbar=ttk.ProgressBar(app, ...) should be replaced by pbar=ttk.ProgressBar(root1, ...). In this class instantiation, the first argument is the parent widget, and I bet it should be root1 in your code.\nBut as written by brc in comment, we can't be sure as long as you do not ... | [
0
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0008045923_python_tkinter_user_interface.txt |
Q:
How to draw a translucent rectangle on a static text?
I draw a tranlucent rectangle on my panel but on the places that have static text's the rectangle is not filled.
I've drawn rectangles inside each static text but when I do that, the correspondent text doesn't happear.
How can I draw a translucent rectangle ins... | How to draw a translucent rectangle on a static text? | I draw a tranlucent rectangle on my panel but on the places that have static text's the rectangle is not filled.
I've drawn rectangles inside each static text but when I do that, the correspondent text doesn't happear.
How can I draw a translucent rectangle inside the statix text without making the text disappear?
The ... | [
"Associate the onPaint event to all statix text's.\n"
] | [
0
] | [] | [] | [
"draw",
"python",
"text",
"wxpython"
] | stackoverflow_0003075065_draw_python_text_wxpython.txt |
Q:
render_to_response concatenate URL to the current URL
I have a view to delete a record when clicking an anchor in index page.I wanna redirect to current page after running this view.in urls.py:
(r'^airAgency/(?P<key>[a-zA-Z0-9]+)/tour/delete/(?P<tour_id>\d+)/$','airAgency.views.deletetour'),
(r'^airAgency/(?P<key>... | render_to_response concatenate URL to the current URL | I have a view to delete a record when clicking an anchor in index page.I wanna redirect to current page after running this view.in urls.py:
(r'^airAgency/(?P<key>[a-zA-Z0-9]+)/tour/delete/(?P<tour_id>\d+)/$','airAgency.views.deletetour'),
(r'^airAgency/(?P<key>[a-zA-Z0-9]+)/$','airAgency.views.index'),
in views.py:
de... | [
"If you decide to use HttpResponseRedirect, try this:\nreturn HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))\n\n",
"Once you are in a handler for another url, you can't change the url without redirecting. If you need to maintain state into the original url when you get back to it, encode it into get ... | [
2,
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008063626_django_python.txt |
Q:
Regex to match word and trailing whitespace pairs
I have a text:
" Alice, Bob Charlie "
and I would like to get pairs of word (if any) and the whitespace after it. That is:
[("", " "), ("Alice,", " "), ("Bob", " "), ("Charlie", " ")]`
In Python, I tried:
re.findall(r"(\S*)(\s*)", " Alice, Bob ... | Regex to match word and trailing whitespace pairs | I have a text:
" Alice, Bob Charlie "
and I would like to get pairs of word (if any) and the whitespace after it. That is:
[("", " "), ("Alice,", " "), ("Bob", " "), ("Charlie", " ")]`
In Python, I tried:
re.findall(r"(\S*)(\s*)", " Alice, Bob Charlie ")
which almost works - it just adds an empt... | [
"re.findall(r\"(\\S+)(\\s*)\", \" Alice, Bob Charlie \")\n\nwith a + sign after the \\S returns what you probably want:\n[('Alice,', ' '), ('Bob', ' '), ('Charlie', ' ')]\n\notherwise \\S*\\s* can possibly match empty string at the end: zero-or-more and zero-or-more can equal to zero-length too.\nOther p... | [
2,
2,
2
] | [] | [] | [
"python",
"regex",
"whitespace"
] | stackoverflow_0008063525_python_regex_whitespace.txt |
Q:
Django and SSL question
I am planning to sell products by charging credit cards thus using SSL will be critical for Django-powered website. And I am very naive for this.
My initial django setup plan was using Apache as the webserver and using mod_wsgi to communicate with Django, static media again served by Apache... | Django and SSL question | I am planning to sell products by charging credit cards thus using SSL will be critical for Django-powered website. And I am very naive for this.
My initial django setup plan was using Apache as the webserver and using mod_wsgi to communicate with Django, static media again served by Apache. All seemed good until SSL p... | [
"I have deployed Django apps on SSL using Apache's mod_ssl and mod_wsgi.\nI am no Apache expert, but here's how I setup SSL for one site (put the directives below in the httpd.conf file, or in a file referenced from that file, for instance in the sites-enabled directory, if that is used in your Apache installation)... | [
28,
14,
7
] | [] | [] | [
"django",
"python",
"ssl"
] | stackoverflow_0002131727_django_python_ssl.txt |
Q:
ajax widgets in pyramid and chameleon
I would like to be able to easily create ajax 'widgets' backed by chameleon and pyramid on the server side.
Does Pyramid provide any plumbing code that would make writing widgets easy?
My current approach is I have a home view which uses home.pt as the renderer. home.pt uses ... | ajax widgets in pyramid and chameleon | I would like to be able to easily create ajax 'widgets' backed by chameleon and pyramid on the server side.
Does Pyramid provide any plumbing code that would make writing widgets easy?
My current approach is I have a home view which uses home.pt as the renderer. home.pt uses a macro base.pt which defines the page stru... | [
"A good way of dealing with this is to associate your account_login_widget with its own view, like:\n@view_config(name='login_widget',\n renderer='templates/account_login_widget.pt')\ndef login_widget(request):\n return {'username': ...}\n\nYou should then be able to visit http://yourapp/login_widget... | [
8
] | [] | [] | [
"ajax",
"chameleon",
"pyramid",
"python",
"template_tal"
] | stackoverflow_0008063012_ajax_chameleon_pyramid_python_template_tal.txt |
Q:
Is it possible to have python rich comparison in php?
One of my dreams is to use python rich comparison (something like __eq__) on php objects.
class A {
public $a = 1;
public function __eq__($other) {
return $this->a == $other->a;
}
}
class B {
public $a = 2;
public function __eq__($other) {
... | Is it possible to have python rich comparison in php? | One of my dreams is to use python rich comparison (something like __eq__) on php objects.
class A {
public $a = 1;
public function __eq__($other) {
return $this->a == $other->a;
}
}
class B {
public $a = 2;
public function __eq__($other) {
return $this->a == $other->a;
}
}
class C {
pu... | [
"No, it isn't. A common way to achieve this is to use an equals() method, but there isn't any magic method. You'll have to call it manually. For example:\n<?php\nclass User\n{\n private $id;\n\n public function __construct($id)\n {\n $this->id = $id;\n }\n\n public function getId()\n {\n ... | [
2
] | [] | [] | [
"comparable",
"comparison",
"php",
"python"
] | stackoverflow_0008064769_comparable_comparison_php_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.