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:
How to create a restart button in wx.Python - Python
So I have a program that opens up and does stuff.. However, is there a way to either restart the frame that is open or is there a way to close and open the frame again without have to rerun the program?
A:
You can use either:
frame.Iconize() to minimize your ... | How to create a restart button in wx.Python - Python | So I have a program that opens up and does stuff.. However, is there a way to either restart the frame that is open or is there a way to close and open the frame again without have to rerun the program?
| [
"You can use either:\n\nframe.Iconize() to minimize your window\nHide it using methods:\nwindow.Hide()\n\nwindow.Show(n) with n= True or False \n\n\nWith the second alternative the frame disappears, so you need some method to call your frame back (maybe leaving visible a small parent or child frame with a button to... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008101674_python_wxpython.txt |
Q:
Python, change current shell environment variables while using Popen?
I have an XML that contains information about environment variable to set into the shell by my python script. Here is a snippet of the XML :
<envVar name='QTDIR'>/homeqt/libs.qt4/qt4.5.1</envVar>
<envVar name='MAKE'>which make</envVar>
This pa... | Python, change current shell environment variables while using Popen? | I have an XML that contains information about environment variable to set into the shell by my python script. Here is a snippet of the XML :
<envVar name='QTDIR'>/homeqt/libs.qt4/qt4.5.1</envVar>
<envVar name='MAKE'>which make</envVar>
This part of this snippet tells my python script to set environment variables QTDI... | [
"I would make use of XML attributes.\n<envVar name=\"MAKE\" type=\"command\">which make</envVar>\n<envVar name=\"QTDIR\" type=\"string\">/homeqt/libs.qt4/qt4.5.1</envVar>\n\npseudocode depending on your xml library:\nif node.attributes['type'] == 'command':\n value = os.popen(node.firstChild.text).read()\nelif n... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0008101641_python.txt |
Q:
Python: trying to use 'count' to limit the amount of lines "print" will output
I have a script that will walk a system directory, and get the files sizes in that directory. it then sorts by the file size(descending), takes two arguments. The first arg is the system path and the second arg is an integer to limit t... | Python: trying to use 'count' to limit the amount of lines "print" will output | I have a script that will walk a system directory, and get the files sizes in that directory. it then sorts by the file size(descending), takes two arguments. The first arg is the system path and the second arg is an integer to limit the output to that integer count.
I'm using a while loop to limit the print output bu... | [
"FWIW, the repr module has tools to display a list while limiting the number of lines of output.\n",
"If mycnt is a string, not an integer (which it is when read directly from sys.argv), your loop will never end.\n",
"You should have an if instead of while.\nYou want to exit the program if count <= mycnt.\n",
... | [
4,
3,
2,
1,
1
] | [] | [] | [
"count",
"python",
"while_loop"
] | stackoverflow_0008102177_count_python_while_loop.txt |
Q:
How to check screen is running?
How to check in Python whether the screen with the given name. For example, check if server1 is running?
Thanks : )
A:
The built in command for finding current screen sessions is screen -ls
To get the same functionality in python:
from subprocess import check_output
def screen_pr... | How to check screen is running? | How to check in Python whether the screen with the given name. For example, check if server1 is running?
Thanks : )
| [
"The built in command for finding current screen sessions is screen -ls\nTo get the same functionality in python:\nfrom subprocess import check_output\n\ndef screen_present(name):\n var = check_output([\"screen -ls; true\"],shell=True)\n if \".\"+name+\"\\t(\" in var:\n print name+\" is... | [
5,
3,
0
] | [] | [] | [
"gnu_screen",
"python"
] | stackoverflow_0008015163_gnu_screen_python.txt |
Q:
If we execute a symbolic link python script, can we print the path of the real file?
If I execute a python script which is actually a symbolic link linked to the real script from somewhere else, is there anyway we can print the location of the real script?
A:
Alternatively, if you don't want to use argv
#!/usr/b... | If we execute a symbolic link python script, can we print the path of the real file? | If I execute a python script which is actually a symbolic link linked to the real script from somewhere else, is there anyway we can print the location of the real script?
| [
"Alternatively, if you don't want to use argv\n#!/usr/bin/python\nimport os\nprint os.path.realpath(__file__)\n\n",
"#!/usr/bin/python\n\nimport os\nimport sys\n\nprint os.path.realpath(sys.argv[0])\n\n"
] | [
4,
3
] | [] | [] | [
"python"
] | stackoverflow_0008102476_python.txt |
Q:
Calling a base class method from a base class
When I call method1() from the outer class, it ends up calling the derived class method1() instead. How can I force it to call the base class method1? Is it best for the inner class to have an init and from there call the parent init?
class OuterClassA
__init__
... | Calling a base class method from a base class | When I call method1() from the outer class, it ends up calling the derived class method1() instead. How can I force it to call the base class method1? Is it best for the inner class to have an init and from there call the parent init?
class OuterClassA
__init__
method1()
def method1(self):
...... | [
"Python's double underscores name mangling is designed to help with this issue.\nFor the details and a worked-out example see: http://docs.python.org/tutorial/classes.html#private-variables and at http://docs.python.org/reference/expressions.html#atom-identifiers .\nclass OuterClassA:\n def __init__(self):\n ... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0008102538_python.txt |
Q:
Python: How can I fix this code so it works on Windows?
import lxml.html
import mechanize, cookielib
import multiprocessing
browser = None
def download(i):
link = 'www.google.com'
response = browser.open(link)
tree = lxml.html.parse(response)
print tree
return 0
if __name__ == '__main__': ... | Python: How can I fix this code so it works on Windows? | import lxml.html
import mechanize, cookielib
import multiprocessing
browser = None
def download(i):
link = 'www.google.com'
response = browser.open(link)
tree = lxml.html.parse(response)
print tree
return 0
if __name__ == '__main__':
browser = mechanize.Browser()
cookie_jar = cookieli... | [
"I would try to:\n\nremove browser = None\nor\nmove the code in the __name__==\"__main__\" into main() function and add global browser before browser=mechanize.Browser()\nor\nmove code that initializes browser to an initializer\n\nIf your tasks are I/O bound then you don't necessarily need multiprocessing to make c... | [
0,
0
] | [] | [] | [
"mechanize",
"multithreading",
"python"
] | stackoverflow_0008102293_mechanize_multithreading_python.txt |
Q:
how to apply patch in mercurial and show diff tool if failed apply
I want apply patch in Mercurial:
hg import patch_name.patch
But if I get the error abort: patch failed to apply, Mercurial creates *.rej files.
Is there a way show kdiff or vim-diif to correcting conflict.
A:
There isn't a way to do this. The r... | how to apply patch in mercurial and show diff tool if failed apply | I want apply patch in Mercurial:
hg import patch_name.patch
But if I get the error abort: patch failed to apply, Mercurial creates *.rej files.
Is there a way show kdiff or vim-diif to correcting conflict.
| [
"There isn't a way to do this. The recommended approach is to open the file and the .rej file and manually merge in the rejected hunks.\n",
"I would bet that hg returns an error code. Perhaps you can wrap hg import in a shell script that catches the error code returned and does what you want if there was an erro... | [
3,
2
] | [] | [] | [
"mercurial",
"patch",
"python"
] | stackoverflow_0008006203_mercurial_patch_python.txt |
Q:
How do I avoid text between {{ }}
Possible Duplicate:
My regex is not working properly
Suppose I have long text. From following text I need only abstract part. How do I avoid text between {{ }}. Thanks
`
{{ Info extra text}}
{{Infobox film
| name = Papori
| released = 1986
| runtime = 144 ... | How do I avoid text between {{ }} |
Possible Duplicate:
My regex is not working properly
Suppose I have long text. From following text I need only abstract part. How do I avoid text between {{ }}. Thanks
`
{{ Info extra text}}
{{Infobox film
| name = Papori
| released = 1986
| runtime = 144 minutes
| country = Assam, {{IN... | [
"What I did:\n>>> text\n\"{{ Info extra text}}\\n{{Infobox film\\n| name = Papori\\n| released = 1986\\n| runtime = 144 minutes\\n| country = Assam, {{IND}}\\n| budget = [[a]]\\n| followed by = free\\n}}\\nAlbert Einstein ( /'ælb?rt 'a?nsta?n/; German: ['alb?t 'a?n?ta?n] ( l... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008103081_python_regex.txt |
Q:
If Python 3 is the newest python, why is python 2 still around?
I used Python a few years ago when 2 was the only version.
Now there is 2 and 3.
Was there a a reason 2 hasn't continued to upgrade and now there is a split into two different pythons? Like no one uses Python 2.5. They all use 2.7 or whatever it is. W... | If Python 3 is the newest python, why is python 2 still around? | I used Python a few years ago when 2 was the only version.
Now there is 2 and 3.
Was there a a reason 2 hasn't continued to upgrade and now there is a split into two different pythons? Like no one uses Python 2.5. They all use 2.7 or whatever it is. Why not just use 3? Obviously there's a reason, but I was unable to fi... | [
"\nWhy not just use 3?\n\nA lot of existing Python code is not compatible with Python 3 yet. If you need to use Django for example you are forced to use Python 2.x.\n\nMy second question is, which one should I use?\n\n\nPython 3 and PyQt 4 recommendations\n\n",
"Python 3 is significantly different than Python 2.x... | [
10,
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008102987_python.txt |
Q:
Setting up my remote api
My app needs a backup system and remote administration so I disabled the federated login for easier remote_api access. Now I can log in but I can't import my module:
montao$ python ./remote_api_shell.py -s montaoproject.appspot.com
Email: niklasro
Password:
App Engine remote_api shell
Pyt... | Setting up my remote api | My app needs a backup system and remote administration so I disabled the federated login for easier remote_api access. Now I can log in but I can't import my module:
montao$ python ./remote_api_shell.py -s montaoproject.appspot.com
Email: niklasro
Password:
App Engine remote_api shell
Python 2.7.1+ (r271:86832, Apr 11... | [
"Prefix your command with PYTHONPATH=. (or replace . with the directory your app is in). Without telling Python where it can find modules, it doesn't know where to look, and the current directory isn't part of the path by default.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008099353_google_app_engine_python.txt |
Q:
How to crawl 'this' url use urllib?
I try to use urllib to crawl this file: http://www.anzhi.com/dl_app.php?s=68611, but always download a wrong file(size smaller). However, if I open up this link on chrome, it goes well and the downloaded file size is correct. The code is attached, what's the problem?
import url... | How to crawl 'this' url use urllib? | I try to use urllib to crawl this file: http://www.anzhi.com/dl_app.php?s=68611, but always download a wrong file(size smaller). However, if I open up this link on chrome, it goes well and the downloaded file size is correct. The code is attached, what's the problem?
import urllib
apk = "http://sc.hiapk.com/Download.... | [
"What OS are you on? This line of code:\nlocalFile = open(local, \"w\")\n\nopens a text-mode file on Windows, which will do things that you don't want. Does changing that to \nlocalFile = open(local, \"wb\")\n\n(opening the file in binary mode) make things work correctly?\n",
"You're not using the same URL in you... | [
2,
1
] | [] | [] | [
"download",
"python",
"urllib"
] | stackoverflow_0007878179_download_python_urllib.txt |
Q:
Appending tuples to lists, assigning index
I'm working on a chemistry program which requires a list of all elements and their corresponding atomic mass units, something along the lines of:
Elements = [(H,1),(He,2)...(C,12)]
all the elements and their AMU are read from a file where each line is written like "C 12"... | Appending tuples to lists, assigning index | I'm working on a chemistry program which requires a list of all elements and their corresponding atomic mass units, something along the lines of:
Elements = [(H,1),(He,2)...(C,12)]
all the elements and their AMU are read from a file where each line is written like "C 12". I need to read the information from the file, ... | [
"An easier solution is to iterate over the file using a for loop:\nelements = []\nwith open(\"AtomAMU.txt\") as f:\n for line in f:\n name, mass = line.split()\n elements.append((name, int(mass)))\n\n",
"Assuming the lines only contain C 12 and such, and are separated by spaces:\nresult = []\nfor... | [
5,
3,
1,
1,
0
] | [] | [] | [
"append",
"list",
"python",
"tuples"
] | stackoverflow_0008055117_append_list_python_tuples.txt |
Q:
why does b'(and sometimes b' ') show up when I split some HTML source[Python]
I'm fairly new to Python and programming in general. I have done a few tutorials and am about 2/3 through a pretty good book. That being said I've been trying to get more comfortable with Python and proggramming by just trying things in ... | why does b'(and sometimes b' ') show up when I split some HTML source[Python] | I'm fairly new to Python and programming in general. I have done a few tutorials and am about 2/3 through a pretty good book. That being said I've been trying to get more comfortable with Python and proggramming by just trying things in the std lib out.
that being said I have recently run into a wierd quirk that I'm su... | [
"The \"b\" prefix means that the type is bytes not str. To convert the bytes into text, use the decode method and name the appropriate encoding. The encoding is often found in the \"Content-Type\" header:\n>>> u = urllib.request.urlopen('http://cnn.com')\n>>> u.getheader('Content-Type')\n'text/html; charset=UTF-8... | [
8,
2
] | [] | [] | [
"parsing",
"python",
"python_3.x"
] | stackoverflow_0008102471_parsing_python_python_3.x.txt |
Q:
How do you define a wrapper function in Fabric?
Consider this simple fabric file:
def wrapper():
f1()
f2()
@hosts([host1])
def f1():
run('ls')
@hosts([host2])
def f2():
run('uname')
By running fab wrapper you get a prompt for:
No hosts found. Please specify a (single) host string for connection... | How do you define a wrapper function in Fabric? | Consider this simple fabric file:
def wrapper():
f1()
f2()
@hosts([host1])
def f1():
run('ls')
@hosts([host2])
def f2():
run('uname')
By running fab wrapper you get a prompt for:
No hosts found. Please specify a (single) host string for connection:
How can I make wrapper() ignore any hosts, and ass... | [
"Fabric issue #21 deals with this longstanding problem.\nexecute() now supports this behavior.\n"
] | [
0
] | [] | [] | [
"fabric",
"python"
] | stackoverflow_0007056032_fabric_python.txt |
Q:
Python : How to save object state and reuse it
I want to save object state and reuse it after some time.
I got some example on How to save object (Pickle module), I was not able to find how to resume class/method from the save state and proceed further.
Like game, we can save the game and latter we can continue, ... | Python : How to save object state and reuse it | I want to save object state and reuse it after some time.
I got some example on How to save object (Pickle module), I was not able to find how to resume class/method from the save state and proceed further.
Like game, we can save the game and latter we can continue, I know in game we save all the data and game read th... | [
"The easiest way is to make sure that the state of the Object is not saved in local scopes, but as attributes of the object. Consider\nimport cPickle\n\nclass Test(objet):\n def __init__(self, filename=\"mystate.pickle\"):\n self.index = 0\n self.filename = filename\n\n def save(self):\n ... | [
1,
0
] | [] | [] | [
"python",
"serialization"
] | stackoverflow_0005673127_python_serialization.txt |
Q:
Storing the output of a for loop through each iteration
I'm trying to save the output of my for loop for each iteration...for example, here is my code:
def encrypt(key):
for char in (key):
val = (ord(char)) - (96)
for example, if someone entered "lol" through the interpreter my program outputs...
encrypt("lol... | Storing the output of a for loop through each iteration | I'm trying to save the output of my for loop for each iteration...for example, here is my code:
def encrypt(key):
for char in (key):
val = (ord(char)) - (96)
for example, if someone entered "lol" through the interpreter my program outputs...
encrypt("lol")
12
15
12
In this example, I need to store 12,15,12 in mem... | [
"Instead of saving to some temporary value val, save it to a list and return the list.\ndef encrypt(key):\n temp = list()\n for char in(key):\n temp.append((ord(char))-96)\n return temp\n\n",
"There are a number of different methods you could use to do this, but in Python probably the nicest way i... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0008104173_python.txt |
Q:
Python- Sympy Issue with expression equality check when evaluate=False
In my project I have to use evaluate=false at the time when i am creating any Add or Mul objects. In this case I am facing a problem when I apply equality checks on these objects. The issue is because of the ordering of the arguments.
Please co... | Python- Sympy Issue with expression equality check when evaluate=False | In my project I have to use evaluate=false at the time when i am creating any Add or Mul objects. In this case I am facing a problem when I apply equality checks on these objects. The issue is because of the ordering of the arguments.
Please consider the example below:
k2=Mul(*[x,y,2],evaluate=False)
k1=Mul(*[x,2,y],ev... | [
"Mul doesn't know that x and y both represent scalars. Matrix multiplication depends on the order of the arguments so in your example k1 and k2 are not necessarily equal. \nIf you know that in your program x and y will always be scalars (or some other type of value where multiplication is commutative and associativ... | [
1,
0,
0
] | [] | [] | [
"python",
"sympy"
] | stackoverflow_0008079892_python_sympy.txt |
Q:
Command prompt within another widget
I have a GUI with label and entry widgets on a frame widget. I want to add a command prompt.to the frame through which the user can submit commands. I know about using the cmd module to create a prompt in the python shell, but I want the prompt to be part of my GUI window. Is t... | Command prompt within another widget | I have a GUI with label and entry widgets on a frame widget. I want to add a command prompt.to the frame through which the user can submit commands. I know about using the cmd module to create a prompt in the python shell, but I want the prompt to be part of my GUI window. Is there a way to 'embed' a command prompt in ... | [
"The cmd module was made for terminals, where there's just one textual “widget” used for both input and output. This is not really suited for a GUI.\nHere's an idea (inspired by web frameworks like Pyramid) that works better:\nHave a read-only widget for the output, and a separate widget for the command entry.\nWhe... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0008104455_python.txt |
Q:
SWIG C++ to Python: Warning(362): operator= ignored
I am exporting a C++ class to Python and I noticed that during compilation, SWIG issued the following warning:
Warning(362): operator= ignored
I am not sure why the operator is being overloaded, because it says in the SWIG documentation, that SWIG is capable of ... | SWIG C++ to Python: Warning(362): operator= ignored | I am exporting a C++ class to Python and I noticed that during compilation, SWIG issued the following warning:
Warning(362): operator= ignored
I am not sure why the operator is being overloaded, because it says in the SWIG documentation, that SWIG is capable of handling operators such as the assignment operator
There ... | [
"There is no assignment in python (other than in primitive types), only assignment of pointers. If you want to create a copy, you need a special copy function.\n",
"Read the last line of your documentation link (section 31.3.11):\n\nAlso, be aware that certain operators don't map cleanly to Python. For instance, ... | [
9,
6
] | [] | [] | [
"c++",
"python",
"swig"
] | stackoverflow_0008102244_c++_python_swig.txt |
Q:
What's the difference between class attributes and data attributes in python
Possible Duplicate:
Python: Difference between class and instance attributes
class a:
m = 1
def __init__(self):
self.n = 2
According to the book I am reading, m is called class attributes and n is called data attributes... | What's the difference between class attributes and data attributes in python |
Possible Duplicate:
Python: Difference between class and instance attributes
class a:
m = 1
def __init__(self):
self.n = 2
According to the book I am reading, m is called class attributes and n is called data attributes, but what's the difference between them?
It seems that the operations of them i... | [] | [] | [
"This is essentially a duplicate of this question which has an example of the difference.\nPython: Difference between class and instance attributes\n"
] | [
-1
] | [
"attributes",
"class",
"python"
] | stackoverflow_0008104814_attributes_class_python.txt |
Q:
chmod - file permission on executable
I have to change file permissions on an executable file, using os.chmod.
I have this executable and I want to change its permissions so that it can write nowhere, only reading and executing.
How can I do that?
Thanks,
rubik
A:
The permissions you can set on a file with chm... | chmod - file permission on executable | I have to change file permissions on an executable file, using os.chmod.
I have this executable and I want to change its permissions so that it can write nowhere, only reading and executing.
How can I do that?
Thanks,
rubik
| [
"The permissions you can set on a file with chmod affect who can read from/write to/execute that file, not what privileges the process created by running that file has.\nOn Unix you could get some form of protection by playing with the file owner and the sticky bit, and having appropriate permissions on your filesy... | [
2,
1,
1
] | [] | [] | [
"chmod",
"executable",
"permissions",
"python"
] | stackoverflow_0008104811_chmod_executable_permissions_python.txt |
Q:
psycopg2 fails on execute many statement with syntax error
I have data coming from mongodb which looks like
data =
(
{
u'name': 'A',
u'primary_key': 1
},
{
u'name': 'B',
u'primary_key': 2
},
{
u'name': 'C',
u'primary_key': 3
}
)
when I call the following
cur = conn.cursor()
cur.execut... | psycopg2 fails on execute many statement with syntax error | I have data coming from mongodb which looks like
data =
(
{
u'name': 'A',
u'primary_key': 1
},
{
u'name': 'B',
u'primary_key': 2
},
{
u'name': 'C',
u'primary_key': 3
}
)
when I call the following
cur = conn.cursor()
cur.executemany("""INSERT INTO ddmension(id,name) VALUES (%(primary_key)s,... | [
"We should try un-quoting that error message to see a bit more clearly what is going on here. We can do that at the Python prompt:\n>>> message = 'syntax error at or near \"\"\"\"INSERT INTO dimension (id, name) VALUES (1, E\\'A\\')\"\"\"\"\\nLINE 1: \"\"\"INSERT INTO dimension (id, name) VALUES (1, E\\'A\\n ^\\n'\... | [
0
] | [] | [] | [
"mongodb",
"psycopg2",
"python"
] | stackoverflow_0008101744_mongodb_psycopg2_python.txt |
Q:
Using a for loop instead of if,elif?
I can begin with what i've written:
for player in self.players:
player.shot()
if self.players[0].best > self.players[1].best and self.players[2].best:
self.players[0].wins += 1
print ("Winner: ", self.players[0].name, "\nResult: ", self.players[0].best)
elif self.... | Using a for loop instead of if,elif? | I can begin with what i've written:
for player in self.players:
player.shot()
if self.players[0].best > self.players[1].best and self.players[2].best:
self.players[0].wins += 1
print ("Winner: ", self.players[0].name, "\nResult: ", self.players[0].best)
elif self.players[1].best > self.players[0].best and... | [
"The Pythonic way to do it is something like:\nbestOfAll = max(p.best for p in self.players)\nbestPlayers = [p for p in self.players if p.best == bestOfAll]\n\nif len(bestPlayers) == 1:\n bestPlayer = bestPlayers[0]\n bestPlayer.wins += 1\n print (\"Winner: \", bestPlayer.name, \"\\nResult: \", bestPlayer.... | [
4,
0,
0
] | [
"int playerno\nint max = 0\nforeach player in self.players\nif(self.players[player].best > max)\n{\nplayerno = player\nmax = self.players[player]\n}\nself.players[playerno].wins++\nprint (\"Winner: \", self.players[playerno].name, \"\\nResult: \", self.players[playerno].best)\n\nThe syntax may be a little incorrect... | [
-1
] | [
"compare",
"object",
"python"
] | stackoverflow_0008105084_compare_object_python.txt |
Q:
How do I stop the QTreeWidget from moving the scroll position?
I have a QTreeWidget with a bunch of QTreeWidgetItems. Each item has a couple columns. When one of the columns is wider than the width of the widget, there will be a scroll bar at the bottom. When I click on a QTreeWidgetItem inside the column that is ... | How do I stop the QTreeWidget from moving the scroll position? | I have a QTreeWidget with a bunch of QTreeWidgetItems. Each item has a couple columns. When one of the columns is wider than the width of the widget, there will be a scroll bar at the bottom. When I click on a QTreeWidgetItem inside the column that is wider than the widget, the QTreeWidget will automatically scroll to ... | [
"This is behaviour is controlled by the QAbstractItemView.autoScroll property, which can be set like this:\ntreewidget.setAutoScroll(False)\n\nHowever, this property is mainly used for automatically scrolling the tree widget when dragging items to the edge of the widget's viewport. So if this behaviour is still nee... | [
7
] | [] | [] | [
"pyqt",
"python",
"qt",
"qtreewidget",
"scroll"
] | stackoverflow_0008100343_pyqt_python_qt_qtreewidget_scroll.txt |
Q:
Dynamically call python-class defined in config-file
I have a config.cfg which I parse using the python-module ConfigParser. In one section I want to configure assignments of the form fileextension : ClassName. Parsing results in the following dictionary:
types = {
"extension1" : "ClassName1",
"extension2" : "... | Dynamically call python-class defined in config-file | I have a config.cfg which I parse using the python-module ConfigParser. In one section I want to configure assignments of the form fileextension : ClassName. Parsing results in the following dictionary:
types = {
"extension1" : "ClassName1",
"extension2" : "ClassName2"
}
EDIT: I know I can now do:
class_ = eval(ty... | [
"You could use eval, if the class name in the config file exactly matches the class names in your python code (and if the classes are in scope!), but ..... eval is evil (a coincidence that there's only one letter difference? I think not!)\n\nA safer way to do it would be to add an extra dictionary that maps from c... | [
6,
0
] | [] | [] | [
"python"
] | stackoverflow_0008105533_python.txt |
Q:
What is the proper way of deleting item from a dictionary in "for" loop (Python)?
I want to iterate a dictionary, examine the value and delete items that matches certain values.
Example
d = {1, 1, 2, 1, 4, 5}
for i in d:
if i == 1:
del i
But we know doing this is dangerous since the list is updated whi... | What is the proper way of deleting item from a dictionary in "for" loop (Python)? | I want to iterate a dictionary, examine the value and delete items that matches certain values.
Example
d = {1, 1, 2, 1, 4, 5}
for i in d:
if i == 1:
del i
But we know doing this is dangerous since the list is updated while it is been iterated. What is clean way of doing this in Python?
| [
"If k is your dictionary, you can do\nk = {x:v for x,v in k.iteritems() if x != 1}\n\nFor 2.7+ and 3.0\nFor anything older, you can do \nk = dict((x,v) for x,v in k.iteritems() if x!=1)\n\n",
"I would recommend you to use builtin filter function since it is more clear what will be done with a list. Also filter wo... | [
6,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008105221_python.txt |
Q:
How do I use Django's ORM to return a group of rows only when 3 or more rows will be GROUPed?
Given the following Model:
class Enquiry(models.Model):
enquiryparent = models.ForeignKey('self',default=None, null=True, blank=True)
type = models.SmallIntegerField()
name = models.CharField(max_length=200)
... | How do I use Django's ORM to return a group of rows only when 3 or more rows will be GROUPed? | Given the following Model:
class Enquiry(models.Model):
enquiryparent = models.ForeignKey('self',default=None, null=True, blank=True)
type = models.SmallIntegerField()
name = models.CharField(max_length=200)
mobile = models.CharField(max_length=40,blank=True,null=True)
email = models.EmailField(blan... | [
"If I'm understanding you correctly it seems like this should be doable, but I'm unfortunately unfamiliar with Django's ORM. I think the basic idea would probably look like:\n\nSelect by id (id == 1 in your example), a static integer column that always equals 1, and a dynamic column like sum(static1)\nFilter by typ... | [
0
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0008036807_django_mysql_python.txt |
Q:
Python: Change the parameter of the loop while the loop is running
I want to change a in the for-loop to [4,5,6].
This code just print: 1, 2, 3
a = [1,2,3]
for i in a:
global a
a = [4,5,6]
print i
I want the ouput 1, 4, 5, 6.
A:
You'll need to clarify the question because there is no explanation of... | Python: Change the parameter of the loop while the loop is running | I want to change a in the for-loop to [4,5,6].
This code just print: 1, 2, 3
a = [1,2,3]
for i in a:
global a
a = [4,5,6]
print i
I want the ouput 1, 4, 5, 6.
| [
"You'll need to clarify the question because there is no explanation of how you should derive the desired output 1, 4, 5, 6 when your input is [1, 2, 3]. The following produces the desired output, but it's completely ad-hoc and makes no sense:\ni = 0\na = [1, 2, 3]\nwhile i < len(a):\n print(a[i])\n if a[i] ... | [
3,
0,
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0008104169_for_loop_python.txt |
Q:
Instantiating a Python Class without Construction Function and Inheritance
In the code following, OP created a class with inheriting Template class class BatchRename(Template): and at the bottom of the code, he is instantiating the class as t = BatchRename(fmt) albeit there is no construction method (def __init__(... | Instantiating a Python Class without Construction Function and Inheritance | In the code following, OP created a class with inheriting Template class class BatchRename(Template): and at the bottom of the code, he is instantiating the class as t = BatchRename(fmt) albeit there is no construction method (def __init__():). As I understand inheritance in Python, there might be something wrong with ... | [
"You don't need an __init__ in every Python class; it's optional and only called when present. The actual constructor for new-style Python classes is __new__, which is inherited from object:\n>>> class Foo(object):\n... pass\n...\n>>> Foo()\n<__main__.Foo object at 0x021757F0>\n>>> Foo(1)\nTraceback (most recent c... | [
3,
2
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0008106137_inheritance_python.txt |
Q:
Python AES decrypt string end with different char
I have an input string and I'm encrypting it with MySQL's AES_ENCRYPT and then decrypting it with python (not mysql AES_DECRYPT). I printed out some tests of the decrypted string:
print decrypt_string
print "%sxxx" % decrypt_string
print len(decrypt_string)
print s... | Python AES decrypt string end with different char | I have an input string and I'm encrypting it with MySQL's AES_ENCRYPT and then decrypting it with python (not mysql AES_DECRYPT). I printed out some tests of the decrypted string:
print decrypt_string
print "%sxxx" % decrypt_string
print len(decrypt_string)
print self.toHex(decrypt_string)
When the input string length... | [
"The reason for your observation is that AES is a block cipher, which can only encrypt data in blocks of 128 bits (= 16 bytes). To do so, it is normally used with a mode of operation (to allow encrypting larger pieces of data), and a padding mode. It looks like your python decrypting function does the decrypting, b... | [
1
] | [] | [] | [
"aes",
"char",
"python"
] | stackoverflow_0008102112_aes_char_python.txt |
Q:
Python Socket error
I am new to Python and I am trying to write a Server program. However, when it comes time for the server to accept the socket connection, it won't and I have to terminate the program with
File "test.py", line 12, in <module>
client_socket, address = server_socket.accept()
File "/usr/lib/pyth... | Python Socket error | I am new to Python and I am trying to write a Server program. However, when it comes time for the server to accept the socket connection, it won't and I have to terminate the program with
File "test.py", line 12, in <module>
client_socket, address = server_socket.accept()
File "/usr/lib/python2.6/socket.py", line 19... | [
"I think you should call socket.gethostbyname(socket.gethostname()) instead of just socket.gethostname().\n",
"I figured it out. Instead of socket.gethostname() I needed to be server_address in that spot. Thats why I couldn't connect to the server in the first place and always had to kill it with ^C \n"
] | [
0,
0
] | [] | [] | [
"python",
"sockets",
"syntax_error"
] | stackoverflow_0007935478_python_sockets_syntax_error.txt |
Q:
On a django form, how do I loop through individual options per field?
I'm building a form wizard. On the first step I have a form with one field. That field is a foreign key. Django's default widget for a foreign key gives me the field's options in a drop down (select) menu and represenets each option as an html o... | On a django form, how do I loop through individual options per field? | I'm building a form wizard. On the first step I have a form with one field. That field is a foreign key. Django's default widget for a foreign key gives me the field's options in a drop down (select) menu and represenets each option as an html option. I changed the default widget to a RadioSelect. So now it gives me th... | [
"you can access the choices queryset, but note that a template is probably not the right place for this kind of logic. NB the field.field which isn't a typo\n{% for field in form %}\n {% for option in field.field.choices.queryset %}\n {{ option.image }}\n {{ option.title }}\n {{ option.descr... | [
7,
0,
0
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0008106311_django_forms_python.txt |
Q:
Replacing parts of the string
Actually my question is quite simple:
I have a string like: 101222_1_1_ab;
I hope to change it into: 101222_1_ab_1
What bash commands should I use? and what to do in python?
THanks
A:
The easiest mechanism I can think of is to use awk(1):
$ echo 101222_1_1_ab | awk -F_ '{print $1 "_... | Replacing parts of the string | Actually my question is quite simple:
I have a string like: 101222_1_1_ab;
I hope to change it into: 101222_1_ab_1
What bash commands should I use? and what to do in python?
THanks
| [
"The easiest mechanism I can think of is to use awk(1):\n$ echo 101222_1_1_ab | awk -F_ '{print $1 \"_\" $2 \"_\" $4 \"_\" $3;}'\n101222_1_ab_1\n\nThe -F_ asks awk(1) to split fields apart on underscores.\nUpdate Glenn Jackman recommends the following, far more legible, version:\nawk -F_ -v OFS=_ '{print $1, $2, $4... | [
3,
2,
2,
2,
1,
1,
1
] | [] | [] | [
"bash",
"python",
"sed",
"split",
"string"
] | stackoverflow_0008101469_bash_python_sed_split_string.txt |
Q:
How to multiply pair-wise tuple list
I know how to multiply the elements of a single tuple:
tup = (2,3)
tup[0]*tup[1]
6
My question is how do you multiply the elements of several tuples using a for loop?
example: How do I get x = (4,5,6) when x = ((2,2), (5,1), (3,2))?
A:
Something like this:
tuple(a*b for a, b... | How to multiply pair-wise tuple list | I know how to multiply the elements of a single tuple:
tup = (2,3)
tup[0]*tup[1]
6
My question is how do you multiply the elements of several tuples using a for loop?
example: How do I get x = (4,5,6) when x = ((2,2), (5,1), (3,2))?
| [
"Something like this:\ntuple(a*b for a, b in x)\n\n",
"for tuples of any length, one line script:\n>>> tpl = ((2,2), (5,1), (3,2,4))\n>>> tuple(reduce(lambda x, y: x*y, tp) for tp in tpl)\n(4, 5, 24)\n>>> \n\n",
"x = ((2, 2), (5, 1), (3, 2))\ny = ((2, 3), (2, 3, 5), (2, 3, 5, 7))\n\ndef multiply_the_elements_of... | [
5,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008105774_python.txt |
Q:
Default configuration in python/django
I'm working on a reusable django app, which I want to make configurable by GLOBAL VARIABLES in settings.py.
I want these to be optional so I've provided default values inside my app in a conf.py module, where I have the following:
GLOBAL_1 = "Def value for global 1"
GLOBAL_2... | Default configuration in python/django | I'm working on a reusable django app, which I want to make configurable by GLOBAL VARIABLES in settings.py.
I want these to be optional so I've provided default values inside my app in a conf.py module, where I have the following:
GLOBAL_1 = "Def value for global 1"
GLOBAL_2 = "Def value for global 2"
GLOBAL_3 = "Def ... | [
"GLOBAL_1 = getattr(settings, 'GLOBAL_1', 'Def value for global 1')\n\n"
] | [
1
] | [] | [] | [
"django",
"python",
"python_import",
"verbosity"
] | stackoverflow_0008106589_django_python_python_import_verbosity.txt |
Q:
Why doesn't python regard two discrete instances of a django model to be the same object?
(Using django as an example; the ForeignKey is implicit in the example)
>>> from coconuts.models import Coconut, Swallow
>>> c1 = Coconut.objects.get(id=1)
>>> s = Swallow.objects.get(id=1)
>>> c2 = s.coconuts_carried.filter(... | Why doesn't python regard two discrete instances of a django model to be the same object? | (Using django as an example; the ForeignKey is implicit in the example)
>>> from coconuts.models import Coconut, Swallow
>>> c1 = Coconut.objects.get(id=1)
>>> s = Swallow.objects.get(id=1)
>>> c2 = s.coconuts_carried.filter(id=1)
>>> c1 == c2
True
>>> c1 is c2
False
My understanding is that 'is' tests identity, while... | [
"is compares python objects, not objects in your database. each query returns a new python objects, and so c and c2 are different. \nto see this, try changing some of the properties of c or c2. Only one of them will change.\nas can be seen from the docs,\nc == c2\n\nis equivalent to \nc.id == c2.id\n\n",
"They ar... | [
4,
1,
0
] | [] | [] | [
"django",
"operators",
"python"
] | stackoverflow_0008106028_django_operators_python.txt |
Q:
Python numpy averaging
Averaging a table like this is not a problem
table = [[1,2,3,0],[1,2,3,0],[1,2,3,4]]
You can
print numpy.average(table,axis=0)
But what if I have uneven sequences like:
table = [[1,2,3],[1,2,3],[1,2,3,4]]
Then the result should be:
1,2,3,4
As the element containing number 4 only occurs o... | Python numpy averaging | Averaging a table like this is not a problem
table = [[1,2,3,0],[1,2,3,0],[1,2,3,4]]
You can
print numpy.average(table,axis=0)
But what if I have uneven sequences like:
table = [[1,2,3],[1,2,3],[1,2,3,4]]
Then the result should be:
1,2,3,4
As the element containing number 4 only occurs once. and 4/1 = 4.
But numpy ... | [
"You could feed the data into a numpy masked array, then compute the means with np.ma.mean:\nimport numpy as np\nimport itertools\ndata=[[1,2,3],[1,2,3],[1,2,3,4]]\n\nrows=len(data)\ncols=max(len(row) for row in data)\narr=np.ma.zeros((rows,cols))\narr.mask=True\nfor i,row in enumerate(data):\n arr[i,:len(row)]=... | [
3,
2
] | [] | [] | [
"average",
"numpy",
"python"
] | stackoverflow_0008106691_average_numpy_python.txt |
Q:
Embedding a program within a Python Script
I created a program that allows the user to enter info about DNA twist,turn, and location, and other info. And the output is a PDB file, however, I want to show the .pdb file in a .pdb viewer within the program and cannot seem to know how. The desired applications are Chi... | Embedding a program within a Python Script | I created a program that allows the user to enter info about DNA twist,turn, and location, and other info. And the output is a PDB file, however, I want to show the .pdb file in a .pdb viewer within the program and cannot seem to know how. The desired applications are Chimera(http://www.cgl.ucsf.edu/chimera/), or swiss... | [
"Depending on how tight you want your integration to be, a decent start could be something as simple as using python to externally invoke Chimera or Swiss:\nimport subprocess\nsubprocess.Popen([\"C:/Path/To/Chimera/bin/chimera.exe\", \"--stereo\", \"seq\", \"c:/Path/to/pdb/you/created/protease.pdb\"])\n\nThis woul... | [
2
] | [] | [] | [
"biopython",
"python"
] | stackoverflow_0008105992_biopython_python.txt |
Q:
__new__ and __init__ in Python
I am learning Python and so far I can tell the things below about __new__ and __init__:
__new__ is for object creation
__init__ is for object initialization
__new__ is invoked before __init__ as __new__ returns a new instance and __init__ invoked afterwards to initialize inner state... | __new__ and __init__ in Python | I am learning Python and so far I can tell the things below about __new__ and __init__:
__new__ is for object creation
__init__ is for object initialization
__new__ is invoked before __init__ as __new__ returns a new instance and __init__ invoked afterwards to initialize inner state.
__new__ is good for immutable obje... | [
"\nhow I should structure the class using __init__ and __new__ as they are different and both accepts arbitrary arguments besides default first argument.\n\nOnly rarely will you have to worry about __new__. Usually, you'll just define __init__ and let the default __new__ pass the constructor arguments to it.\n\nsel... | [
63
] | [] | [] | [
"class",
"python"
] | stackoverflow_0008106900_class_python.txt |
Q:
filtering input from serial port data
I am very very new to Python and I could use your help.
I made a small program that reads an analog signal from the serial port and dumps it into a file. However, even though the reading is very precise, sometimes it dumps unnecessary/undetermined characters into the file:
Thi... | filtering input from serial port data | I am very very new to Python and I could use your help.
I made a small program that reads an analog signal from the serial port and dumps it into a file. However, even though the reading is very precise, sometimes it dumps unnecessary/undetermined characters into the file:
This is a dump from a 500 line file; check the... | [
"To make the job in a simple way (ie without regular expression ;) ) try this : \ndef purifystring(string_to_analyze): # string is a really bad variable name as it is a python module's name\n return \"\".join(digit for digit in string_to_analyze if digit.isdigit())\n\nthis way, you will filter only the digits ... | [
1
] | [] | [] | [
"input_filtering",
"python",
"regex",
"serial_port"
] | stackoverflow_0008106957_input_filtering_python_regex_serial_port.txt |
Q:
How to store a string containing both single quote( ' ) and double quote( " ) in python
(+CMGL: 2,"REC READ","DD-Etopup",,"11/11/04,12:48:51+22" Hye! How's it going?)
I want to store this sms message in python as a string. How can I do this?
A:
Triple quotes - this will allow embedded single and double-quotes... | How to store a string containing both single quote( ' ) and double quote( " ) in python | (+CMGL: 2,"REC READ","DD-Etopup",,"11/11/04,12:48:51+22" Hye! How's it going?)
I want to store this sms message in python as a string. How can I do this?
| [
"Triple quotes - this will allow embedded single and double-quotes without escape characters.\ns = \"\"\"(+CMGL: 2,\"REC READ\",\"DD-Etopup\",,\"11/11/04,12:48:51+22\" Hye! How's it going?)\"\"\"\n\n",
"Backslash escaping is the quick answer: \n>>> '(+CMGL: 2,\"REC READ\",\"DD-Etopup\",,\"11/11/04,12:48:51+22\" H... | [
3,
2
] | [] | [] | [
"escaping",
"python"
] | stackoverflow_0008107103_escaping_python.txt |
Q:
Extracting relationship status from Facebook in Python running on Google App Engine
I'm working on a Facebook application. It's written in Python and running on Google App Engine (GAE).
I know how to get the relationship status of the users network, but the way I do it is running way to slow. There is a time limit... | Extracting relationship status from Facebook in Python running on Google App Engine | I'm working on a Facebook application. It's written in Python and running on Google App Engine (GAE).
I know how to get the relationship status of the users network, but the way I do it is running way to slow. There is a time limit on GAE in order to reduce CPU usage which is about 60 seconds. Using the following code ... | [
"Each app engine instance can have have max 10 parallel HTTP queries, so you could potentially make this 10 times faster with create_rpc & make_fetch_call. There are scenarios where this doesn't work either, so you need to split the job to several tasks and let them run in parallel. \n",
"You can use the facebook... | [
2,
2
] | [] | [] | [
"facebook",
"facebook_graph_api",
"google_app_engine",
"python"
] | stackoverflow_0008107007_facebook_facebook_graph_api_google_app_engine_python.txt |
Q:
Using Python-Requests Library to Post a Text File
Hi I'm having trouble posting a text file using the Python Requests Library ( http://docs.python-requests.org/en/latest/index.html ), can you let me know what I'm doing wrong?
I tried searching for related questions and found this Send file using POST from a Pytho... | Using Python-Requests Library to Post a Text File | Hi I'm having trouble posting a text file using the Python Requests Library ( http://docs.python-requests.org/en/latest/index.html ), can you let me know what I'm doing wrong?
I tried searching for related questions and found this Send file using POST from a Python script but it doesn't answer my question.
Here's my c... | [
"The files parameter expects a dict of a filename matching to a file-handler. This is described in the source code (currently line 69):\nGithub Source (requests/models.py)\n#: Dictionary of files to multipart upload (``{filename: content}``).\nself.files = files\n\nSometimes the best documentation is the code.\nYou... | [
5
] | [] | [] | [
"http_request",
"post",
"python",
"python_requests"
] | stackoverflow_0008107177_http_request_post_python_python_requests.txt |
Q:
Classes 2d lists in python
I have a 2d list and a class to get users input and compare that object to what is stored.
For testing purposes it prints the coordinate and its equal to A but it ignores the if statement by not adding to the count.
Why is it ignoring the if statement
this is my current code
count =0
pri... | Classes 2d lists in python | I have a 2d list and a class to get users input and compare that object to what is stored.
For testing purposes it prints the coordinate and its equal to A but it ignores the if statement by not adding to the count.
Why is it ignoring the if statement
this is my current code
count =0
print self.object[row][col]
if self... | [
"I know nothing about the type of self.object[row][col] and type matters, as clearly visible below:\n>>> 1 == \"1\"\nFalse\n\nThus, by guessing, you can try the following comparisons, converting your variable into appropriate type before comparison:\n\nconverting to string:\nif str(self.object[row][col]) == \"1\":\... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0008107205_python.txt |
Q:
Why doesn't this loop break?
Python noob; please explain why this loop doesn't exit.
for i in range(0,10):
print "Hello, World!"
if i == 5: i = 15
print i
next
regards
A:
Because what you have done with range(0,10) is created an array of 10 elements like so:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
and you are goin... | Why doesn't this loop break? | Python noob; please explain why this loop doesn't exit.
for i in range(0,10):
print "Hello, World!"
if i == 5: i = 15
print i
next
regards
| [
"Because what you have done with range(0,10) is created an array of 10 elements like so:\n1, 2, 3, 4, 5, 6, 7, 8, 9, 10\n\nand you are going through each one.\nIn other programming languages, you are doing what is called a foreach loop. \nOtherwise, do it another way.\n",
"Because Python's for loop doesn't count,... | [
5,
5,
3,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008107285_python.txt |
Q:
How to write to localStorage and post textarea with one click?
I have a handler /choice with a textarea field and /choicehandler that writes the information returned to database. But before posting the form I want to write a user name to localStorage.
This is the form:
<form name="choice_form" action="/choicehandl... | How to write to localStorage and post textarea with one click? | I have a handler /choice with a textarea field and /choicehandler that writes the information returned to database. But before posting the form I want to write a user name to localStorage.
This is the form:
<form name="choice_form" action="/choicehandler" method="post">
<textarea name="choice" rows="7" cols="50"></te... | [
"you can change your function a bit (lots of ways to do this). Add an Id to your form (id=\"choice_form\"), then add a line that submits your form:\nfunction writeToStorage() { \n user = \"user\" + count; \n count++; \n localStorage.setItem(\"chooser\", user); \n document.getElementById(\"ch... | [
1,
1
] | [] | [] | [
"html",
"javascript",
"python"
] | stackoverflow_0008107351_html_javascript_python.txt |
Q:
CRC check corrupted BZ2
Is there a way to check the CRC validity of a BZ2 file in python?
I'm using it to check a PNG in a corrupted BZ2 file
Thank you
A:
Instead of checking for a corrupted file, assume it is intact:
import bz2
try:
bz2.BZ2File(zipFile).read()
print 'Intact'
except IOError:
print 'Corrup... | CRC check corrupted BZ2 | Is there a way to check the CRC validity of a BZ2 file in python?
I'm using it to check a PNG in a corrupted BZ2 file
Thank you
| [
"Instead of checking for a corrupted file, assume it is intact:\nimport bz2\n\ntry:\n bz2.BZ2File(zipFile).read()\n print 'Intact'\nexcept IOError:\n print 'Corrupted'\n\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0008107481_python.txt |
Q:
Python 24 bit Stream not giving a right value?
I am converting 3 letters into their ASCII binary notation and then incrementing the first letter by 16 places, the second letter by 8 places, and the last is staying where it is, so that when the 24 bit stream is configured, the first 8 bit places represents the firs... | Python 24 bit Stream not giving a right value? | I am converting 3 letters into their ASCII binary notation and then incrementing the first letter by 16 places, the second letter by 8 places, and the last is staying where it is, so that when the 24 bit stream is configured, the first 8 bit places represents the first letter, the next 8 the middle letter and the last ... | [
"Looks like you're missing an & 0xff:\ncbk1 = ((chr(bk1>>16)) + (chr((bk1>>8) & 0xff)) + (chr(bk1&0xFF)))\n\nyields the correct answer. When reshifting back you need to mask out the upper bits as well because the bits set by the first character (shifted by 16 bit) will still be there.\n",
"This happens because yo... | [
1,
1,
0
] | [] | [] | [
"block_cipher",
"python"
] | stackoverflow_0008107547_block_cipher_python.txt |
Q:
How to have a versatile function call that can call different functions in Python?
I'm trying to make a text-based game in Python, however, code could get out of hand pretty quickly if I can't do one thing on one line.
First, the source code:
from sys import exit
prompt = "> "
inventory = []
def menu():
whil... | How to have a versatile function call that can call different functions in Python? | I'm trying to make a text-based game in Python, however, code could get out of hand pretty quickly if I can't do one thing on one line.
First, the source code:
from sys import exit
prompt = "> "
inventory = []
def menu():
while True:
print "Enter \"start game\" to start playing."
print "Enter \"pa... | [
"elif location != \"default\" and item != \"nothing\":\n print \"You picked up %s.\" % item\n inventory.append(item)\n location()\nelif location != \"default\" and item == \"nothing\":\n print \"You enter the room.\"\n location()\n\nI guess you want to call a function having its name. For that you ne... | [
1,
0,
0
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0008107203_python_python_2.7.txt |
Q:
Eventlets and SMTP
I would like to multithread sending mail (using django's SMTPConnection or perhaps the smtplib module). I was hoping there was a module similar to urllib2 where I can:
import eventlet
from eventlet.green import urllib2
except using smtplib instead of the urllib2 import. However, this does to ... | Eventlets and SMTP | I would like to multithread sending mail (using django's SMTPConnection or perhaps the smtplib module). I was hoping there was a module similar to urllib2 where I can:
import eventlet
from eventlet.green import urllib2
except using smtplib instead of the urllib2 import. However, this does to appear to supported. I ... | [
"Use\nimport eventlet\neventlet.monkey_patch()\nimport module\n\nOr\nmodule = eventlet.import_patched(module)\n\nEither should work for you.\nhttp://eventlet.net/doc/patching.html\n"
] | [
1
] | [] | [] | [
"django",
"eventlet",
"python",
"smtplib"
] | stackoverflow_0008107825_django_eventlet_python_smtplib.txt |
Q:
How to extract money value from "grossing" string in IMDbPY
I would like to extract a money value when using IMDbPY to extract datas from IMDB.
My problem is that IMDbPY returns results in the following format, what is a unicode string:
In : movie['business']['gross'][0]
Out: u'$134,966,411 (USA) (11 May 1997)'
A... | How to extract money value from "grossing" string in IMDbPY | I would like to extract a money value when using IMDbPY to extract datas from IMDB.
My problem is that IMDbPY returns results in the following format, what is a unicode string:
In : movie['business']['gross'][0]
Out: u'$134,966,411 (USA) (11 May 1997)'
Also, the date is sometimes present, sometimes not.
Can you help m... | [
"re.match with this pattern:\nr\"\\$([1-9][0-9,]+)\"\n\n"
] | [
0
] | [] | [] | [
"imdbpy",
"numbers",
"python",
"regex",
"string"
] | stackoverflow_0008107925_imdbpy_numbers_python_regex_string.txt |
Q:
How can I create an empty variable based on another data type in Python?
How can I create empty variable that has the same data type of another variable?
data = get_data()
new_variable = data.data_type() #just create empty variable
In the above case, if data is a list then new_variable will be list()
A:
... | How can I create an empty variable based on another data type in Python? | How can I create empty variable that has the same data type of another variable?
data = get_data()
new_variable = data.data_type() #just create empty variable
In the above case, if data is a list then new_variable will be list()
| [
"Get the class of the value, invoke the constructor with no arguments, and hope that it doesn't blow up.\ndata.__class__()\n\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0008107964_python.txt |
Q:
How do I update a label with an image in tkinter in python?
I have a dropdown menu with a couple of choices and a label with an image in it.
I would like to change the image according to the choice selected from the dropdown menu,but i cant figure it out.
Example code:
from Tkinter import*
import Tkinter as tk
de... | How do I update a label with an image in tkinter in python? | I have a dropdown menu with a couple of choices and a label with an image in it.
I would like to change the image according to the choice selected from the dropdown menu,but i cant figure it out.
Example code:
from Tkinter import*
import Tkinter as tk
def image():
list1=['im1.gif','im2.gif']
studDropDown['menu... | [
"Here is a simple example based of the code you provided:\nfrom Tkinter import *\n\ndef change_image(*args):\n # Change image of label accordingly\n label.config(image=photos[int(studFiles.get())])\n\napp = Tk()\napp.title(\"Example\")\napp.geometry('500x200+200+200')\napp.configure(background='black')\napp.r... | [
7
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0008107024_python_tkinter.txt |
Q:
Standalone Python web server and/or nginx
So I've done some reading about Python web frameworks (or servers?), mostly Tornado and Bottle but also FAPWS3, and there are still some grey areas.
First, these three web frameworks are all said to be fast, yet they all include a web server written in Python (except FAPWS... | Standalone Python web server and/or nginx | So I've done some reading about Python web frameworks (or servers?), mostly Tornado and Bottle but also FAPWS3, and there are still some grey areas.
First, these three web frameworks are all said to be fast, yet they all include a web server written in Python (except FAPWS3) which should be put behind nginx/Apache. Isn... | [
"First of, Tornado and FAPWS3 are web servers, while Bottle is a web framework. Those belong to completely different categories. \nWeb frameworks are usually run as a WSGI server behind a HTTP (\"web\") proxy. The HTTP server included in most frameworks is only there for fast development and deployment and easy dep... | [
8
] | [] | [] | [
"bottle",
"nginx",
"python",
"tornado",
"webserver"
] | stackoverflow_0008107986_bottle_nginx_python_tornado_webserver.txt |
Q:
access to generic form field in template
I have a form with generic fields
forms.py
class OfferForm(forms.ModelForm):
class Meta:
model=Offer
some_views.py
def add_field(request):
form = OfferForm()
#some logic here
for x in list:
form.fields[x]=forms... | access to generic form field in template | I have a form with generic fields
forms.py
class OfferForm(forms.ModelForm):
class Meta:
model=Offer
some_views.py
def add_field(request):
form = OfferForm()
#some logic here
for x in list:
form.fields[x]=forms.ModelChoiceField(queryset=some_query)
... | [
"I see you are intended to do and here my reply. You should adapt your code to django and not django to your code. In this way, to solve your issue, the 'prefix' form resource is the right option:\nYou can put several Django forms inside one tag. To give each Form its own namespace, use the prefix keyword argument... | [
0
] | [] | [] | [
"django",
"python",
"templates"
] | stackoverflow_0008105803_django_python_templates.txt |
Q:
Extracting text from SMS message in Python
This is an SMS message which I obtained using AT commands from mobile:
+CMGL: 24,"REC READ","DD-655501",,"11/11/10,17:10:26+22"
hey is it working "BBC news channel" pack @ Rs.10, Dial *234*7514#
Now I need to extract only the text message from it. I have tried a few app... | Extracting text from SMS message in Python | This is an SMS message which I obtained using AT commands from mobile:
+CMGL: 24,"REC READ","DD-655501",,"11/11/10,17:10:26+22"
hey is it working "BBC news channel" pack @ Rs.10, Dial *234*7514#
Now I need to extract only the text message from it. I have tried a few approaches but something always gets missed. I am u... | [
"The format of the response is:\n\n+CMGL: index,message_status,address,[address_text],[service_center_time_stamp][,address_type,sms_message_body_length]\nsms_message_body\n\n(source)\nYou want all the text apart from the first line.\nmessage_body = smsText[smsText.index('\\r\\n') + 2:]\n\n"
] | [
1
] | [] | [] | [
"python",
"sms"
] | stackoverflow_0008108106_python_sms.txt |
Q:
I don't understand why this loop terminates the way it does
checkSql = 'SELECT userid FROM bs_members WHERE userid = :checkUser'
doesUserExist = False
while True:
doesUserExist = False
newUser.userID = ga.getInput('Enter userID: ', "\w+$")
checkUserID = ds.execute(checkSql,checkUser=newUser.userID)
... | I don't understand why this loop terminates the way it does | checkSql = 'SELECT userid FROM bs_members WHERE userid = :checkUser'
doesUserExist = False
while True:
doesUserExist = False
newUser.userID = ga.getInput('Enter userID: ', "\w+$")
checkUserID = ds.execute(checkSql,checkUser=newUser.userID)
for row in ds:
if row == checkUserID:
doesUs... | [
"Your custom execute method doesn't return anything meaning that checkUserID in your code will be None.\nFurthermore, what you're interested in is if there's at least one row returned by the query. If there are none then the userID should be available.\nThe docs say that calling .fetchone() returns None if no more ... | [
4,
0
] | [] | [] | [
"cx_oracle",
"loops",
"python"
] | stackoverflow_0008107979_cx_oracle_loops_python.txt |
Q:
How can I switch between 2 characters?
I am using python 2.7 and i'm trying to find a solution to this problem,
when i get a string from a certain function
i need to switch between the first and the last character.
for example if the string is "hello" it should return as "oellh"
slicing won't work and i cant jus... | How can I switch between 2 characters? | I am using python 2.7 and i'm trying to find a solution to this problem,
when i get a string from a certain function
i need to switch between the first and the last character.
for example if the string is "hello" it should return as "oellh"
slicing won't work and i cant just replace the characters like i will normall... | [
"s[-1] + s[1:-1] + s[0] if len(s) > 1 else s\n\nThis will swap everything except for the edge cases of '' and 'a' (single char).\nThe snippet of code below slices the string into three chunks. The end chunks swap the first and last letters while the middle chunk grabs the middle of the string.\n s[-1] + s[1:-1] + ... | [
5,
4,
0
] | [
"SINGLE LINE SOLUTION\nRegexes are not as efficient as string replacements, but it should not make a big difference for short strings.\n>>> s = 'hello'\n>>> print re.sub('^(.)(.*?)(.)$',r'\\3\\2\\1',s)\n'oellh'\n\n"
] | [
-2
] | [
"python"
] | stackoverflow_0008086320_python.txt |
Q:
tweepy/twitter get all tweets from a location:
I have the following questions about tweepy python module
1.I am trying to retrieve all tweets for a specific location. I am able to do this by using tweepy python module (streaming API), but I get only those tweets whose geo locations are enabled, which means I would... | tweepy/twitter get all tweets from a location: | I have the following questions about tweepy python module
1.I am trying to retrieve all tweets for a specific location. I am able to do this by using tweepy python module (streaming API), but I get only those tweets whose geo locations are enabled, which means I would loose rest of the tweeter’s tweet who have not enab... | [
"If tweepy doesn't have a feature you need, you can always access Twitter directly with an HTTP request. The full Twitter REST API is described here: https://dev.twitter.com/docs/api\nThe ones that seem relevant to your interest are:\n\nGET trends/:woeid which looks up tweets by woeid, a Yahoo Identifier for coll... | [
4
] | [] | [] | [
"api",
"python",
"tweepy",
"twitter"
] | stackoverflow_0008108019_api_python_tweepy_twitter.txt |
Q:
For each member of a list, write it to a separate file, python
I have a list of length n. Each item of the list need to be written to n .txt files. For some reason the following, basic approach isn't working for me:
for item in lst:
for i in range(len(lst)):
write_to_me = open('list_item_%i.txt' %i... | For each member of a list, write it to a separate file, python | I have a list of length n. Each item of the list need to be written to n .txt files. For some reason the following, basic approach isn't working for me:
for item in lst:
for i in range(len(lst)):
write_to_me = open('list_item_%i.txt' %i, 'w')
write_to_me.write(item)
The file names are fine ('... | [
"Don't use nested loops. Use enumerate to get both the index and the item:\n for i, item in enumerate(lst):\n write_to_me = open('list_item_{0}.txt'.format(i), 'w') \n write_to_me.write(item)\n write_to_me.close()\n\nSidenote: Don't forget to close the files when you have finished using them!\n"
] | [
1
] | [] | [] | [
"file_io",
"list",
"python"
] | stackoverflow_0008108612_file_io_list_python.txt |
Q:
Making an android Python service to run in suspend state
Here's my Python script written using android-scripting:
import android, time
droid = android.Android()
interval = 1 # every 1 minute
while True:
# define your own vibrate pattern here
droid.vibrate(200)
time.sleep(0.3)
droid.vibrate(300)
... | Making an android Python service to run in suspend state | Here's my Python script written using android-scripting:
import android, time
droid = android.Android()
interval = 1 # every 1 minute
while True:
# define your own vibrate pattern here
droid.vibrate(200)
time.sleep(0.3)
droid.vibrate(300)
time.sleep(60*interval)
It basically vibrates every minut... | [
"The scripting environment is definitely a second-class citizen. What you want is called the AlarmManager, using ELAPSED_REALTIME. If that's not available for the scripting environment, you're stuck.\nThe scripting environment is not, at least currently, intended to be a full replacement for the development kit e... | [
10,
2,
1
] | [
"I don't know much about Python binding, so I am going to answer as general Android issue. See Power Management.\nPARTIAL_WAKE_LOCK sounds interesting: \"Wake lock that ensures that the CPU is running. The screen might not be on.\"\n\nExploring a Wake Lock Example\nAll power management calls follow the same\n basi... | [
-1,
-2
] | [
"android",
"android_scripting",
"python"
] | stackoverflow_0002076381_android_android_scripting_python.txt |
Q:
Change elements in 2d ndarray into arrays
In numpy, I have a 2d array like:
[
[1 2 3 4 5]
[2 3 1 4 5]
.....
[3 5 2 3 5]
]
I want to replace each element in this array into a 1d array, e.g.
1 -> [0 0 0 0 1]
2 -> [0 0 0 1 0]
etc.
This will convert elements into arrays, and the whole 2d array into a 3d array.
I... | Change elements in 2d ndarray into arrays | In numpy, I have a 2d array like:
[
[1 2 3 4 5]
[2 3 1 4 5]
.....
[3 5 2 3 5]
]
I want to replace each element in this array into a 1d array, e.g.
1 -> [0 0 0 0 1]
2 -> [0 0 0 1 0]
etc.
This will convert elements into arrays, and the whole 2d array into a 3d array.
I tried few things, but nothing worked. What sho... | [
"Suppose this is your 2d array:\nx=np.random.randint(1,3,size=(3,2))\nprint(x)\n\n# [[2 2]\n# [1 2]\n# [2 1]]\n\nCreate the array:\ny=np.array([[0,0,0,0,0],[0,0,0,0,1],[0,0,0,1,0]])\n\nYou can look upon this array as a mapping:\n0 --> [0,0,0,0,0] # y[0] is mapped to [0,0,0,0,0]\n1 --> [0,0,0,0,1] # y[1] ... | [
4
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0008108649_numpy_python.txt |
Q:
Python, why does this sum function not work
Why does this sum function not work? It's intent is to sum the variable items in a list
def sum_list (a_list):
length= len(a_list)
counter = 0
total= 0
while(counter < length):
(a_list[counter] +total)
... | Python, why does this sum function not work | Why does this sum function not work? It's intent is to sum the variable items in a list
def sum_list (a_list):
length= len(a_list)
counter = 0
total= 0
while(counter < length):
(a_list[counter] +total)
total = total + counter
counter = c... | [
"First, length is not defined anywhere, but you are trying to use it in the while condition. That would cause the error you are probably seeing. The length of your list can be obtained with len(list).\nSecond, your while body isn't actually using the list values: (list[counter] +total) isn't doing anything, as it... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0008108954_python.txt |
Q:
gcc-4.0 failed on mac 10.6.8 while installing Scrapy how can i overcome this?
I used pip install Scrapy on my mac 10.6.8 and i get the error below
can anyone help me please?
creating build/lib.macosx-10.3-fat-2.7/twisted/internet/iocpreactor/iocpsupport
copying twisted/internet/iocpreactor/iocpsupport/iocpsupport... | gcc-4.0 failed on mac 10.6.8 while installing Scrapy how can i overcome this? | I used pip install Scrapy on my mac 10.6.8 and i get the error below
can anyone help me please?
creating build/lib.macosx-10.3-fat-2.7/twisted/internet/iocpreactor/iocpsupport
copying twisted/internet/iocpreactor/iocpsupport/iocpsupport.c ->
build/lib.macosx-10.3-fat-2.7/twisted/internet/iocpreactor/iocpsupport
copyi... | [
"It appears you have installed Xcode 4 which removed the gcc-4.0 used to build the Python 2.7 you have installed. From the path names in the traceback, chances are that was a 32-bit-only Python downloaded from python.org. With Xcode 4, you should try installing the latest 64-bit/32-bit OS X installer for Python 2... | [
2,
0
] | [] | [] | [
"pip",
"python",
"scrapy"
] | stackoverflow_0008105897_pip_python_scrapy.txt |
Q:
Python passing variable into thread
I'm using the threading module to control threads that send data through sockets and what not, however I can't find a suitable solution to pass data into the thread to work with. I've tried things such as Overriding python threading.Thread.run() but can't seem to get it working.... | Python passing variable into thread | I'm using the threading module to control threads that send data through sockets and what not, however I can't find a suitable solution to pass data into the thread to work with. I've tried things such as Overriding python threading.Thread.run() but can't seem to get it working. If anyone has any suggestions I'd be hap... | [
"You are thinking about this backwards. Forget about the fact that it happens to be a thread that's sending the data through the sockets. The data doesn't need to get to the thread, it needs to get to the logic that sends data on the socket.\nFor example, you can have a queue that holds things that need to be sent ... | [
2,
1
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0008109087_multithreading_python.txt |
Q:
Calling dir() in Python
What object is being queried when I call dir() in Python's interpreter?
I'm playing with a package that I want to be able to get the names for functions from the global dictionary. I thought that it would be dir(__global) but that wasn't it, nor was dir(sys.modules).
If I type dir() into a... | Calling dir() in Python | What object is being queried when I call dir() in Python's interpreter?
I'm playing with a package that I want to be able to get the names for functions from the global dictionary. I thought that it would be dir(__global) but that wasn't it, nor was dir(sys.modules).
If I type dir() into a fresh interpreter session it... | [
"dir() returns names in the current scope. I can't remember now if it's exactly equivalent to locals().keys(), or are there any differences.\n",
"Re-reading your question 8 years later, I now wonder if you are asking about dir() run interactively at the Python prompt, a situation which I and the other answers ent... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0008109066_python.txt |
Q:
Python if/elif issue with random.randint
This is part of a bigger problem, but I'm having some problems with this if/elif function.
def fish():
import random
score = 0
i = random.randint(0,39)
if i == [0,19]:
print("You caught nothing!")
elif i == [20,39]:
print("You caug... | Python if/elif issue with random.randint | This is part of a bigger problem, but I'm having some problems with this if/elif function.
def fish():
import random
score = 0
i = random.randint(0,39)
if i == [0,19]:
print("You caught nothing!")
elif i == [20,39]:
print("You caught a Minnow! +10 points.")
score += 10... | [
"Yeah, um... that's not how it works. You're comparing an integer to a list.\n if 0 <= i < 20:\n print(\"You caught nothing!\")\n elif 20 <= i < 40:\n print(\"You caught a Minnow! +10 points.\")\n score += 10\n\n",
"You're comparing an integer to a list.\nTo do what you're trying to do,... | [
6,
1,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008109288_python_python_3.x.txt |
Q:
Trac spawning for nginx deployement without using tracd
I am trying to run Trac on nginx.
There is a simple solution that consists of running the tracd server, but I'm trying to avoid that. It doesn't support unix sockets.
Instead, I'm trying to use Spawning that should be able to launch any WSGI application.
But ... | Trac spawning for nginx deployement without using tracd | I am trying to run Trac on nginx.
There is a simple solution that consists of running the tracd server, but I'm trying to avoid that. It doesn't support unix sockets.
Instead, I'm trying to use Spawning that should be able to launch any WSGI application.
But I don't know how to use it. After deplyement, I have my cgi-b... | [
"Reading Spawning docs I saw that it receives on the command line, as the first parameter, the dotted name of your application's WSGI object. Especifically for Trac, the WSGI object is defined at trac.web.main.dispatch_request [1]. Try passing this to Spawning.\nBut remember that Trac needs some environ variables i... | [
2
] | [] | [] | [
"python",
"spawning",
"trac",
"wsgi"
] | stackoverflow_0008108539_python_spawning_trac_wsgi.txt |
Q:
Can't install SQLAlchemy
I've been trying to install SQLAlchemy for a project. I've tried 3 different computers running Windows 7, Vista, and 7 with identical python32 installations. My first issue was an inability to execute easy_install on any of these computers for different reasons. Next, running the include... | Can't install SQLAlchemy | I've been trying to install SQLAlchemy for a project. I've tried 3 different computers running Windows 7, Vista, and 7 with identical python32 installations. My first issue was an inability to execute easy_install on any of these computers for different reasons. Next, running the included setup.py script didn't work,... | [
"First of all, don't use easy_install. pip is much more reliable.\nTry installing it and see how things go: How do I install pip on Windows?\nThen, just install your package (search for cmd in the Search Bar on the Start Menu and run it as an Administrator):\npip install sqlalchemy\n\n"
] | [
9
] | [] | [] | [
"installation",
"python",
"sqlalchemy"
] | stackoverflow_0008109678_installation_python_sqlalchemy.txt |
Q:
Python - Search for Word In Line, Count it, Add It
I'm pretty sure I'm over thinking this and there's a simple outcome for it, but I just can't seem to put it all together.
I'm looking for a kind of a search method. I'd like a Python script search a text file for a keyword and count how many lines it appears on. T... | Python - Search for Word In Line, Count it, Add It | I'm pretty sure I'm over thinking this and there's a simple outcome for it, but I just can't seem to put it all together.
I'm looking for a kind of a search method. I'd like a Python script search a text file for a keyword and count how many lines it appears on. Though if the keyword comes up on a single line multiple ... | [
"You can define the following function.\ndef lcount(keyword, fname):\n with open(fname, 'r') as fin:\n return sum([1 for line in fin if keyword in line])\n\nNow if you want to know the number of lines containing \"int\" in \"foo.cpp\", you do:\nprint lcount('int', 'foo.cpp')\n\nAn alternative that you can... | [
4,
0,
0,
0
] | [] | [] | [
"find",
"lines",
"python",
"search",
"text"
] | stackoverflow_0008109713_find_lines_python_search_text.txt |
Q:
Compare values in two strings and then yield a result that can be placed in an array
I have two strings in python that I have converted to lists:
Seq1 = [x1,x2,x3,x4]
Seq2 = [y1,y2,y3,y4]
The strings are the same length and are composed of only the letters 'a', 'c', 'g', and 'u'.
Then I created an empty matrix l... | Compare values in two strings and then yield a result that can be placed in an array | I have two strings in python that I have converted to lists:
Seq1 = [x1,x2,x3,x4]
Seq2 = [y1,y2,y3,y4]
The strings are the same length and are composed of only the letters 'a', 'c', 'g', and 'u'.
Then I created an empty matrix len(Seq1) by len(Seq2):
a = numpy.zeros(shape=len(Seq1),len(Seq2))
Next, I want to compare... | [
"Iterate over both lists and compare:\nfor x in range(len(Seq1)):\n for y in range(len(Seq2)):\n a[x, y] = (Seq1[x] == Seq2[y])\n\n",
"I assume that this is a bioinformatics question. The purpose, however, is unclear to me. I've listed a generic matching system that you can use.\n>>> for s1 in xrange(len(seq1... | [
1,
0,
0,
0
] | [] | [] | [
"arrays",
"compare",
"python",
"string"
] | stackoverflow_0008109755_arrays_compare_python_string.txt |
Q:
How to disable auto-swapping in axes labels in matplotlib?
Using matplotlib in Python I drew a 3D graph. When I rotate the graph I noticed that the axes labels swap automatically which does not look interesting or helping to me. In fact it disturbs my focusing on the purpose of rotation which is to explore visuall... | How to disable auto-swapping in axes labels in matplotlib? | Using matplotlib in Python I drew a 3D graph. When I rotate the graph I noticed that the axes labels swap automatically which does not look interesting or helping to me. In fact it disturbs my focusing on the purpose of rotation which is to explore visually the presented data.
Q: How to disable auto-swapping axes label... | [
"I grabbed some ideas from SO, examined many and finally developed the following solution. It simply works.\n\nfrom __future__ import division\nimport scipy as sp\nimport mpl_toolkits.mplot3d as a3d\nimport pylab as pl\n\nnan = sp.nan\n\ndef axesoff():\n box = [[-1,1,1,-1,-1,1,1,-1,-1,-1,nan,1,1,nan,1,1,nan,-1,-... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008026399_matplotlib_python.txt |
Q:
How do I configure mod_wsgi with python that has been built from source code?
I want to build mod_wsgi against a Python which I have built myself from source code in Ubuntu. (You can see specifically how I built it in How would I build python myself from source code on Ubuntu?)
I tried running this from within the... | How do I configure mod_wsgi with python that has been built from source code? | I want to build mod_wsgi against a Python which I have built myself from source code in Ubuntu. (You can see specifically how I built it in How would I build python myself from source code on Ubuntu?)
I tried running this from within the mod_wsgi-3.3 directory:
$ sudo ./configure --with-apxs=/usr/local/apache2/bin/apxs... | [
"Instead of\n./configure --with-apxs=/usr/local/apache2/bin/apxs --with-python=/usr/local/share/man/man1/python2.7.1\n\nI would assume you would want to use:\n./configure --with-apxs=/usr/local/apache2/bin/apxs --with-python=/usr/local/bin/python2.7.1\n\nI think you want to tell mod_wsgi to use the path to the pyth... | [
2,
1
] | [] | [] | [
"django",
"mod_wsgi",
"python",
"ubuntu"
] | stackoverflow_0008109354_django_mod_wsgi_python_ubuntu.txt |
Q:
python - regex search and findall
I need to find all matches in a string for a given regex. I've been using findall() to do that until I came across a case where it wasn't doing what I expected. For example:
regex = re.compile('(\d+,?)+')
s = 'There are 9,000,000 bicycles in Beijing.'
print re.search(regex, s).gr... | python - regex search and findall | I need to find all matches in a string for a given regex. I've been using findall() to do that until I came across a case where it wasn't doing what I expected. For example:
regex = re.compile('(\d+,?)+')
s = 'There are 9,000,000 bicycles in Beijing.'
print re.search(regex, s).group(0)
> 9,000,000
print re.findall(re... | [
"Ok, I see what's going on... from the docs:\n\nIf one or more groups are present in the pattern, return a list of groups; \n this will be a list of tuples if the pattern has more than one group.\n\nAs it turns out, you do have a group, \"(\\d+,?)\"... so, what it's returning is the last occurrence of this gro... | [
19,
7
] | [] | [] | [
"findall",
"python",
"regex",
"search",
"string_matching"
] | stackoverflow_0008110059_findall_python_regex_search_string_matching.txt |
Q:
Updating the list by adding the interest rate [Python]
I just started learning Python and I am having a problem wring a specific function. Basically, this function should update the list by adding the interest rate.
lst = [[25, 10, 300], [7, 30, 80], [7, 530, 24],[65, 30, 2]]
rate = [0.5, 0.02, 0.15]
Output:
[37.... | Updating the list by adding the interest rate [Python] | I just started learning Python and I am having a problem wring a specific function. Basically, this function should update the list by adding the interest rate.
lst = [[25, 10, 300], [7, 30, 80], [7, 530, 24],[65, 30, 2]]
rate = [0.5, 0.02, 0.15]
Output:
[37.5, 10.2, 345.0]
[10.5, 30.6, 92.0]
[10.5, 540.6, 27.6]
[97.5... | [
"lst[i] is a list of numbers, not a number itself. You can't multiply a list of numbers by a number, but you can multiply the elements in the list by the number.\n",
"You're indexing into both lst and rate with the loop variable i -- but one list has four elements and the other list has three elements. You're eit... | [
3,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008110285_python.txt |
Q:
Using haystack with Whoosh
Requires setting HAYSTACK_WHOOSH_PATH to the place on your filesystem where the Whoosh index should be located.
Can anyone explain where exactly this path is pointing? I mean what should i give in this path?
A:
Any directory you wish. You can use this configuration:
import os, sys
PRO... | Using haystack with Whoosh | Requires setting HAYSTACK_WHOOSH_PATH to the place on your filesystem where the Whoosh index should be located.
Can anyone explain where exactly this path is pointing? I mean what should i give in this path?
| [
"Any directory you wish. You can use this configuration:\nimport os, sys\nPROJECT_ROOT = os.path.dirname(__file__)\nHAYSTACK_WHOOSH_PATH = os.path.join(PROJECT_ROOT, 'search_index')\n\n",
"Any directory where you have write access will do, as long as its filesystem has enough space to store the Whoosh index,... | [
3,
1
] | [] | [] | [
"django",
"django_haystack",
"python",
"whoosh"
] | stackoverflow_0008108170_django_django_haystack_python_whoosh.txt |
Q:
django: passing parameters in URLConf
I want to have this URL:
/weibo_login/?app=first
I want the URLConf to call my view function with parameters but I don't know how to write the URL dispatcher to pass 'app=first' to the view function. The original URLConf:
urlpatterns += patterns('',
(r'weibo_login/', 'weibo.vi... | django: passing parameters in URLConf | I want to have this URL:
/weibo_login/?app=first
I want the URLConf to call my view function with parameters but I don't know how to write the URL dispatcher to pass 'app=first' to the view function. The original URLConf:
urlpatterns += patterns('',
(r'weibo_login/', 'weibo.views.mylogin'),
The view function:
def mylo... | [
"In your view you should write sth like this:\ndef mylogin(request):\n app = request.GET.get('app')\n ...\n\nURLconf stays same as you posted.\nGenerally you don't handle GET parameters in URLconf - this is job for views.\n"
] | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008110161_django_python.txt |
Q:
Python UnicodeEncodeError using PyCrypto on App Engine
I'm trying to pass an encrypted query string to another URL.
The following code gives me this error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u04b7' in
position 7: ordinal not in range(128)
The encryption module is PyCrypto
Running Pytho... | Python UnicodeEncodeError using PyCrypto on App Engine | I'm trying to pass an encrypted query string to another URL.
The following code gives me this error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u04b7' in
position 7: ordinal not in range(128)
The encryption module is PyCrypto
Running Python 2.5.2 on App Engine
PAGE A
import Crypto
from Cryp... | [
"General guidelines: add base64 encoding/decoding step in your encrypted stuff.\nimport base64\n\nbase64_encrypted_message = base64.b64encode(encrypted_message)\n// send your message via POST as GET can be seen on system logs\n\nencrypted_message = base64.b64decode(base64_encrypted_message)\n// decrypt your message... | [
6,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008108277_google_app_engine_python.txt |
Q:
MATPLOTLIB X-AXIS AND Y-AXIX tick background and font color
I was wondering if is there a way to change the background color of the x-axis tick and y-axis tick background and font color.
For instance in the example in this link, you can see that the x-axis(0,2,4,5..), and y-axis(12,10,8,6..) font color are black f... | MATPLOTLIB X-AXIS AND Y-AXIX tick background and font color | I was wondering if is there a way to change the background color of the x-axis tick and y-axis tick background and font color.
For instance in the example in this link, you can see that the x-axis(0,2,4,5..), and y-axis(12,10,8,6..) font color are black for the tickers. How can I change the background of the font to wh... | [
"Here you have the functions you need (I only colored yaxis):\nIn [20]: f = figure(facecolor='red')\nIn [21]: ax = f.add_subplot(111)\nIn [22]: ax.set_axis_bgcolor('black')\nIn [23]: ya = ax.yaxis \nIn [24]: xa = ax.xaxis # you modify x ticks indepently\nIn [25]: ya.set_ti... | [
3
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008110107_matplotlib_python.txt |
Q:
python 3: splitting information and reporting occurrences
Say for example i want to count how many times bob visits sears and walmart how would i do this by creating dictionaries?
information given:
bob:oct1:sears
bob:oct1:walmart
mary:oct2:walmart
don:oct2:sears
bob:oct4:walmart
mary:oct4:sears
A:
Okay, as this... | python 3: splitting information and reporting occurrences | Say for example i want to count how many times bob visits sears and walmart how would i do this by creating dictionaries?
information given:
bob:oct1:sears
bob:oct1:walmart
mary:oct2:walmart
don:oct2:sears
bob:oct4:walmart
mary:oct4:sears
| [
"Okay, as this might be homework, I’ll try to give you some hints on how to do this. If this is not homework, please say so, and I’ll restore my original answer and example code.\nSo first of all, you have your data set in a way that each entry is in single line. As we want to work with each data entry on its own, ... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007987123_python.txt |
Q:
SQLite 3.x database file cannot be opened with python anydbm
I have a .db file created with SQLite3. I want to use anydbm to read this file.
My code:
import anydbm
db = anydbm.open('mydb.db', 'r')
However, it throws this error --> "anydbm.error: db type could not be determined"
I don't get it. What is wrong with ... | SQLite 3.x database file cannot be opened with python anydbm | I have a .db file created with SQLite3. I want to use anydbm to read this file.
My code:
import anydbm
db = anydbm.open('mydb.db', 'r')
However, it throws this error --> "anydbm.error: db type could not be determined"
I don't get it. What is wrong with this? The file type according to the Unix file command is SQLite 3... | [
"Anydbm module is only for db/dbm/gdbm type of files. It does not work at all with sqlite. They are not the same thing, and don't have the same file format. Use the sqlite module for SQLite databases.\n"
] | [
4
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0008111294_python_sqlite.txt |
Q:
psycopg2 does not execute PostgreSQL function
I'm trying to call a function from psycopg2 like such:
conn = psycopg2.connect(host="name.host.ex", user="username", password="secret")
cur = conn.cursor()
cur.callproc("f_do_action", ["aaa", "bbb"])
cur.close()
conn.close()
When calling this function from psql everyt... | psycopg2 does not execute PostgreSQL function | I'm trying to call a function from psycopg2 like such:
conn = psycopg2.connect(host="name.host.ex", user="username", password="secret")
cur = conn.cursor()
cur.callproc("f_do_action", ["aaa", "bbb"])
cur.close()
conn.close()
When calling this function from psql everything works fine but using psycopg2 nothing seems to... | [
"Try committing before closing your connection:\ncur.close()\nconn.commit()\nconn.close()\n\nFrom psycopg2 documentation:\n\nNote that closing a connection without committing the changes first\n will cause any pending change to be discarded as if a ROLLBACK was\n performed (unless a different isolation level has ... | [
17
] | [] | [] | [
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0008111278_postgresql_psycopg2_python.txt |
Q:
Would Python's Twisted library be the best case for an observer type pattern?
I'm developing a system where a queue will be filled with millions of items
I need a process that reads items from the queue constantly and then sends those items out to registered clients.
I'm thinking about using twisted for this, hav... | Would Python's Twisted library be the best case for an observer type pattern? | I'm developing a system where a queue will be filled with millions of items
I need a process that reads items from the queue constantly and then sends those items out to registered clients.
I'm thinking about using twisted for this, having the queue reader be a twisted server listening on a tcp port then clients can c... | [
"Perspective Broker might be what you're looking for. If you dont know PB, think of it as XML-RPC but much more. You can invoke remote procedures (duh!), pass most of python objects around just to name two.\nFor your case, have a PB for clients. Twisted Server can invoke the remote doWork(myItem, myParameters). The... | [
1,
1,
0
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0003001916_python_twisted.txt |
Q:
Overlay text on a picture with PIL
I just wanted to write some text on picture (possibly with some simple effects like shadow). How can I do this with PIL?
A:
First install Python Imaging Library (pip install Pillow)
Note: you may need to change the path to your font file font_fname.
import numpy as np
import ... | Overlay text on a picture with PIL | I just wanted to write some text on picture (possibly with some simple effects like shadow). How can I do this with PIL?
| [
"First install Python Imaging Library (pip install Pillow)\nNote: you may need to change the path to your font file font_fname. \nimport numpy as np\nimport PIL\nimport PIL.Image as Image\nimport PIL.ImageDraw as ImageDraw\nimport PIL.ImageFont as ImageFont\n\nfont_fname = '/usr/share/fonts/truetype/freefont/FreeS... | [
4
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0008110342_python_python_imaging_library.txt |
Q:
Python operator that mimic javascript || operator
I am Python newbie, so maybe don't knew if this is obvious or not.
In Javascript a||b returns a if a is evaluated to true, else returns b.
Is that possible in Python other than lengthy if else statement.
A:
I believe this is correct:
x = a or b
Proof
This is ho... | Python operator that mimic javascript || operator | I am Python newbie, so maybe don't knew if this is obvious or not.
In Javascript a||b returns a if a is evaluated to true, else returns b.
Is that possible in Python other than lengthy if else statement.
| [
"I believe this is correct:\nx = a or b\n\nProof\nThis is how \"||\" works in JavaScript:\n> 'test' || 'again'\n\"test\"\n> false || 'again'\n\"again\"\n> false || 0\n0\n> 1 || 0\n1\n\nThis is how \"or\" works in Python:\n>>> 'test' or 'again'\n'test'\n>>> False or 'again'\n'again'\n>>> False or 0\n0\n>>> 1 or 0\n1... | [
26,
3,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0008111484_python.txt |
Q:
Appending something to a list within a dict within a list in Python
I am attempting to create a list of dicts which will have the following structure:
[
{
'id': '234nj233nkj2k4n52',
'embedded_list': []
},
{
'id': 'jb234bhj23423h4b4',
'embedded_list': []
},
...
]
... | Appending something to a list within a dict within a list in Python | I am attempting to create a list of dicts which will have the following structure:
[
{
'id': '234nj233nkj2k4n52',
'embedded_list': []
},
{
'id': 'jb234bhj23423h4b4',
'embedded_list': []
},
...
]
Initially, this list will be empty.
What I need to be able to do is:
Ch... | [
"Your data structure should be a dictionary of dictionaries in the first place:\n{'234nj233nkj2k4n52': {'embedded_list': []},\n 'jb234bhj23423h4b4': {'embedded_list': []},\n ... }\n\nThis will make all your desired operations much easier. If the inner dictionaries only contain the embedded list, this can be fur... | [
4,
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0008111737_dictionary_list_python.txt |
Q:
Django Multiple File upload failing
I have a single HTML page with 2 Django Forms in it, all in the same <form>..</form> tag. Everything works great, except when I try to upload multiple files.
Each form has their own image, and for some reason I can only save the image from the first form. Other data from the sec... | Django Multiple File upload failing | I have a single HTML page with 2 Django Forms in it, all in the same <form>..</form> tag. Everything works great, except when I try to upload multiple files.
Each form has their own image, and for some reason I can only save the image from the first form. Other data from the second form still gets saved, but without an... | [
"looks like you are missing a play.save() (you save the form with commit=False)\n"
] | [
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0008111706_django_django_forms_django_models_python.txt |
Q:
I'm having a trouble with encoding in Python
I have been using PHP for a while,
but now I am trying to learn Python.
I never really had a serious problem with encoding on PHP. At least I could solve in few minutes. but I have spent hours to solve encoding problems in python, and I still can't solve it.
So my probl... | I'm having a trouble with encoding in Python | I have been using PHP for a while,
but now I am trying to learn Python.
I never really had a serious problem with encoding on PHP. At least I could solve in few minutes. but I have spent hours to solve encoding problems in python, and I still can't solve it.
So my problem is that I want to print a Japanese string to a ... | [
"Try setting your environment variable PYTHONIOENCODING to utf8. That will make Python use that encoding instead of none by default.\n",
"Update: I removed my comment because it was not really helpful for the question because I misread it...\nNow here my to cents that could perhaps help: You print the japanese te... | [
2,
0
] | [] | [] | [
"encoding",
"python",
"unicode"
] | stackoverflow_0008111769_encoding_python_unicode.txt |
Q:
PIL and Tkinter, multi windows
I have this message: image "pyimage2" doesn't exist . I want to have multi windows with images , how ?
Here is my code:
import Image
import ImageTk
import Tkinter
def new():
wind = Tkinter.Tk()
wind.geometry('600x600') # This not work, why?
imageFile2 = I... | PIL and Tkinter, multi windows | I have this message: image "pyimage2" doesn't exist . I want to have multi windows with images , how ?
Here is my code:
import Image
import ImageTk
import Tkinter
def new():
wind = Tkinter.Tk()
wind.geometry('600x600') # This not work, why?
imageFile2 = Image.open("someimage2.jpg")
im... | [
"Change wind = Tkinter.Tk() to wind = Tkinter.Toplevel():\ndef new():\n wind = Tkinter.Toplevel()\n wind.geometry('600x600') \n\nThat's all you need to change.\n\nReference:\n\nTkinter Toplevel\n\n"
] | [
3
] | [] | [] | [
"python",
"python_imaging_library",
"tkinter"
] | stackoverflow_0008111739_python_python_imaging_library_tkinter.txt |
Q:
Static member of a function in Python ?
Possible Duplicate:
Static class variables in Python
What is the Python equivalent of static variables inside a function?
How can I use static fields in Python ?
for example i want to count how many times the function has been called - how can i do this ?
A:
If you wi... | Static member of a function in Python ? |
Possible Duplicate:
Static class variables in Python
What is the Python equivalent of static variables inside a function?
How can I use static fields in Python ?
for example i want to count how many times the function has been called - how can i do this ?
| [
"If you wish to count how many times a method has been called, no matter which instance called it, you could use a class member like this:\nclass Foo(object):\n calls=0 # <--- call is a class member\n def baz(self):\n Foo.calls+=1\n\nfoo=Foo()\nbar=Foo()\nfor i in range(100): \n foo.baz()... | [
9,
4,
4,
2
] | [] | [] | [
"python",
"static_members"
] | stackoverflow_0008111543_python_static_members.txt |
Q:
Tornado and Unicode
does tornado accept unicode in the adress?
#coding: utf-8 (there is # dont know how to show it here...)
import tornado.ioloop
import tornado.web
class Abdou(tornado.web.RequestHandler):
def get(self):
self.write("hi")
miaw = tornado.web.Application([
(u'/ééé', Abdou),
])
if __name__ ==... | Tornado and Unicode | does tornado accept unicode in the adress?
#coding: utf-8 (there is # dont know how to show it here...)
import tornado.ioloop
import tornado.web
class Abdou(tornado.web.RequestHandler):
def get(self):
self.write("hi")
miaw = tornado.web.Application([
(u'/ééé', Abdou),
])
if __name__ == "__main__":
miaw.liste... | [
"Look at tornado.escape.url_escape(value) and tornado.escape.url_unescape(value, encoding='utf-8').\nSomething like this:\n#coding: utf-8 (there is # dont know how to show it here...)\nimport tornado.ioloop\nimport tornado.web\n\nclass Abdou(tornado.web.RequestHandler):\n def get(self):\n self.write(\"hi\... | [
1,
0
] | [] | [] | [
"python",
"tornado",
"unicode"
] | stackoverflow_0008100049_python_tornado_unicode.txt |
Q:
mean average on the contents of a list
I have a list like the following:
mylist = [('a', [(0,1), (1,2), (2,3)]),
('b', [(0,1), (1,2), (2,3)]),
('c', [(0,1), (1,2), (2,3)])]
which I got after different operations in the code.
Is it possible to get an output like the following?
newlist = [('a', [0... | mean average on the contents of a list | I have a list like the following:
mylist = [('a', [(0,1), (1,2), (2,3)]),
('b', [(0,1), (1,2), (2,3)]),
('c', [(0,1), (1,2), (2,3)])]
which I got after different operations in the code.
Is it possible to get an output like the following?
newlist = [('a', [0.5, 1.5, 2.5]),
('b', [0.5, 1.5, 2... | [
">>> l = [('a', [(0,1), (1,2), (2,3)]),\n... ('b', [(0,1), (1,2), (2,3)]),\n... ('c', [(0,1), (1,2), (2,3)])]\n>>> newl = [(i[0], [(j[0]+j[1])/2 for j in i[1]]) for i in l]\n>>> newl\n[('a', [0.5, 1.5, 2.5]), ('b', [0.5, 1.5, 2.5]), ('c', [0.5, 1.5, 2.5])]\n\nThis works in Python 3; in Python 2, you need\n>>> newl ... | [
4,
3,
2
] | [] | [] | [
"arrays",
"average",
"python"
] | stackoverflow_0008112175_arrays_average_python.txt |
Q:
Split string in python
I have an input on the form 'A7-A5'
How can i get that input to a list like: [['A',7],['A',5]]
A:
>>> a = "A7-A5"
>>> b = [[i[0], int(i[1])] for i in a.split("-")]
>>> b
[['A', 7], ['A', 5]]
| Split string in python | I have an input on the form 'A7-A5'
How can i get that input to a list like: [['A',7],['A',5]]
| [
">>> a = \"A7-A5\"\n>>> b = [[i[0], int(i[1])] for i in a.split(\"-\")]\n>>> b\n[['A', 7], ['A', 5]]\n\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0008112328_python.txt |
Q:
better algorithm for checking 5 in a row/col in a matrix
is there a good algorithm for checking whether there are 5 same elements in a row or a column or diagonally given a square matrix, say 6x6?
there is ofcourse the naive algorithm of iterating through every spot and then for each point in the matrix, iterate t... | better algorithm for checking 5 in a row/col in a matrix | is there a good algorithm for checking whether there are 5 same elements in a row or a column or diagonally given a square matrix, say 6x6?
there is ofcourse the naive algorithm of iterating through every spot and then for each point in the matrix, iterate through that row, col and then the diagonal. I am wondering if ... | [
"You could keep a histogram in a dictionary (mapping element type -> int). And then you iterate over your row or column or diagonal, and increment histogram[element], and either check at the end to see if you have any 5s in the histogram, or if you can allow more than 5 copies, you can just stop once you've reached... | [
3,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"algorithm",
"matrix",
"python"
] | stackoverflow_0008091248_algorithm_matrix_python.txt |
Q:
How can I model a scalable set of definition/term pairs?
Right now my flashcard game is using a prepvocab() method where I
define the terms and translations for a week's worth of terms as a dictionary
add a description of that week's terms
lump them into a list of dictionaries, where a user selects their "weeks" ... | How can I model a scalable set of definition/term pairs? | Right now my flashcard game is using a prepvocab() method where I
define the terms and translations for a week's worth of terms as a dictionary
add a description of that week's terms
lump them into a list of dictionaries, where a user selects their "weeks" to study
Every time I add a new week's worth of terms and tra... | [
"You should store your term:translation pairs and descriptions in a text file in some manner. Your program should then parse the text file and discover all available lessons. This will allow you to extend the set of lessons available without having to edit any code.\nAs for your selection of lessons, write a print_... | [
0,
0
] | [] | [] | [
"dictionary",
"python",
"scalability"
] | stackoverflow_0007669701_dictionary_python_scalability.txt |
Q:
forcing python version in windows
I know how what to write in a python script to tell a unix box which version of python to run (#!/usr/bin/env python3.2), but how do I do that in windows. I will be deploying a program through distutils to windows boxes that have both python2.7 and 3.2 installed. I need to force... | forcing python version in windows | I know how what to write in a python script to tell a unix box which version of python to run (#!/usr/bin/env python3.2), but how do I do that in windows. I will be deploying a program through distutils to windows boxes that have both python2.7 and 3.2 installed. I need to force it to use 2.7
Thanks!
| [
"Even on unix with a shebang (#!) you are not forcing which version to run under. If the program is not executed directly (./my.py) and instead is run like python2 my.py then Python 2 will still be used.\nI would suggest the safest way is to check the version at the beginning of your script and bail out with an err... | [
4
] | [] | [] | [
"deployment",
"python",
"version"
] | stackoverflow_0008112766_deployment_python_version.txt |
Q:
Check tar archive before extractall
In the python documentation, it is adviced not to extract a tar archive without prior inspection. What is the best way to make sure an archive is safe using the tarfile python module? Should I just iterate over all the filename and check wether they contain absolute pathnames?
W... | Check tar archive before extractall | In the python documentation, it is adviced not to extract a tar archive without prior inspection. What is the best way to make sure an archive is safe using the tarfile python module? Should I just iterate over all the filename and check wether they contain absolute pathnames?
Would something like the following be suff... | [
"Almost, although it would still be possible to have a path like foo/../../.\nBetter would be to use os.path.join and os.path.abspath, which together will correctly handle leading / and ..s anywhere in the path:\ntarget_dir = \"/target/\" # trailing slash is important\nwith tarfile.open(…) as tarf:\n for n in ta... | [
4
] | [] | [] | [
"python",
"tar"
] | stackoverflow_0008112742_python_tar.txt |
Q:
Cant understand results while using assertRaises in unit testing on a sqlalchemy code
I am trying to unit test my sqlalchemy code.
def add_user(*user_details):
try:
u = User(*user_details)
session.add(u)
session.commit()
except:
session.rol... | Cant understand results while using assertRaises in unit testing on a sqlalchemy code | I am trying to unit test my sqlalchemy code.
def add_user(*user_details):
try:
u = User(*user_details)
session.add(u)
session.commit()
except:
session.rollback()
Now in my unit test:
def testDuplicate(self):
add_user(user_detail1,u... | [
"You are using assertRaises incorrectly, instead you should write:\nself.assertRaises(IntegrityError, add_user, user_detail1, user_detail2)\n\nYou give the function and the arguments separately to assertRaises so it can control when the function is called (e.g. in a try/except block in assertRaises).\nThe other pro... | [
3
] | [] | [] | [
"assertraises",
"exception_handling",
"python",
"python_unittest",
"sqlalchemy"
] | stackoverflow_0008112654_assertraises_exception_handling_python_python_unittest_sqlalchemy.txt |
Q:
Unicode with accents raising UnicodeDecodeError on logging (App Engine)
I'm trying to make a change to an old appengine application, but now after formating my pc and installing updated tools the logging functions are raising a unicode error.
In the previous development environment everything worked fine.
ubun... | Unicode with accents raising UnicodeDecodeError on logging (App Engine) | I'm trying to make a change to an old appengine application, but now after formating my pc and installing updated tools the logging functions are raising a unicode error.
In the previous development environment everything worked fine.
ubuntu 9.04
python2.6
google appengine sdk 1.5
Now I'm trying make a chan... | [
"It's a bug:\nhttp://code.google.com/p/googleappengine/issues/detail?id=6266\nHopefully it will be corrected in next version (1.6.1).\n",
"You can try checking this page on unicode and utf-8 encoding. Strategies and workaround are also included. It's a known issue since Python 2 default encoding is 'ascii'. \n"
] | [
3,
0
] | [
"Python 2 is not using UTF-8 by default for source code, otherwise you will have to specify the encoding. See PEP-263\n#!/usr/local/bin/python\n# -*- coding: utf-8 -*-\n\nAnyway, it's not a good idea to keep Unicode in your source code.\n"
] | [
-1
] | [
"google_app_engine",
"logging",
"python",
"unicode",
"utf_8"
] | stackoverflow_0008107388_google_app_engine_logging_python_unicode_utf_8.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.