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: In Ubuntu Python 2.7 reading output of an os.system() command So I am running code that looks like this on Ubuntu 11.4 and Python 2.7: p_scan_command = "sudo nmap -sC -sV -PN -O 192.168.0.1/24" time.sleep(1.5) os.system(p_scan_command) f = open('nmapscan1.log', 'r') print f.read() f.close() What is happening is t...
In Ubuntu Python 2.7 reading output of an os.system() command
So I am running code that looks like this on Ubuntu 11.4 and Python 2.7: p_scan_command = "sudo nmap -sC -sV -PN -O 192.168.0.1/24" time.sleep(1.5) os.system(p_scan_command) f = open('nmapscan1.log', 'r') print f.read() f.close() What is happening is that I end up with no results, and the scan is not being run, probab...
[ "\nAre you sure that the log file is even created? I cannot see where this name is mentionned - but maybe it is created by default.\nAre you asked for the password by sudo?\nThis could tell you if sudo is really run.\nos.system is kind of deprecated or at least frowned upon; better use subprocess.call(), subprocess...
[ 7, 0 ]
[]
[]
[ "os.system", "python", "python_2.7", "ubuntu", "ubuntu_11.04" ]
stackoverflow_0007129928_os.system_python_python_2.7_ubuntu_ubuntu_11.04.txt
Q: amqp exchange types I'm getting into the whole amqp thing and i have a question regarding which type of exchange type to use under the following scenario's: 1) i have the need to create a worker pool where each worker does something when they receive a message. now i want different workers attached to different ty...
amqp exchange types
I'm getting into the whole amqp thing and i have a question regarding which type of exchange type to use under the following scenario's: 1) i have the need to create a worker pool where each worker does something when they receive a message. now i want different workers attached to different types of tasks; which i can...
[ "For most people it is best to just use a topic exchange for everything until you fully understand how AMQP works. You can get fanout and direct behavior just by choosing the right binding key for a queue. For instance if you use \"#\" for a binding key, then that queue behaves as if it was connected to a direct ex...
[ 0 ]
[]
[]
[ "amqp", "kombu", "python" ]
stackoverflow_0005998693_amqp_kombu_python.txt
Q: Python fixed width strings with the Template object Is there a way make fixed width substitutions with the python String.Template objects substitution language For example if I wanted s to be 'A string 0003' how would I modify this code: from string import Template stmpl=Template("A string ${tcount}") s=stmpl.subs...
Python fixed width strings with the Template object
Is there a way make fixed width substitutions with the python String.Template objects substitution language For example if I wanted s to be 'A string 0003' how would I modify this code: from string import Template stmpl=Template("A string ${tcount}") s=stmpl.substitute(tcount=3) print(s) Related question, not using te...
[ "read throu PEP 292 , \"Simpler String Substitutions\" does not make it as expressive as % format. i think you had to format the substitution yourself before feed to the template. something like \n\"{0:05}\".format(3)\n\n", "s=stmpl.substitute(tcount=str(3).zfill(4))\n" ]
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007130072_python.txt
Q: Symlinking PIL from site packages on Snow Leopard to a virtualenv with no-site-packages not working I have a virtualenv with --no-site-packages and am having all sorts of issues installing PIL in the virtualenv. The global PIL works fine. I'm trying to get this working by symlinking to PIL in the global site packa...
Symlinking PIL from site packages on Snow Leopard to a virtualenv with no-site-packages not working
I have a virtualenv with --no-site-packages and am having all sorts of issues installing PIL in the virtualenv. The global PIL works fine. I'm trying to get this working by symlinking to PIL in the global site packages, which I know works. I tried: ln -s /Library/Python/2.6/site-packages/PIL ~/my_virtualenv/lib/python2...
[ "Install the development libraries (jpeg, zip, etc.), then use the virtualenv (adding setuptools or pip to it as necessary) to install PIL into the virtualenv itself.\n" ]
[ 0 ]
[]
[]
[ "python", "python_imaging_library", "virtualenv" ]
stackoverflow_0006106239_python_python_imaging_library_virtualenv.txt
Q: Python: sys.exc_info() is missing local variables In Python, I have code that catches an exception, like this: try: <do stuff> except: exc_info = sys.exc_info() The problem I'm running into is that the traceback object (exc_info[2]) is non-deterministically missing local variables in the traceback objects...
Python: sys.exc_info() is missing local variables
In Python, I have code that catches an exception, like this: try: <do stuff> except: exc_info = sys.exc_info() The problem I'm running into is that the traceback object (exc_info[2]) is non-deterministically missing local variables in the traceback objects. I know this for a fact because I run the exact same c...
[ "What is in the locals is completely dependent on the code in that local context. For example:\nif condition:\n foo='foo'\nelse:\n bar='bar'\n\nif condition==True then foo will be in locals() and bar will not, otherwise bar will be in locals() and foo will not.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003001750_python.txt
Q: for-case loop evaluates second iteration twice and skips third iteration So i have this code: def Convert(ama,a): print ama,a def run(): z=0 while z!=3: z+=1 if z==1: n='e' if z==2: n='B' if z=='3': n='G' a='-----2-----5-6--...
for-case loop evaluates second iteration twice and skips third iteration
So i have this code: def Convert(ama,a): print ama,a def run(): z=0 while z!=3: z+=1 if z==1: n='e' if z==2: n='B' if z=='3': n='G' a='-----2-----5-6----7' Convert(a,n) run() The result: -----2-----5-6----7 e -----2-----...
[ " if z=='3':\n\nshould be this\n if z==3:\n\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0007130323_python.txt
Q: Blender 2.5 Python find uv layer image I have a mesh in blender with one uv layer that is mapped to an image. From python I want to access the properties of that image (for example name, width and height). I can get the uv layer like this: ob = context.active_object me = ob.data uv_layer = me.uv_textures[0] # doe...
Blender 2.5 Python find uv layer image
I have a mesh in blender with one uv layer that is mapped to an image. From python I want to access the properties of that image (for example name, width and height). I can get the uv layer like this: ob = context.active_object me = ob.data uv_layer = me.uv_textures[0] # does not work: img = uv_layer.image In blend...
[ "Ok, found out how to do it:\nimg = me.uv_textures[0].data.values()[0].image\n\n" ]
[ 1 ]
[]
[]
[ "blender", "python" ]
stackoverflow_0007127605_blender_python.txt
Q: XMLRPC c# client to python client - method does not exists I've searched the web and seen the following question: XML-RPC C# and Python RPC Server I'm trying for a while to do the same, but I fail. I get the exception "Method "HelloWorld" is not supported..." [XmlRpcUrl("http://192.168.0.xxx:8000/RPC2")] public in...
XMLRPC c# client to python client - method does not exists
I've searched the web and seen the following question: XML-RPC C# and Python RPC Server I'm trying for a while to do the same, but I fail. I get the exception "Method "HelloWorld" is not supported..." [XmlRpcUrl("http://192.168.0.xxx:8000/RPC2")] public interface HelloWorld : IXmlRpcProxy { [XmlRpcMethod] Strin...
[ "I found the problem:\n\nSyntax problem server.register_function(\"HelloWorld\", HelloWorld) should be server.register_function(HelloWorld, \"HelloWorld\").\nThis change also didn't work, so I changed the function name form helloWorld to hello and it worked(!)\n\n" ]
[ 1 ]
[]
[]
[ "c#", "python", "simplexmlrpcserver", "xml_rpc" ]
stackoverflow_0007124937_c#_python_simplexmlrpcserver_xml_rpc.txt
Q: Why is there a difference in performance between Tornado's ioloop and httpserver? I decided to use Python Tornado as a choice server for my startup, and I was running httpref against two reference Python Tornado implementations to stress test Tornado's capabilities. Here are the two pieces of code that I ran again...
Why is there a difference in performance between Tornado's ioloop and httpserver?
I decided to use Python Tornado as a choice server for my startup, and I was running httpref against two reference Python Tornado implementations to stress test Tornado's capabilities. Here are the two pieces of code that I ran against each other: iostream: import errno import functools import socket from tornado impor...
[ "\n\nErrors: fd-unavail 47569\n\n\nThis means your machine are out of file descriptors.\nYour httperf failed.\n" ]
[ 1 ]
[]
[]
[ "python", "stress_testing", "tornado" ]
stackoverflow_0007129345_python_stress_testing_tornado.txt
Q: printing values for x,y,and z in columns, python import xlrd import os path = 'data' with open('', 'w') as f: column_values=['', '', ''] for filename in os.listdir(path): fullname = os.path.join(path, filename) if fullname.endswith('.xls'): wb = xlrd.open_workbook(fullname) ...
printing values for x,y,and z in columns, python
import xlrd import os path = 'data' with open('', 'w') as f: column_values=['', '', ''] for filename in os.listdir(path): fullname = os.path.join(path, filename) if fullname.endswith('.xls'): wb = xlrd.open_workbook(fullname) sh = wb.sheet_by_name(u'') for...
[ "Well, that's very, very basic programming. I would rewrite the script like this:\nimport xlrd\nimport os\n\npath = 'E:\\\\IMRT_C\\\\Preanalysis\\\\'\n\nwith open('E:\\\\IMRT_C\\\\Working_files\\\\Trying_excel.csv', 'w') as f:\n column_values=[[], [], []]\n\n for filename in os.listdir(path):\n fullnam...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007130348_python_python_3.x.txt
Q: Why does `print hashlib.sha224(some_string).digest()` differs from its `repr()`? I want to store some hashes of some strings in my Database table. For that I created a column of type varchar(64). I do generate the hashes like this: >>> thehash = hashlib.sha224(some_string).digest() Now I realize that >>> print th...
Why does `print hashlib.sha224(some_string).digest()` differs from its `repr()`?
I want to store some hashes of some strings in my Database table. For that I created a column of type varchar(64). I do generate the hashes like this: >>> thehash = hashlib.sha224(some_string).digest() Now I realize that >>> print thehash is not the same as >>> thehash (By now, I know the difference between >>> prin...
[ "Neither. You should call the .hexdigest() method instead and store that.\n" ]
[ 5 ]
[]
[]
[ "hash", "mysql", "python", "repr" ]
stackoverflow_0007130494_hash_mysql_python_repr.txt
Q: Can python.org releases play nice with Apple framework builds? (Advanced apologies for the lack or proper links; the system won't allow me to add more than two.) Unfortunately, I've learnt the hard way that you shouldn't mess with the default Python installations in Mac OS X (specifically, 10.6.8). After using th...
Can python.org releases play nice with Apple framework builds?
(Advanced apologies for the lack or proper links; the system won't allow me to add more than two.) Unfortunately, I've learnt the hard way that you shouldn't mess with the default Python installations in Mac OS X (specifically, 10.6.8). After using the python.org installers for 2.6.6 (http://www.python.org/getit/rele...
[ "You misunderstand how Python installations work on OS X. Each Python instance has its own site-packages directory. The standard location for framework installers is within the framework at ./lib/pythonx.y/site-packages. So for the python.org installers which install into /Library/Frameworks/Python.framework, yo...
[ 3 ]
[]
[]
[ "macos", "pyobjc", "python" ]
stackoverflow_0007130283_macos_pyobjc_python.txt
Q: Strange socket problem in python 3.2 I'm currently making a chat application in python. It works like this: 1. The server is working 2. Clients enter their id and password 3. The login info are checked by the server 4. They are assigned a random number by the server 5. They can now send and recv message from and t...
Strange socket problem in python 3.2
I'm currently making a chat application in python. It works like this: 1. The server is working 2. Clients enter their id and password 3. The login info are checked by the server 4. They are assigned a random number by the server 5. They can now send and recv message from and to the server I'm having a problem at recei...
[ "Ouch ouch ouch.\nAbout the global stuff, I let it up to you to correct, but\ndef recv_server():\n global number\n global s #the tcp socket\n global sockets\n sockets[number], sockname = s.accept()\n logindata = sockets[number].recv(65535)\n logindata = logindata.decode()\n ...\n\nwith a so...
[ 2, 1 ]
[]
[]
[ "python", "sockets", "version" ]
stackoverflow_0007128020_python_sockets_version.txt
Q: Does calling fetchall() after execute(sql) read the data a second time? I just learned using MySQLDb package for python and I am familiar with fetching rows from a select statement. cursor.execute("SELECT movie_list_....") result = cursor.fetchall() As I noticed, when I run the first command, it displays 123L, th...
Does calling fetchall() after execute(sql) read the data a second time?
I just learned using MySQLDb package for python and I am familiar with fetching rows from a select statement. cursor.execute("SELECT movie_list_....") result = cursor.fetchall() As I noticed, when I run the first command, it displays 123L, the number of rows affected. When I run the second command, the data is actuall...
[ "It depends on if you take a \"normal\", client side cursor or a server side cursor.\nInternally, the client side one (CS) uses mysql_store_result(), while the server side one (SS) uses mysql_use_result().\nThe CS one is (normally) to be favourized, as it fetches all data immediately after sending the query. This i...
[ 2 ]
[]
[]
[ "database", "mysql", "python" ]
stackoverflow_0007130610_database_mysql_python.txt
Q: web2py TypeError: id() takes exactly one argument (0 given) I am making a web service in Web2Py which accept some parameters and inserts them into a table. I am getting the following error while I am inserting data in this 1 table Traceback (most recent call last): File "E:\Development\Python\web2py\gluon\restr...
web2py TypeError: id() takes exactly one argument (0 given)
I am making a web service in Web2Py which accept some parameters and inserts them into a table. I am getting the following error while I am inserting data in this 1 table Traceback (most recent call last): File "E:\Development\Python\web2py\gluon\restricted.py", line 192, in restricted exec ccode in environment ...
[ "You have problems here:\ndb.define_table('t_wish',\n Field('id','id',\n represent=lambda id:SPAN(id,' ',A('view',_href=URL('wish_read',args=id)))),\n\nand here:\n# try: \n wish_id = db.t_wish.insert(f_user_id = id, ...)\n\nchange to:\ndb.define_table('t_wish',\n Field('id','id',\n rep...
[ 3, 2 ]
[]
[]
[ "python", "sql", "web2py" ]
stackoverflow_0007130349_python_sql_web2py.txt
Q: Unexpected performance loss when calling Cython function within Python script? So I have a time-critical section of code within a Python script, and I decided to write a Cython module (with one function -- all I need) to replace it. Unfortunately, the execution speed of the function I'm calling from the Cython mod...
Unexpected performance loss when calling Cython function within Python script?
So I have a time-critical section of code within a Python script, and I decided to write a Cython module (with one function -- all I need) to replace it. Unfortunately, the execution speed of the function I'm calling from the Cython module (which I'm calling within my Python script) isn't nearly as fast as I tested it ...
[ "It could be that, while individually, each function call with the Cython implementation is faster than its corresponding Python function, there is more overhead in the Cython function call because it has to look up the name in the module namespace. You can try assigning the function to a local callable first, for ...
[ 3, 1 ]
[]
[]
[ "c", "cython", "python" ]
stackoverflow_0007101956_c_cython_python.txt
Q: How to tell MySQL to trigger a Hash before Update/Insert? I am struggeling to create a trigger within MySQL, so that everytime I am inserting a value into a column named title a HASH shall be created and stored in the column title_hash. Since I don't know how this works I found this code while googling: CREATE TRI...
How to tell MySQL to trigger a Hash before Update/Insert?
I am struggeling to create a trigger within MySQL, so that everytime I am inserting a value into a column named title a HASH shall be created and stored in the column title_hash. Since I don't know how this works I found this code while googling: CREATE TRIGGER insertModelHash BEFORE INSERT ON products FOR EACH ROW...
[ "To answer your three questions:\nThe NEW keyword references the 'pseudo-table' for the record that would be inserted. On an updated trigger, you can access both 'NEW' and 'OLD', and on a delete, just 'OLD'.\nYes, MD5 is used to create the hash. However, in your question, you have part of the parameter to the 'RIGH...
[ 5 ]
[]
[]
[ "hash", "insert", "mysql", "python", "triggers" ]
stackoverflow_0007130883_hash_insert_mysql_python_triggers.txt
Q: Problem with gaesessions (django+GAE) I'm using gaesessions on gae with django. When I run the application Following error occurs while loading gaesessions.DjangoSessionMiddleware. Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 405...
Problem with gaesessions (django+GAE)
I'm using gaesessions on gae with django. When I run the application Following error occurs while loading gaesessions.DjangoSessionMiddleware. Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 4053, in _HandleRequest self._Dispatch(dis...
[ "The middleware does not get handed a response. Check your request handler.\n" ]
[ 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0006823408_django_google_app_engine_python.txt
Q: Xpath doesn't match I'm trying to get some elements from a page. Unfortunately it results with an empty list. The pretty-printed tree includes this element: <html:a title="..." href="..." id="..." class="topic_title">...</html:a> However when I do this on the same tree: page.xpath('''.//a[@class="topic_title"]'''...
Xpath doesn't match
I'm trying to get some elements from a page. Unfortunately it results with an empty list. The pretty-printed tree includes this element: <html:a title="..." href="..." id="..." class="topic_title">...</html:a> However when I do this on the same tree: page.xpath('''.//a[@class="topic_title"]''') I get an empty list. T...
[ "It seems as if you are dealing with XHTML, so you could register the namespace html before evaluating the XPath expression:\npage.xpath('''.//html:a[@class=\"topic_title\"]''',\n namespaces={'html': 'http://www.w3.org/1999/xhtml'})\n\nSee also Namespaces and Prefixes:\n\nIf your XPath expression uses nam...
[ 2 ]
[]
[]
[ "html", "html5lib", "lxml", "python", "xpath" ]
stackoverflow_0007131917_html_html5lib_lxml_python_xpath.txt
Q: Place Pip and Yolk inside or outside a virtual environment? I'm using virtualenv for sandboxing my Python environment, pip to install/uninstall packages and yolk to list the packages. I can install packages to my virtual environment by using pip install <package name> -e=<environment name> and I guess I don't need...
Place Pip and Yolk inside or outside a virtual environment?
I'm using virtualenv for sandboxing my Python environment, pip to install/uninstall packages and yolk to list the packages. I can install packages to my virtual environment by using pip install <package name> -e=<environment name> and I guess I don't need to have pip inside my virtual environment. Am i correct? If I ne...
[ "Here is your workflow:\n\nAdd virtualenv and pip to your global environment.\nCreate virtualenvs\nWithin a virtualenv, add new packages\n\nI recommend you look into virtualenvwrapper. It makes the maintenance of virtualenvs way easier.\n\nDownload and install virtualenvwrapper in your global environment\nCreate di...
[ 2 ]
[]
[]
[ "pip", "python", "virtualenv", "yolk" ]
stackoverflow_0007130516_pip_python_virtualenv_yolk.txt
Q: Managing Python installations There are many versions of Python, and it becomes difficult to manage them all. Often I need to install one module into 3 different versions of Python. Is there a tool which can simplify things? I'm on Windows. Thanks. A: Are you using virtualenv? If not, you definitely want to chec...
Managing Python installations
There are many versions of Python, and it becomes difficult to manage them all. Often I need to install one module into 3 different versions of Python. Is there a tool which can simplify things? I'm on Windows. Thanks.
[ "Are you using virtualenv? If not, you definitely want to check that out: http://pypi.python.org/pypi/virtualenv\nIt helps you by managing and switching between several virtual Python environments, with different versions of Python if you want to. \nThere are loads of tutorials of how to set it up, all over dem in...
[ 2, 2, 1 ]
[ "I'm not aware of any Python facility for doing that, that's really the OS's job. Debian/Ubuntu, for example, has support for installing multiple versions of Python and installing libraries into each version. I doubt there's any such support in Windows.\n" ]
[ -3 ]
[ "python", "windows" ]
stackoverflow_0007130489_python_windows.txt
Q: wxWidgets calculating incorrect frame size I need to make small wxWidgets (wxPython) frame, which contains only toolbar and menubar and is just enough big to contain them. When I run code below, it creates a frame but it`s way too big. What should I do to make frame fit tightly around components it contains? Code...
wxWidgets calculating incorrect frame size
I need to make small wxWidgets (wxPython) frame, which contains only toolbar and menubar and is just enough big to contain them. When I run code below, it creates a frame but it`s way too big. What should I do to make frame fit tightly around components it contains? Code that creates problematic frame: class ToolFrame...
[ "Try to delete self.SetMaxSize(size) and say what happened.\n" ]
[ 0 ]
[]
[]
[ "python", "user_interface", "wxpython", "wxwidgets" ]
stackoverflow_0007130611_python_user_interface_wxpython_wxwidgets.txt
Q: self.writer.writerow([s.encode('utf-8') for s in row]) I am trying to write into a file (in Python), but it says: 'ManyRelatedManager' object has no attribute 'encode' Here is the code: self.writer.writerow([s.encode('utf-8') for s in row]) Is there a way to avoid/fix this ? A: in your code self.writer.wri...
self.writer.writerow([s.encode('utf-8') for s in row])
I am trying to write into a file (in Python), but it says: 'ManyRelatedManager' object has no attribute 'encode' Here is the code: self.writer.writerow([s.encode('utf-8') for s in row]) Is there a way to avoid/fix this ?
[ "in your code \nself.writer.writerow([s.encode('utf-8') for s in row])\n\nthe \"s\" object may not a unicode object \nyou should try change your \"s\" object to unicode first\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007132308_python.txt
Q: Loop problem while iterating through a list and removing recurring elements I want to iterate through a list, and remove the items that count more than once, so they don't get printed repeatedly by the for loop. However, some items appearing only one time in the list seem to get affected too by this, and I can't ...
Loop problem while iterating through a list and removing recurring elements
I want to iterate through a list, and remove the items that count more than once, so they don't get printed repeatedly by the for loop. However, some items appearing only one time in the list seem to get affected too by this, and I can't figure out why. Any input would be greatly appreciated. Example Output: listy ...
[ "You should not modify a list while iterating over it. This one should work:\nlisty = [2,2,1,3,4,2,1,2,3,4,5]\nfound = set()\nfor i in listy:\n if not i in found:\n print i, listy.count(i)\n found.add(i)\n\nThe result is:\n2 4\n1 2\n3 2\n4 2\n5 1\n\n", "The reason for your problems is that you mo...
[ 5, 3, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "iterator", "list", "loops", "python" ]
stackoverflow_0007131457_iterator_list_loops_python.txt
Q: Using nipype to apply a FLIRT registration to an additional image error I am trying to do some registration in python using the nipype package. It worked for basic registration: from nipype.interfaces import fsl from nipype.testing import example_data flt = fsl.FLIRT(bins=640, cost_func='mutualinfo') flt.inputs.in...
Using nipype to apply a FLIRT registration to an additional image error
I am trying to do some registration in python using the nipype package. It worked for basic registration: from nipype.interfaces import fsl from nipype.testing import example_data flt = fsl.FLIRT(bins=640, cost_func='mutualinfo') flt.inputs.in_file = 'myInput.img' flt.inputs.reference = 'myReference.img' flt.inputs.out...
[ "There is a space in directory/file name containing your images:\n/root/Desktop/Test Data\nRename Test Data as Test_Data and it will work\n" ]
[ 2 ]
[]
[]
[ "image_processing", "nipy", "nipype", "python" ]
stackoverflow_0007018599_image_processing_nipy_nipype_python.txt
Q: twisted perspective broker server side delay I am using twisted's Perspective Broker to talk between the client and the server. The client requests from the server a remote method 'remote_ssh'. This causes the PB server to initiate an SSH connection using Paramiko's SSH library and retrieve a configuration from ...
twisted perspective broker server side delay
I am using twisted's Perspective Broker to talk between the client and the server. The client requests from the server a remote method 'remote_ssh'. This causes the PB server to initiate an SSH connection using Paramiko's SSH library and retrieve a configuration from a remote device. This all works fine, but when I...
[ "This happens because the responses can't be sent until the reactor has a chance to run. If all five requests arrive at about the same time, then the reactor may wake up once and notice all five of them at the same time. It will dispatch all five of them to the PB server. The remote_ssh method will service one o...
[ 5 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0007127731_python_twisted.txt
Q: Twisted Throughput Limit Decreases I am developing a program which allows for simulations of networks on a single machine. For this I am using Twisted for asynchronous I/O, as having a thread for each 'connection' might be a bit much. (I have also implemented a similar program in Java using their NIO). However as ...
Twisted Throughput Limit Decreases
I am developing a program which allows for simulations of networks on a single machine. For this I am using Twisted for asynchronous I/O, as having a thread for each 'connection' might be a bit much. (I have also implemented a similar program in Java using their NIO). However as I scale the emulated network size up the...
[ "Try profiling the application at different levels of concurrency and see which things get slower as you add more connections.\nselect is a likely candidate; if you find that it is using noticably more and more time as you add connections, try using the poll or epoll reactor.\n" ]
[ 1 ]
[]
[]
[ "java", "python", "selector", "throughput", "twisted" ]
stackoverflow_0007127320_java_python_selector_throughput_twisted.txt
Q: Creating a URLretreive function using urllib2 in python I want to have a function which can save a page from the web into a designated path using urllib2. Problem with urllib is that it doesn't check for Error 404, but unfortunately urllib2 doesn't have such a function although it can check for http errors. How ca...
Creating a URLretreive function using urllib2 in python
I want to have a function which can save a page from the web into a designated path using urllib2. Problem with urllib is that it doesn't check for Error 404, but unfortunately urllib2 doesn't have such a function although it can check for http errors. How can i make a function to save the file permanently to a path? d...
[ "Just use .read() to get the contents and write it to a file path.\ndef save(url,path):\n g = urllib2.urlopen(url)\n with open(path, \"w\") as fH:\n fH.write(g.read())\n\n" ]
[ 1 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0007132892_python_urllib2.txt
Q: Using KWallet in PyQt4 It would be great if anyone could show me how to use KWallet with pyqt4 A: Tutorial in the Python command line First I will show how kwallet can be used from the Python command line to read and write a password: $ python # We import the necessary modules. >>> from PyKDE4.kdeui import KWal...
Using KWallet in PyQt4
It would be great if anyone could show me how to use KWallet with pyqt4
[ "Tutorial in the Python command line\nFirst I will show how kwallet can be used from the Python command line to read and write a password:\n$ python\n\n# We import the necessary modules.\n>>> from PyKDE4.kdeui import KWallet\n>>> from PyQt4 import QtGui\n\n# We create a QApplication. We will not use it, but otherwi...
[ 5, 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0002147724_pyqt4_python.txt
Q: Python's CSV module behaves differently in Django view I have a csv file with this test content: 1,2,3 4,5,6 7,8,9 Parsing this in the usual manner with the csv module works fine: >>> for row in csv.reader(open('test.csv')): ... print row ... ['1', '2', '3'] ['4', '5', '6'] ['7', '8', '9'] I then try and us...
Python's CSV module behaves differently in Django view
I have a csv file with this test content: 1,2,3 4,5,6 7,8,9 Parsing this in the usual manner with the csv module works fine: >>> for row in csv.reader(open('test.csv')): ... print row ... ['1', '2', '3'] ['4', '5', '6'] ['7', '8', '9'] I then try and use the same process in a django view: def upload_csv(request)...
[ "Matt added to the top of the question:\n\nJust after posting, the answer came to me: removing the .read(). Feel free to remove this moderators if you wish.\n\nThe reason for the problem is read returns a string, which gives characters when iterated over, while open produces a file object, which produces lines when...
[ 3, 0 ]
[]
[]
[ "csv", "django", "python" ]
stackoverflow_0007132903_csv_django_python.txt
Q: Appengine (python flavour) request source port With AppEngine, the IP of request can be retrieve in Python by : the_request_handler.request.environ["REMOTE_ADDR"] Do you know if it's possible to get the source port number and how to proceed? A: should be available via the_request_handler.request.environ["REMOTE...
Appengine (python flavour) request source port
With AppEngine, the IP of request can be retrieve in Python by : the_request_handler.request.environ["REMOTE_ADDR"] Do you know if it's possible to get the source port number and how to proceed?
[ "should be available via\nthe_request_handler.request.environ[\"REMOTE_PORT\"]\n\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "port", "python", "request" ]
stackoverflow_0007133181_google_app_engine_port_python_request.txt
Q: What is going on with PIL and the import statement I find this code in Django: # Try to import PIL in either of the two ways it can end up installed. try: from PIL import ImageFile as PILImageFile except ImportError: import ImageFile as PILImageFile and up until recently, I just blew it off as unimportant...
What is going on with PIL and the import statement
I find this code in Django: # Try to import PIL in either of the two ways it can end up installed. try: from PIL import ImageFile as PILImageFile except ImportError: import ImageFile as PILImageFile and up until recently, I just blew it off as unimportant. However I built PIL under my virtualenv in windows a...
[ "Edit: From the comment to my answer by @cgohlke, this will change in PIL1.2:\n\nthe support for importing from the standard\n namespace [has been dropped]; PIL now lives in the PIL namespace only\n\n\nI think the Django comment is pretty clear:\n# Try to import PIL in either of the two ways it can end up installe...
[ 4 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0007133193_python_python_imaging_library.txt
Q: Subprocess.communicate() returns char at a time rather than lines I am running Python 2.7.2 on Windows and trying to automate a number of command line tools using subprocess as follows: p = subprocess.Popen(mip4 + " status", bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) stdout...
Subprocess.communicate() returns char at a time rather than lines
I am running Python 2.7.2 on Windows and trying to automate a number of command line tools using subprocess as follows: p = subprocess.Popen(mip4 + " status", bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) stdout, stderr = p.communicate() for line in stdout: print line Rather t...
[ "If your aim to get output of the command , you should use check_output. \nIn [120]: for x in subprocess.check_output([\"/bin/sh\", \"-c\", \"ls - a\"]).split('\\n'):\n print x\n .....: \n .....: \n .\n ..\n cluster.py\n database1.py\n\n" ]
[ 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0006415804_python_subprocess.txt
Q: Which webserver to use with Django? (updated for use in 2011) I am asking this question because I am a beginner and I've read almost 90% of articles speaking about Django, but the problem is: Django was made and had problems for deploying, it is python, and python is not PHP! When reading Django tutorials, a begin...
Which webserver to use with Django? (updated for use in 2011)
I am asking this question because I am a beginner and I've read almost 90% of articles speaking about Django, but the problem is: Django was made and had problems for deploying, it is python, and python is not PHP! When reading Django tutorials, a beginner is in big problem, because he can find a tutorial "outdated" fo...
[ "\n1 - which one is the best for VPS, Apache or Nginx, using the latest\n release of course! please dont say: use lighty or cherokee...\n\nEither will work fine.\n\n2 - if for example the answer was: use ngnix, then, is it better to\n use one server or two, as in the past it was better to make two\n webservers?\...
[ 6 ]
[]
[]
[ "apache", "deployment", "django", "python" ]
stackoverflow_0007133409_apache_deployment_django_python.txt
Q: Except statement In a function check_price() I try to open a .txt file, that does not exist, to read and I wanted to use except statement to catch the IOerror. But after, I created a .txt file and I want to use the same function to read it. However my function doesn't read the file. Can anyone help me? I'm suppos...
Except statement
In a function check_price() I try to open a .txt file, that does not exist, to read and I wanted to use except statement to catch the IOerror. But after, I created a .txt file and I want to use the same function to read it. However my function doesn't read the file. Can anyone help me? I'm suppose to make a price chec...
[ "There are two problems. One, where you open the file, and two, the use of the while statement to open the file. If you think about it logically, you don't want to keep re-opening and closing that file, really. Just open it once, read each line from it, and close it. So your reading function might look like this:\n...
[ 3, 0, 0 ]
[ "The function is nonsensical. There's no reason to use a while loop here. In particular, it looks very easy for the logic to get into an infinite loop.\nHere are some suggestions:\n\nI would avoid the try/except and just check the existence of the file directly, using os.path.exists.\nIf the file doesn't already ...
[ -1 ]
[ "python" ]
stackoverflow_0007133571_python.txt
Q: datetime: print as seconds I have a datetime object. I want to print it as just number of seconds (i.e., 1 min 30.5 sec should print as 90.5 s). Can't seem to find a way to do it with strftime. A: I think that for your situation you'd be better off using a datetime.timedelta object. It has a function that will ...
datetime: print as seconds
I have a datetime object. I want to print it as just number of seconds (i.e., 1 min 30.5 sec should print as 90.5 s). Can't seem to find a way to do it with strftime.
[ "I think that for your situation you'd be better off using a datetime.timedelta object. It has a function that will do exactly what you want, datetime.timedelta.total_seconds().\n", "Datetimes are instants in time, unlike durations which are just numbers. The reason strftime won't say \"90.5s\" is that, well, t...
[ 12, 0 ]
[]
[]
[ "datetime", "python", "python_3.x" ]
stackoverflow_0007133977_datetime_python_python_3.x.txt
Q: Django query a model since its creation to an X time Having a such model: class HelpRequest(models.Model): creation_time = models.DateTimeField(auto_now_add=True) I want to query HelpRequest which are created within the last 5 mins, how can I achieve this? A: import datetime HelpRequest.objects.filter(creat...
Django query a model since its creation to an X time
Having a such model: class HelpRequest(models.Model): creation_time = models.DateTimeField(auto_now_add=True) I want to query HelpRequest which are created within the last 5 mins, how can I achieve this?
[ "import datetime\nHelpRequest.objects.filter(creation_time__gte=(datetime.datetime.now() - datetime.timedelta(minutes=5)))\n\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007134288_django_python.txt
Q: Max size of a file Python can open? I opened an 8 MB file in Python, because I wanted to batch change various types of file names. I went through and loaded the file into a string and used the string method replace to replace everything. I then noticed that only half of the file was being replaced; as if Python wa...
Max size of a file Python can open?
I opened an 8 MB file in Python, because I wanted to batch change various types of file names. I went through and loaded the file into a string and used the string method replace to replace everything. I then noticed that only half of the file was being replaced; as if Python wasn't fully opening the file. Is there so...
[ "No, there is no reachable maximum on the size of a file Python can open. 8 MB is tiny in modern terms. You made a mistake somewhere.\nPeople regularly load gigabytes of data into memory. Depending on your computer's RAM, whether it's 64- or 32- bit OS and processor, the practical maximum for you may be anywhere fr...
[ 21 ]
[]
[]
[ "limit", "python", "string" ]
stackoverflow_0007134338_limit_python_string.txt
Q: BeautifulSoup installed but not recognized when dev_appserver runs Update By adding BeautifulSoup.py to my app source, this error was gone :) Thanks @Ned Deily, that took along time, but was fruitful Ignore from here I have just one instance of python 2.5 installed with BeautifulSoup, still no luck!, what I ...
BeautifulSoup installed but not recognized when dev_appserver runs
Update By adding BeautifulSoup.py to my app source, this error was gone :) Thanks @Ned Deily, that took along time, but was fruitful Ignore from here I have just one instance of python 2.5 installed with BeautifulSoup, still no luck!, what I am I doing wrong, please help bash-3.2$ ls -ltr /Library/Frameworks/Py...
[ "You apparently have installed a second, newer instance of Python 2.6. Chances are that your Django app is installed and being run from another instance of Python 2.6, possibly the system Python 2.6 (/usr/bin/python or /usr/bin/python2.6). Type which python to see the path of the Python which has BeautifulSoup (/...
[ 4 ]
[]
[]
[ "beautifulsoup", "django", "python" ]
stackoverflow_0007134460_beautifulsoup_django_python.txt
Q: Django-registration combine databases I've installed the django-registration app succesfully and it works great. But now I want that when people are logged in, they have to fill in more data about theirself. Do I need to create an new django-app, so with a new database, or is it possible to save the data in the dj...
Django-registration combine databases
I've installed the django-registration app succesfully and it works great. But now I want that when people are logged in, they have to fill in more data about theirself. Do I need to create an new django-app, so with a new database, or is it possible to save the data in the djano-registration app database (the database...
[ "Look at the User-Profiles section of the auth application. It explains how to create a Profile object (basically a new table, not database), that is connected to the User object, and has whatever data you add to it. It can be retrieved with get_profile().\nJust to highlight something in the docs - get_profile() do...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007131667_django_python.txt
Q: Django select database objects based on previous query I'm currently working on a project where there is twitter-style one way following, and I've been unable to figure out how to select 'posts' in the database based on who the user is following. I'm using the default user functionality, and then this is my follow...
Django select database objects based on previous query
I'm currently working on a project where there is twitter-style one way following, and I've been unable to figure out how to select 'posts' in the database based on who the user is following. I'm using the default user functionality, and then this is my following model: class Following(models.Model): user = models....
[ "My django is getting rusty, but here goes:\nposts = Post.objects.filter(user__following__user=request.user)\n\n", "from django.db import transaction\n\n@transaction.commit_manually\ndef get_posts(following):\n posts = []\n for f in following:\n posts.append(Post.objects.filter(user=f))\n transact...
[ 3, 0 ]
[]
[]
[ "django", "models", "orm", "python", "sql" ]
stackoverflow_0007133194_django_models_orm_python_sql.txt
Q: Python search and replace not replacing properly I have this script that needs to replace a file extension and it is not doing so properly: import os import sys #directory is the directory we will work from directory = "C:\\Users\\joe\\Desktop" os.chdir(directory) whatToLookFor = ["Ca", "Cb", "Cd", "Ce", "Cf", ...
Python search and replace not replacing properly
I have this script that needs to replace a file extension and it is not doing so properly: import os import sys #directory is the directory we will work from directory = "C:\\Users\\joe\\Desktop" os.chdir(directory) whatToLookFor = ["Ca", "Cb", "Cd", "Ce", "Cf", "Cg", "Ch", "Ci", "Cj", "Ck", "Cl", "Cm", "Cn", "Co", ...
[ "Without knowing what your actual input is, it will be very difficult to help, however, I did notice one thing. It looks like you are trying to make sure you have two digit numbers in your buffer (after the item from whatToLookFor).\nIf that's true, life would probably be easier if you replaced this:\nif x < 10:\n ...
[ 2, 1, 0 ]
[]
[]
[ "python", "replace", "search" ]
stackoverflow_0007125510_python_replace_search.txt
Q: Inconsistency when I'm mapping lists into a dictionary using dict and zip - Python I tried this example and it worked fine: Map two lists into a dictionary in Python But if I replaced "keys" with this list: ['2', '3', '2', '3', '4', '2', '4', '2', '2', '3', '2', '3', '4'] and "values" with this list: [2, 3, 4, 5...
Inconsistency when I'm mapping lists into a dictionary using dict and zip - Python
I tried this example and it worked fine: Map two lists into a dictionary in Python But if I replaced "keys" with this list: ['2', '3', '2', '3', '4', '2', '4', '2', '2', '3', '2', '3', '4'] and "values" with this list: [2, 3, 4, 5, 6, 4, 2, 1, 1, 2, 3, 4, 5] The dict class tried to make a dictionary of the "values" p...
[ "Your keys list has duplicate values and so overwrite the values from the earlier duplicate keys.\n>>> keys = ['2', '3', '2-1', '3-1', '4', '2-2', '4-1', '2-3', '2-4', '3-2', '2-5', '3-3', '4-2']\n>>> values = [2, 3, 4, 5, 6, 4, 2, 1, 1, 2, 3, 4, 5]\n>>> dict(zip(keys, values))\n{'2-2': 4, '4-1': 2, '4-2': 5, '2-1'...
[ 7, 3, 2 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0007134568_dictionary_list_python.txt
Q: implementing multiple string replace() using lambda function I've found tons of solutions doing exactly what I'm trying to do WITHOUT lambda...but I'm learning lambda today... I have a string stri and I'm trying to replace some characters in stri that are all stored in a dictionary. bad_chars={"\newline":" ","\n...
implementing multiple string replace() using lambda function
I've found tons of solutions doing exactly what I'm trying to do WITHOUT lambda...but I'm learning lambda today... I have a string stri and I'm trying to replace some characters in stri that are all stored in a dictionary. bad_chars={"\newline":" ","\n": " ", "\b":" ", "\f":" ", "\r":" ", "\t":" ", "\v":" ", "\0x00":...
[ "If you really want to you can force a lambda function into it:\nprint ''.join(map(lambda x: bad_chars.get(x, x), stri))\n\nBut really there's absolutely no need to use a lambda function here. All you need is: \nprint ''.join(bad_chars.get(x, x) for x in stri)\n\nThis solution is also linear time (ie O(n)) whereas ...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007134360_python.txt
Q: Python (yield): all paths from leaves to root in a tree I want to generate all paths from every leaf to root in a tree. I'd like to do that with generators, to save memory (tree can be big). Here's my code: def paths(self, acc=[]): if self.is_leaf(): yield [self.node]+acc for child in self.childre...
Python (yield): all paths from leaves to root in a tree
I want to generate all paths from every leaf to root in a tree. I'd like to do that with generators, to save memory (tree can be big). Here's my code: def paths(self, acc=[]): if self.is_leaf(): yield [self.node]+acc for child in self.children: child.paths([self.node]+acc) But it doesn't work....
[ "This code only yields leaves that are (immediate) children of the root. The other ones get visited, they yield to the upper function, but the upper function does nothing with them. What you need is to yield them from the lower function to the upper one:\ndef paths(self, acc=[]):\n if self.is_leaf():\n yi...
[ 7, 1 ]
[]
[]
[ "python", "yield" ]
stackoverflow_0007134742_python_yield.txt
Q: Is there a way to pass variables to decorator? I have log in system, based on OpenID provider, and I want to create decorator like @login_required. But I have a problem - I need to check permission per object. I pass id to my views, so I want to know is there any way to pass it to decorator or it's impossible and ...
Is there a way to pass variables to decorator?
I have log in system, based on OpenID provider, and I want to create decorator like @login_required. But I have a problem - I need to check permission per object. I pass id to my views, so I want to know is there any way to pass it to decorator or it's impossible and I need to check users permission in my view.
[ "def outer(var1, var2):\n def inner(func)\n func.foo = var1\n func.bar = var2\n return func\n return inner\n\n@outer(myvar1, myvar2)\ndef myfunc():\n # whatever\n pass\n\nWhile you can't pass variables directly to the function which decorates your function, you can create another fu...
[ 3, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007134756_django_python.txt
Q: blender-python error i get this error : Traceback (most recent call last): File "movement", line 1, in (module) NameError: name 'GameLogic' is not defined import GameLogic cont = GameLogic.getCurrentController() fwd = cont.sensors['forword'] bck = cont.sensors['backword'] lft = cont.sensors['left'] rit =...
blender-python error
i get this error : Traceback (most recent call last): File "movement", line 1, in (module) NameError: name 'GameLogic' is not defined import GameLogic cont = GameLogic.getCurrentController() fwd = cont.sensors['forword'] bck = cont.sensors['backword'] lft = cont.sensors['left'] rit = cont .sensors['right'] m...
[ "GameLogic is C extension module. It will only run within the game engine, when executed from a python game logic controller, there are many example files online showing how this is done.\n" ]
[ 0 ]
[]
[]
[ "blender_2.49", "python" ]
stackoverflow_0006170594_blender_2.49_python.txt
Q: Why am I getting a prompt when using fabric? When I try to use fabric, it gives me a remote shell after I authenticate. Then when I exit, the fabric task runs. Why is this? Here's the output I received: user@locahost:~$ fab -H remote_host mytask [remote_host] Executing task 'mytask' [remote_host] run: python --ver...
Why am I getting a prompt when using fabric?
When I try to use fabric, it gives me a remote shell after I authenticate. Then when I exit, the fabric task runs. Why is this? Here's the output I received: user@locahost:~$ fab -H remote_host mytask [remote_host] Executing task 'mytask' [remote_host] run: python --version [remote_host] Login password: [remote_host] ...
[ "Could not open a connection to your authentication agent. tells me it's looking for ssh-agent or somesuch. Take a look at the .login/.profile/.bash_profile of the host you're connecting to for issues. Also, try initiating an SSH conneection manually and see if that gives any hints.\n" ]
[ 1 ]
[]
[]
[ "authentication", "fabric", "networking", "python", "ssh" ]
stackoverflow_0006883875_authentication_fabric_networking_python_ssh.txt
Q: when using zc.buildout encounter a "UserWarning" about double import pkg_resources when I run bin/buildout , the warning repeated like this: /Users/healdream/Playground/python/buildout/parts/buildout/site.py:262: UserWarning: Module pkg_resources was already imported from /System/Library/Frameworks/Python.framewor...
when using zc.buildout encounter a "UserWarning" about double import pkg_resources
when I run bin/buildout , the warning repeated like this: /Users/healdream/Playground/python/buildout/parts/buildout/site.py:262: UserWarning: Module pkg_resources was already imported from /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg_resources.py, but /Users/healdream/Playground/pytho...
[ "It was probably a isolation issue which was only addressed by the upgrade because it replaced the base installation. If it happens again, trying a virtualenv is a good idea:\n$ virtualenv --no-site-packages .\n$ bin/python bootstrap.py\n$ bin/buildout\n\n" ]
[ 0 ]
[]
[]
[ "buildout", "python" ]
stackoverflow_0006847715_buildout_python.txt
Q: Python Multithreading random behavior I have a multithreaded python application that does a bunch of processing on files. The main application is scanning a directory for new files. Whenever a file is found, this file is being processed (Image/Video editing, FTP uploading, saving metadata to a DB...) in other Pyth...
Python Multithreading random behavior
I have a multithreaded python application that does a bunch of processing on files. The main application is scanning a directory for new files. Whenever a file is found, this file is being processed (Image/Video editing, FTP uploading, saving metadata to a DB...) in other Python threads. A large part of those Processor...
[ "You don't need threads for this becuase you're already using subprocesses. Just let the subprocesses run and use Popen.poll() to check for completion.\n" ]
[ 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0006872345_multithreading_python.txt
Q: RegEx replace in Python I'm pretty new to regular expressions. I've worked out the string (?i)\$url\[([0-9])\] to match what I'm looking for. I want a string like "this is $url[2] a string" to be passed through that regex, have 2 passed to a function, which returns a string, and $url[2] is replaced with that strin...
RegEx replace in Python
I'm pretty new to regular expressions. I've worked out the string (?i)\$url\[([0-9])\] to match what I'm looking for. I want a string like "this is $url[2] a string" to be passed through that regex, have 2 passed to a function, which returns a string, and $url[2] is replaced with that string. How do I do that?
[ "def myrepl(match):\n num = int(match.group(1))\n # Do something here\n return str(num) # this will replace the $url[2]\n\nmystr = \"this is $url[2] a string\"\n\nprint re.sub(r'\\$url\\[([0-9])\\]', myrepl, mystr, flags=re.IGNORECASE)\n\n" ]
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007134959_python_regex.txt
Q: Why does 1 == True but 2 != True in Python? Possible Duplicate: Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language? A brief transcript from my interactive console: Python 2.7.2 (default, Jun 29 2011, 11:10:00) [GCC 4.6.1] on linux2 Type "help", "copyright", "credi...
Why does 1 == True but 2 != True in Python?
Possible Duplicate: Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language? A brief transcript from my interactive console: Python 2.7.2 (default, Jun 29 2011, 11:10:00) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> True ...
[ "Because Boolean in Python is a subtype of integers. From the documentation:\n\nBoolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmeti...
[ 36, 28, 13, 12, 5, 0, 0 ]
[ "It's binary. 0 is always False and 1 is always True. In python though any non-zero value, including negative values are always True.\n>>> if -1:\n... print 'a'\n...\na\n>>> if 2:\n... print 'a'\n...\na\n>>> if 0:\n... print 'a'\n...\n>>>\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0007134984_python.txt
Q: Problem logging into Facebook with Scrapy (I have asked this question on the Scrapy google-group without luck.) I am trying to log into Facebook using Scrapy. I tried the following in the interactive shell: I set the headers and created a request as follows: header_vals={'Accept-Language': ['en'], 'Content-Type':...
Problem logging into Facebook with Scrapy
(I have asked this question on the Scrapy google-group without luck.) I am trying to log into Facebook using Scrapy. I tried the following in the interactive shell: I set the headers and created a request as follows: header_vals={'Accept-Language': ['en'], 'Content-Type': ['application/ x-www-form-urlencoded'], 'Acce...
[ "Notice that \"meta redirect\" text near redirecting. Facebook has a noscript tag to automatically redirect clients without javascript to \"/login.php?_fb_noscript=1\". The problem is that you're posting to \"/login.php\" instead and always getting redirected by meta refresh header. \nEven if you get over this prob...
[ 1 ]
[]
[]
[ "python", "scrapy", "screen_scraping" ]
stackoverflow_0007093312_python_scrapy_screen_scraping.txt
Q: Argparse Subparsers, and linking to Classes We have a simple Python program to manage various types of in-house servers, using argparse: manage_servers.py <operation> <type_of_server> Operations are things like check, build, deploy, configure, verify etc. Types of server are just different types of inhouse serve...
Argparse Subparsers, and linking to Classes
We have a simple Python program to manage various types of in-house servers, using argparse: manage_servers.py <operation> <type_of_server> Operations are things like check, build, deploy, configure, verify etc. Types of server are just different types of inhouse servers we use. We have a generic server class, then s...
[ "Just use the parser.add_subparsers(dest=... argument with a mapping of type_of_server to classes:\nsubparsers = parser.add_subparsers(dest='operation', help='The operation that you want to run on the server.')\n...\nserver_types = dict(spam=SpamServer, ham=HamServer)\nargs = parser.parse_args()\nserver = server_ty...
[ 2 ]
[]
[]
[ "argparse", "command_line", "parsing", "python" ]
stackoverflow_0006727932_argparse_command_line_parsing_python.txt
Q: difflib on Ruby Is there a library similar to Python's difflib on Ruby? Particularly, I need one that has a method similar to difflib.get_close_matches. Any recommendations? A: You can take a look at diff-lcs. A: After some research, I suggest using amatch or SimMetrics (with JRuby) and manually implement the ...
difflib on Ruby
Is there a library similar to Python's difflib on Ruby? Particularly, I need one that has a method similar to difflib.get_close_matches. Any recommendations?
[ "You can take a look at diff-lcs.\n", "After some research, I suggest using amatch or SimMetrics (with JRuby) and manually implement the get_close_matches method. Both libs offer implementations of many string similarity algorithms.\n" ]
[ 0, 0 ]
[]
[]
[ "fuzzy_comparison", "python", "ruby", "string", "string_matching" ]
stackoverflow_0004916966_fuzzy_comparison_python_ruby_string_string_matching.txt
Q: Problem with cx_freeze and utf-8 characters not showing I'm trying to compile a python script which contains spanish strings. If i run the .py, it's displayed correctly. Compilation runs fine, but when I run the resulting .exe, the non-ascii characters are replaced with error chars, and no error reported. I coul...
Problem with cx_freeze and utf-8 characters not showing
I'm trying to compile a python script which contains spanish strings. If i run the .py, it's displayed correctly. Compilation runs fine, but when I run the resulting .exe, the non-ascii characters are replaced with error chars, and no error reported. I couldn't find anyone asking about the same problem, am I the only...
[ "It is not possible to be certain, but assuming that what appears to be in your source file and what appears to be displayed has not been transmogrified in transmission, your problem is this:\nYou expect to see (a-acute, n-tilde, o-acute), but you actually see \"error characters\" (no-break space aka NBSP, currency...
[ 1 ]
[]
[]
[ "cx_freeze", "python", "utf_8" ]
stackoverflow_0007101342_cx_freeze_python_utf_8.txt
Q: When does running Jython on a .py file generate a .class file? I just started playing with Jython, and sometimes running jython on a .py file generates a .class file, but this doesn't always happen. At first I thought the trigger was that you had to define a Python class inside the .py file, but evidently a .class...
When does running Jython on a .py file generate a .class file?
I just started playing with Jython, and sometimes running jython on a .py file generates a .class file, but this doesn't always happen. At first I thought the trigger was that you had to define a Python class inside the .py file, but evidently a .class file is not always generated even then. What is the mechanism that ...
[ "With regular Python, .pyc files are generated when you import a module but not when it's the __main__ module.\nIt is the same with Jython -- .class files are generated when you import a Jython module. \nYou can use jythonc to manually compile a module.\n" ]
[ 5 ]
[]
[]
[ "jvm_languages", "jython", "python" ]
stackoverflow_0007135542_jvm_languages_jython_python.txt
Q: Sort python list by function I have a function that takes an object as an argument and gives me a number. I wish to use this number as the key to sort my list. If I were to iterate over the list I would do something like: sorted_list = [] for object in my_list_of_objects: i = my_number_giving_function(object) ...
Sort python list by function
I have a function that takes an object as an argument and gives me a number. I wish to use this number as the key to sort my list. If I were to iterate over the list I would do something like: sorted_list = [] for object in my_list_of_objects: i = my_number_giving_function(object) sorted_list.insert(i, object) ...
[ "sort(my_list_of_objects, key=my_number_giving_function)\n\nsame for sorted, see the Python Sorting HOWTO\n" ]
[ 25 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0007135836_list_python_sorting.txt
Q: Python design mistakes A while ago, when I was learning Javascript, I studied Javascript: the good parts, and I particularly enjoyed the chapters on the bad and the ugly parts. Of course, I did not agree with everything, as summing up the design defects of a programming language is to a certain extent subjective -...
Python design mistakes
A while ago, when I was learning Javascript, I studied Javascript: the good parts, and I particularly enjoyed the chapters on the bad and the ugly parts. Of course, I did not agree with everything, as summing up the design defects of a programming language is to a certain extent subjective - although, for instance, I g...
[ "\nIs there a blog entry or some book describing design mistakes for Python? \n\nYes.\nIt's called the Py3K list of backwards-incompatible changes.\nStart here: http://docs.python.org/release/3.0.1/whatsnew/3.0.html\nRead all the Python 3.x release notes for additional details on the mistakes in Python 2.\n", "Yo...
[ 33, 33, 23, 5, 5, 4, 2, 1, 1, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004603349_python.txt
Q: Using Django South to move from concrete inheritance to abstract inheritance I have an existing Django project that has several models using concrete inheritance of a base class. After closer consideration, and after reading about what people like Jacob Kaplan-Moss have to say about it, using this concrete inherit...
Using Django South to move from concrete inheritance to abstract inheritance
I have an existing Django project that has several models using concrete inheritance of a base class. After closer consideration, and after reading about what people like Jacob Kaplan-Moss have to say about it, using this concrete inheritance is unnecessary in my case. I would like to migrate to using an abstract base ...
[ "\nAdd NewBaseModel, we use different name so it doesn't conflict with current non-abstract one (South would actually delete BaseModel otherwise).\nclass NewBaseModel(models.Model):\n user = models.ForeignKey(User)\n another_field = models.CharField(max_length=1000)\n\n class Meta:\n abstract = True...
[ 7, 1 ]
[]
[]
[ "django", "django_south", "migration", "python" ]
stackoverflow_0007108899_django_django_south_migration_python.txt
Q: How do I get the Application ID at runtime I need the Application ID to construct the correct <applicationid>.appspotmail.com address, and I'm having a hard time finding out how to retrieve it at runtime. A: The recommended approach now is to use app_identity.get_application_id(): http://code.google.com/appengin...
How do I get the Application ID at runtime
I need the Application ID to construct the correct <applicationid>.appspotmail.com address, and I'm having a hard time finding out how to retrieve it at runtime.
[ "The recommended approach now is to use app_identity.get_application_id():\nhttp://code.google.com/appengine/docs/python/appidentity/functions.html#get_application_id\nSee the warning box here for details:\nhttp://code.google.com/appengine/docs/python/runtime.html#Requests_and_Domains\n", "You can get it using:\n...
[ 13, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005523281_google_app_engine_python.txt
Q: Python: how to get subclass's new attributes name in base class's method? I want to put all attribute names in SubClass to a list, I want to do that in Base class. How can I do that? My method now is: class Base(): def __init__(self): # print SubClass' new attribues' names ('aa' and 'bb' for example) ...
Python: how to get subclass's new attributes name in base class's method?
I want to put all attribute names in SubClass to a list, I want to do that in Base class. How can I do that? My method now is: class Base(): def __init__(self): # print SubClass' new attribues' names ('aa' and 'bb' for example) for attr in dir(self): if not hasattr(Base, attr): ...
[ "As the @JohnZwinck suggested in a comment, you're almost certainly making a design mistake if you need to do this. Without more info, however, we can't diagnose the problem.\nThis seems the simplest way to do what you want:\nclass Base(object):\n cc = '' # this won't get printed\n def __init__(self):\n ...
[ 5 ]
[]
[]
[ "attributes", "python", "subclass" ]
stackoverflow_0007136154_attributes_python_subclass.txt
Q: How can I permanently store commands in the Python REPL/prompt? Is there a way to store commands in Python? For example, to store a bash command I can put: # in .bash_profile alias myproject="cd /path/to/my/project" $ project Is there a way to store a command, for example something like this: 'store' profile="fr...
How can I permanently store commands in the Python REPL/prompt?
Is there a way to store commands in Python? For example, to store a bash command I can put: # in .bash_profile alias myproject="cd /path/to/my/project" $ project Is there a way to store a command, for example something like this: 'store' profile="from userprofile.models import Profile" >>> profile which will work i...
[ "In Bash, I'm assuming you are defining this aliases in .profile, .bash_rc or a similar file. In that file, add the line\nexport PYTHONSTARTUP=~/.python_rc.py\n\nThis will allow you to create a .python_rc.py file that is included whenever you start a session in the Python prompt/REPL. (It will not be included when ...
[ 5, 4, 1, 1 ]
[]
[]
[ "django", "python", "read_eval_print_loop" ]
stackoverflow_0007135583_django_python_read_eval_print_loop.txt
Q: Python For Loop Slowing With Time So I'm having a little trouble dealing with for loops in Python - as far as I can tell, they're getting slower with time. I'm looping over a range inside of a range, and as time passes, the loop noticeably slows. This is done inside of a game engine, if it matters. Could anyone te...
Python For Loop Slowing With Time
So I'm having a little trouble dealing with for loops in Python - as far as I can tell, they're getting slower with time. I'm looping over a range inside of a range, and as time passes, the loop noticeably slows. This is done inside of a game engine, if it matters. Could anyone tell me what the issue is? Here's a quick...
[ "This is another case of \"need more information\". However, Python has a standard way of constructing nested loops like this efficiently, itertools.product:\nfrom itertools import product\n\nfor x, y, z in product(xrange(xs), xrange(zs), xrange(ys)):\n vp = [x * vs, y * vs, z * vs]\n v = Cube(vp)\n\nIt doesn...
[ 16, 1 ]
[]
[]
[ "for_loop", "performance", "python", "python_3.x", "range" ]
stackoverflow_0007136200_for_loop_performance_python_python_3.x_range.txt
Q: How to read muliple values from a config file using config parser I have made a Config file and have multiple values for a keyword as: [section] database: mysql , sqlite and i want to access the values separately..How to go about it?? A: How about using standard ConfigParser and not using comma? [section] datab...
How to read muliple values from a config file using config parser
I have made a Config file and have multiple values for a keyword as: [section] database: mysql , sqlite and i want to access the values separately..How to go about it??
[ "How about using standard ConfigParser and not using comma?\n[section]\n\ndatabase: mysql sqlite\n\nWhen you get the variable, just split it:\ndatabases = configparser.get('database').split()\n\n", "Using space for separating options has the disadvantage that if space is already present in the options, as in the ...
[ 8, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003931178_python.txt
Q: [python]: confused by super() Possible Duplicate: Understanding Python super() Class B subclasses class A, so in B's __init__ we should call A's __init__ like this: class B(A): def __init__(self): A.__init__(self) But with super(), I saw something like this: class B(A): def __init__(self): ...
[python]: confused by super()
Possible Duplicate: Understanding Python super() Class B subclasses class A, so in B's __init__ we should call A's __init__ like this: class B(A): def __init__(self): A.__init__(self) But with super(), I saw something like this: class B(A): def __init__(self): super(B, self).__init__() #o...
[ "super() returns an instance of the base class, so self gets implicitly passed to __init__() like in any other method call.\nWith regards to your second question, that's correct. Calling super() without an instance as the second argument returns a reference to the class itself, not an instance constructed from your...
[ 5 ]
[]
[]
[ "python", "super" ]
stackoverflow_0007136406_python_super.txt
Q: Escaping spaces in alias in Python? This is where the file exists: ~/Library/Application Support/Something/something.sqldb This is my command to access the file: connect('~/Library/Application\ Support/Something/something.sqldb') The command does not work because the file, something.sqldb, can not be found. Any ...
Escaping spaces in alias in Python?
This is where the file exists: ~/Library/Application Support/Something/something.sqldb This is my command to access the file: connect('~/Library/Application\ Support/Something/something.sqldb') The command does not work because the file, something.sqldb, can not be found. Any ideas on how to fix that? Thanks for the ...
[ "The problem is not the space, it is the tilde. Python is not a shell and does not expand special characters in strings. There are functions that can do that. The os.path.expanduser and os.path.expandvars can expand tildes and $VAR portions of the string for you.\n", "Try this:\nconnect('/home/YOURNAME/Library/Ap...
[ 3, 2, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0007136172_python_sqlite.txt
Q: I can't figure out this Tkinter error I'm using Python's Tkinter to create a GUI for a project i'm working on. When I try to run part of the code though, I get this error: Traceback (most recent call last): File "calculator.py", line 59, in <module> app = Application() File "calculator.py", line 28, in __i...
I can't figure out this Tkinter error
I'm using Python's Tkinter to create a GUI for a project i'm working on. When I try to run part of the code though, I get this error: Traceback (most recent call last): File "calculator.py", line 59, in <module> app = Application() File "calculator.py", line 28, in __init__ self.create_widgets() File "cal...
[ "Ok, so I missed this the first time, but the issue is actually that you are trying to add a Button to a list:\nself.button_list += Button(self, text = txt, command = fcn)\n\nIf you simply wrap the Button in brackets, the error goes away (which makes sense because you are supposed to be able to add two lists):\nsel...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007136325_python_tkinter.txt
Q: Python Condition Statement with For-Loop I am attempting to write a single line of Python code for the following: is_valid = False for single_object in object_list: if single_object.test == test: is_valid = True if not is_valid: return 'Bad data!' I know that there has to be a way to accomplish this in l...
Python Condition Statement with For-Loop
I am attempting to write a single line of Python code for the following: is_valid = False for single_object in object_list: if single_object.test == test: is_valid = True if not is_valid: return 'Bad data!' I know that there has to be a way to accomplish this in less code. I mean, it's Python!
[ "is_valid = any(o.test == test for o in object_list)\n\nThe any(iterable) function returns True if any of the values in iterable are True, and False if none of them are. I'm using a \"generator expression\" to go through the values in object_list and evaluate the condition.\n", "Less code is often not better code...
[ 9, 2, 0 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0007136431_optimization_python.txt
Q: learn python the hard way exercise 26 trouble I am doing exercise 26 in learn python the hard way and have been struggling on it. I have read it backwards and everything, but in line 77 I get : sentence = "All god \t things come to those who weight." ^ SyntaxError: invalid syntax I dont know why the ar...
learn python the hard way exercise 26 trouble
I am doing exercise 26 in learn python the hard way and have been struggling on it. I have read it backwards and everything, but in line 77 I get : sentence = "All god \t things come to those who weight." ^ SyntaxError: invalid syntax I dont know why the arrow is at the e . I dont just want to know how to f...
[ "You're probably missing a close bracket, brace, or parenthesis on the previous line of code.\nEdit: From the code:\nprint \"We'd have %d beans, %d jars, and %d crabapples.\" % secret_formula(start_pont\n\nThere is no close parenthesis at the end of the line.\nThis is almost always the problem if you have a SyntaxE...
[ 4, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007136513_python.txt
Q: Pexpect spawn.expect() seems to be unreliable in detecting process output I have a class, ServerManager, which monitors and interfaces with another process using pexpect. Unfortunately, there is not a cleaner way to do this. The process in question does not provide an API. The ServerManager needs to monitor the pr...
Pexpect spawn.expect() seems to be unreliable in detecting process output
I have a class, ServerManager, which monitors and interfaces with another process using pexpect. Unfortunately, there is not a cleaner way to do this. The process in question does not provide an API. The ServerManager needs to monitor the process's output and trigger events when it recognizes specific patterns. Because...
[ "You have here two threads making a blocking call on the same file descriptor. I would implement this is a single threaded asynchronous event loop. The expect method should be able to watch for more than one string can invoke a callback function for each outcome from one call. I'm not sure pexpect can actually do t...
[ 1 ]
[]
[]
[ "multithreading", "pexpect", "python", "thread_safety" ]
stackoverflow_0007136079_multithreading_pexpect_python_thread_safety.txt
Q: Python: Latex symbols to unicode? I have fond several answers hinting how to solve unicode to latex symbols conversion. For example turning u'á' into \'{a}. Well I need it the other way around! So I made some research and fond this dictionary. Since the mapping seems to be bijective, I thought of turning the dicti...
Python: Latex symbols to unicode?
I have fond several answers hinting how to solve unicode to latex symbols conversion. For example turning u'á' into \'{a}. Well I need it the other way around! So I made some research and fond this dictionary. Since the mapping seems to be bijective, I thought of turning the dictionary the other way around. But I can't...
[ "The notation u'\\u0020' is just an escape sequence that specifies the space character, only it does so by specifying it by character code. The author of the dictionary probably did it this way so that it would be obvious if something was missing, but you don't need to perform any special conversion to use the dict...
[ 4, 1 ]
[]
[]
[ "latex", "python", "symbols", "unicode" ]
stackoverflow_0007136584_latex_python_symbols_unicode.txt
Q: python for loops Im trying to use this http://code.google.com/p/pywhois/ along with the socket.gethostbyaddr . import socket import pywhois revip = socket.gethostbyaddr('50.57.48.133') whois = pywhois.whois(revip[0]) for i in whois.emails: print Gives me three lines of nothing. Im trying to print out the emai...
python for loops
Im trying to use this http://code.google.com/p/pywhois/ along with the socket.gethostbyaddr . import socket import pywhois revip = socket.gethostbyaddr('50.57.48.133') whois = pywhois.whois(revip[0]) for i in whois.emails: print Gives me three lines of nothing. Im trying to print out the emails from the whois quer...
[ "print i\n\nThat should solve your problem.\n", "To get the code working, you need to add i after print:\nfor i in whois.emails:\n print i # you may see print(i) because in Python 3 print is a function.\n # and it does not matter in Python < 3\n\nTo get this format \n\n['josh.odom@rackspace.com', 'josh....
[ 2, 2, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0007136679_loops_python.txt
Q: Drawing a radius on olwidget in django I'm using olwidget inside of django to draw some maps. In one of my forms, I ask the user for a location and a radius. The location is input using the OpenLayers map provided by olwidget, and the radius is the slider from jquery-ui. What I would like to do is draw a radius ...
Drawing a radius on olwidget in django
I'm using olwidget inside of django to draw some maps. In one of my forms, I ask the user for a location and a radius. The location is input using the OpenLayers map provided by olwidget, and the radius is the slider from jquery-ui. What I would like to do is draw a radius circle on the map that updates as the user m...
[ "I think you might be able to override the template that renders the OpenLayers map. You can do this by creating \"templates/olwidget/multi_layer_map.html\" within your app. In there you'll likely need to do something like this (adapted from the original):\n<div id=\"{{ id }}\"></div>\n{{ layer_html|join:\"\" }}\n<...
[ 0 ]
[]
[]
[ "django", "javascript", "olwidget", "openlayers", "python" ]
stackoverflow_0007136948_django_javascript_olwidget_openlayers_python.txt
Q: How can I create a tuple where each of the members are compared by an expression? Well, here is the thing: I have the following Haskell code, this one: [ (a, b, c) | c <- [1..10], b <- [1..10], a <- [1..10], a ^ 2 + b ^ 2 == c ^ 2 ] Which will returns [(4,3,5),(3,4,5),(8,6,10),(6,8,10)] For those who aren't fami...
How can I create a tuple where each of the members are compared by an expression?
Well, here is the thing: I have the following Haskell code, this one: [ (a, b, c) | c <- [1..10], b <- [1..10], a <- [1..10], a ^ 2 + b ^ 2 == c ^ 2 ] Which will returns [(4,3,5),(3,4,5),(8,6,10),(6,8,10)] For those who aren't familiar with this, I'll explain: It returns a tuple (a,b,c), where each of these "definit...
[ "It's possible in Python with one long line and with no import. Python's list comprehensions can be used with multiple variables:\n\n>>> [ (a, b, c) for c in range(1, 11) for b in range(1, 11) for a in range(1, 11) if a*a + b*b == c*c ]\n[(4, 3, 5), (3, 4, 5), (8, 6, 10), (6, 8, 10)]\n\n", "Ruby solution:\n(1..1...
[ 12, 11, 9, 5, 1 ]
[]
[]
[ "haskell", "python", "ruby" ]
stackoverflow_0007136921_haskell_python_ruby.txt
Q: Is there a difference between -1 and False in Python? I have always thought that using -1 in a condition is alway the same as the writing False (boolean value). But from my code, I get different results: Using True and False: def count(sub, s): count = 0 index = 0 while True: if string.find(s, ...
Is there a difference between -1 and False in Python?
I have always thought that using -1 in a condition is alway the same as the writing False (boolean value). But from my code, I get different results: Using True and False: def count(sub, s): count = 0 index = 0 while True: if string.find(s, sub, index) != False: count += 1 in...
[ "string.find doesn't return a boolean so string.find('banana', 'nana', index) will NEVER return 0 (False) regardless of the value of index.\n>>> import string\n>>> help(string.find)\nHelp on function find in module string:\n\nfind(s, *args)\n find(s, sub [, start [, end]]) -> int\n\n Return the lowest index i...
[ 4, 2, 1, 0 ]
[]
[]
[ "boolean", "python" ]
stackoverflow_0007135801_boolean_python.txt
Q: how to correct this in python 3.0 I am a newer to python. After I leraned some basic in python, I try to write some program by imitating other's. And I find some code in python2.0 and it can't work in 3.0. How can I fix it. import sys import os import string headers = [ ('JFIF', 6, 'jpg'), ('GIF', 0, 'gif'), ('PN...
how to correct this in python 3.0
I am a newer to python. After I leraned some basic in python, I try to write some program by imitating other's. And I find some code in python2.0 and it can't work in 3.0. How can I fix it. import sys import os import string headers = [ ('JFIF', 6, 'jpg'), ('GIF', 0, 'gif'), ('PNG', 1, 'png') ] marker = [] fileName =...
[ "change\nheaders = [ ('JFIF', 6, 'jpg'), ('GIF', 0, 'gif'), ('PNG', 1, 'png') ] \n...\nstring.find(line, flag)\n\nto\nheaders = [ (b'JFIF', 6, 'jpg'), (b'GIF', 0, 'gif'), (b'PNG', 1, 'png') ] \n...\nline.find(flag)\n\nthe string. change is really just moving the call to the object rather than using a library.\nthe ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007137314_python.txt
Q: Understanding logic in python (Exercise 27 of Learn Python the Hard Way) Could someone explain exercise 27 of learn python the hard way to me? Here is an image showing the section i don't understand. Is it saying that assuming the left column of the table is true, is the answer true? eg if x = y is not false, is ...
Understanding logic in python (Exercise 27 of Learn Python the Hard Way)
Could someone explain exercise 27 of learn python the hard way to me? Here is an image showing the section i don't understand. Is it saying that assuming the left column of the table is true, is the answer true? eg if x = y is not false, is x=y true? yes. but then.. if x = y is false and true, is x=y true? no??
[ "For each table, if you enter (expression in left-hand column) the result is (corresponding value in right-hand column); the table header shows the operator being explained. So, for example, if you enter \"not True\" as an expression, the result will be False.\nEdit:\nGeeze Louise - look, it's really simple. For ex...
[ 6, 5, 3, 2, 2, 1, 1, 1, 0 ]
[]
[]
[ "logic", "python" ]
stackoverflow_0004445948_logic_python.txt
Q: Accessing other class' function in Python I'm very new to Python, so sorry about what will surely be an obvious question. I want the class Computer_paddle to be able to call Ball's function, y_position(), and get the return value. But it doesn't seem to be doing that, telling me: "global name 'ball' is not defined...
Accessing other class' function in Python
I'm very new to Python, so sorry about what will surely be an obvious question. I want the class Computer_paddle to be able to call Ball's function, y_position(), and get the return value. But it doesn't seem to be doing that, telling me: "global name 'ball' is not defined". Is there something special I need to do to...
[ "No, but you need to have a reference to an object in order to access its methods. Since you never bind ball to anything, there's no object to call the methods on. Did you mean to create ball as an instance of Ball at a global level?\n", "Right now all the attributes and methods you defined for the \"Ball\" class...
[ 3, 3, 2 ]
[]
[]
[ "class", "python" ]
stackoverflow_0007137437_class_python.txt
Q: How to match '-' literally inside [..] in regular expression I am trying to match a '-' inside a [..] block using regular expressions in python, but, I am not sure how to make that happen, since '-' denotes ranges in that block. Edit: my failing regex: regex = re.compile("^[0-9+-*/]+$") A: From the docs: If you...
How to match '-' literally inside [..] in regular expression
I am trying to match a '-' inside a [..] block using regular expressions in python, but, I am not sure how to make that happen, since '-' denotes ranges in that block. Edit: my failing regex: regex = re.compile("^[0-9+-*/]+$")
[ "From the docs:\n\nIf you want to include a ']' or a '-' inside a set, precede it with a backslash, or place it as the first character.\n\n", "Just place it at the beginning of the [] (character class):\nregex = re.compile(\"^[-0-9+*/]+$\")\n\nWhy does it work?\nWhen you place the hyphen at the beginning of the c...
[ 9, 6 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007137817_python_regex.txt
Q: How can I add a lot of Buttons to the tkinter Frame efficiently? I want to add 10 buttons to Tkinter, named One to Ten. I basically just used the brute force method, adding each button as I went, in the init function of my application's class. It works, but I want to minimize the code used, to be more efficient, s...
How can I add a lot of Buttons to the tkinter Frame efficiently?
I want to add 10 buttons to Tkinter, named One to Ten. I basically just used the brute force method, adding each button as I went, in the init function of my application's class. It works, but I want to minimize the code used, to be more efficient, such as using a data structure to hold all the buttons. I was thinking ...
[ "Instead of naming the buttons self.one, self.two, etc., it would be more convenient to refer to them by indexing a list, such as self.button.\nIf the buttons do different things, then you just have to explicitly\nassociate buttons with callbacks. For example:\nname_callbacks=(('One',self.callback_one),\n ...
[ 5, 1 ]
[]
[]
[ "button", "python", "tkinter" ]
stackoverflow_0007137636_button_python_tkinter.txt
Q: Example for ast.NodeTransformer that mutates an equation This is a continuation of my last question. I want to parse an equation and work on the ast I get. What I want to do is basically randomly scramble it so I get a new equation, that has to be also a valid function. This is to be used in a genetic algorithm. ...
Example for ast.NodeTransformer that mutates an equation
This is a continuation of my last question. I want to parse an equation and work on the ast I get. What I want to do is basically randomly scramble it so I get a new equation, that has to be also a valid function. This is to be used in a genetic algorithm. Here is where I start: class Py2do(ast.NodeTransformer): def _...
[ "So the input and the output are Fortran code? And you want to use arbitrary Fortran expressions/statements? (Including array slices, ...?) Fortran is a pretty complex language; reading it requires pretty much a full parser.\nPerhaps you want to use an program transformation tool that can already manipulate Fort...
[ 1 ]
[ "What are you trying to do? Looking for the right permutation of an equation might be easy but time consuming (n! possibilities), but generating new ones and optimize those using a genetic algorithm is imho impossible, because it`s not an optimization problem... For example x^0.00 and x^0.01 are fundamental differe...
[ -1 ]
[ "abstract_syntax_tree", "genetic_programming", "python" ]
stackoverflow_0006385292_abstract_syntax_tree_genetic_programming_python.txt
Q: Advanced functions in Django templates? I need to add a <br/> after each character in a string which I'm passing into the template. While one way of doing it would involve doing it before it is passed into the template (i.e. in the Python code), I'm wondering if it is possible to do it in the actual template. Or w...
Advanced functions in Django templates?
I need to add a <br/> after each character in a string which I'm passing into the template. While one way of doing it would involve doing it before it is passed into the template (i.e. in the Python code), I'm wondering if it is possible to do it in the actual template. Or would I be better off creating a helper functi...
[ "Strings in Python are sequences, therefore the individual characters in them can be joined.\n", "How about you make such a function in the javascript, and after passing the string to the template, instead of using it directly, you can call that function on the string, and the function returns the string with eve...
[ 5, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007138055_django_python.txt
Q: How to I pass a value from a child script to a parent script that are both running at the same time? Return a value early to a calling process in Python? Hello, I want to ask is there a way to have one script call another script, have both those scripts running at the same time, and have the child script send a va...
How to I pass a value from a child script to a parent script that are both running at the same time?
Return a value early to a calling process in Python? Hello, I want to ask is there a way to have one script call another script, have both those scripts running at the same time, and have the child script send a value to the parent script long before that child script is done running (WITHOUT exiting that child script ...
[ "You could use multiprocessing to launch the child script from the parent script.\nA mp.Queue could be used to communicate output from the child script back to the parent. Here is a simple example:\nparent.py:\nimport multiprocessing as mp\nimport child\n\nif __name__ == '__main__':\n queue = mp.Queue()\n pro...
[ 3, 1 ]
[]
[]
[ "ipc", "python" ]
stackoverflow_0007138088_ipc_python.txt
Q: is OverflowError actually raised? According to the python documentation exception OverflowError Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for long integers (which would rather raise MemoryError than give up) and for most operations with pl...
is OverflowError actually raised?
According to the python documentation exception OverflowError Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for long integers (which would rather raise MemoryError than give up) and for most operations with plain integers, which return a long integ...
[ "Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) \n[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> float(10**1000)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nOverflowError: long in...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0007138387_python.txt
Q: Is Python's "with" monadic? Like many a foolhardy pioneer before me, I'm endeavoring to cross the trackless wasteland that is Understanding Monads. I'm still staggering through, but I can't help noticing a certain monad-like quality about Python's with statement. Consider this fragment: with open(input_filename, ...
Is Python's "with" monadic?
Like many a foolhardy pioneer before me, I'm endeavoring to cross the trackless wasteland that is Understanding Monads. I'm still staggering through, but I can't help noticing a certain monad-like quality about Python's with statement. Consider this fragment: with open(input_filename, 'r') as f: for line in f: ...
[ "It's almost too trivial to mention, but the first problem is that with isn't a function and doesn't take a function as an argument. You can easily get around this by writing a function wrapper for with:\ndef withf(context, f):\n with context as x:\n f(x)\n\nSince this is so trivial, you could not bother ...
[ 24, 12, 9, 4 ]
[]
[]
[ "functional_programming", "monads", "python" ]
stackoverflow_0007131027_functional_programming_monads_python.txt
Q: encoding string "afile" is a previously existing file. handle=open("afile",'r+b') data=handle.readline() handle.close() # signgenerator is a hashlib.md5() object signgenerator.update(data) hex=signgenerator.hexdigest() print(hex) # prints out 061e3f139c80d04f039b7753de5313ce and write this to a file f...
encoding string
"afile" is a previously existing file. handle=open("afile",'r+b') data=handle.readline() handle.close() # signgenerator is a hashlib.md5() object signgenerator.update(data) hex=signgenerator.hexdigest() print(hex) # prints out 061e3f139c80d04f039b7753de5313ce and write this to a file f=open("syncDB.txt",'a...
[ "You need to unpickle the data:\npickle.load(open('syncDB.txt', 'r+b'))\n\nWhat you have there is pickled data. Proof:\n\n>>> import pickle\n>>> pickle.loads(b'\\x80\\x03X \\x00\\x00\\x00061e3f139c80d04f039b7753de5313ceq\\x00.\\x80\\x03X \\x00\\x00\\x00d9afd4bb6bc57679f6b10c0b9610d2e0q\\x00.\\x80\\x03X \\x00\\x00\\...
[ 2, 1 ]
[]
[]
[ "encode", "md5", "python", "string" ]
stackoverflow_0007138572_encode_md5_python_string.txt
Q: anything wrong with using pyparsing i've written this to parse my own .dotf file: def parseFromDOTF(file_path): comment = "%" + restOfLine typeToken = CaselessKeyword("@TYPE") attrToken = CaselessKeyword('@ATTRIBUTE') ident = Word(alphas,alphanums) type = Suppress(typeToken) + ident columnL...
anything wrong with using pyparsing
i've written this to parse my own .dotf file: def parseFromDOTF(file_path): comment = "%" + restOfLine typeToken = CaselessKeyword("@TYPE") attrToken = CaselessKeyword('@ATTRIBUTE') ident = Word(alphas,alphanums) type = Suppress(typeToken) + ident columnList = Group(delimitedList(nums)) attr...
[ "nums equals the string '0123456789'.\nSo the definition\ncolumnList = Group(delimitedList(nums))\n\ntells pyparsing that a columnList should be a comma-delimited list of strings,\nwith each string literally being '0123456789'.\nTo instead match a comma-delimited list of \"words\" composed of characters from the st...
[ 3 ]
[]
[]
[ "exception_handling", "pyparsing", "python" ]
stackoverflow_0007138378_exception_handling_pyparsing_python.txt
Q: A question regarding a class and it's methods I am currently trying to write an ircbot and have gotten stuck. As you can see I define a method for the ircBot class, connect, which creates a socket object. I want to use this object in the sendCmd method, is this possible? I have been looking around google and stack...
A question regarding a class and it's methods
I am currently trying to write an ircbot and have gotten stuck. As you can see I define a method for the ircBot class, connect, which creates a socket object. I want to use this object in the sendCmd method, is this possible? I have been looking around google and stackoverflow but have not been able to work out a solut...
[ "The trick is the first parameter to the methods, normally named self in Python. When you call the methods, this parameter is automatically passed.\nIt's the instance of the class -- so if you do ircbot.sendCmd(cmd), sendCmd gets ircbot as self, and so it could use itself as self.sendCmd if you wanted.\nYou can add...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007138629_python.txt
Q: How to write a list to a file with newlines in Python3 I'm trying to write an array (list?) to a text file using Python 3. Currently I have: def save_to_file(*text): with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile: for lines in text: print(lines, file = myfile) ...
How to write a list to a file with newlines in Python3
I'm trying to write an array (list?) to a text file using Python 3. Currently I have: def save_to_file(*text): with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile: for lines in text: print(lines, file = myfile) myfile.close This writes what looks like the array straig...
[ "myfile.close -- get rid of that where you use with. with automatically closes myfile, and you have to call close like close() anyway for it to do anything when you're not using with. You should just always use with on Python 3.\nwith open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile:\n myfile...
[ 84, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007138686_python_python_3.x.txt
Q: Text similarity algorithm, optimization concerns I have a django blog, and I am writing a simple similiar text algorithm for it. The code below is the code that I tested with a copy of my blog's database. (Note: code was originally in Turkish, I changed variable names to English for convenience. Therefore, things ...
Text similarity algorithm, optimization concerns
I have a django blog, and I am writing a simple similiar text algorithm for it. The code below is the code that I tested with a copy of my blog's database. (Note: code was originally in Turkish, I changed variable names to English for convenience. Therefore, things may look weird.) # -*- coding:utf-8 -*- from django.ut...
[ "If you want to do text similarity based searching, you are better off going with a search server like Sphinx: http://sphinxsearch.com/\n" ]
[ 0 ]
[]
[]
[ "database", "optimization", "python", "similarity" ]
stackoverflow_0007133350_database_optimization_python_similarity.txt
Q: How to cache query result in django? I am trying to cache query results on my django app. However, it seems that it is caching the whole app. I tried following logi: def cacheView(): result = cache.get('key') if result is None: result = Model.objects.get(id=1) cache.set('key', 'result') I am calling t...
How to cache query result in django?
I am trying to cache query results on my django app. However, it seems that it is caching the whole app. I tried following logi: def cacheView(): result = cache.get('key') if result is None: result = Model.objects.get(id=1) cache.set('key', 'result') I am calling this method when user logs in. However, if ...
[ "RTFM :) Official Django Docs: Caching and QuerySets\n\nEach QuerySet contains a cache, to minimize database access. (...)\n\nand:\n\nIn a newly created QuerySet, the cache is empty. The first time a QuerySet is evaluated -- and, hence, a database query happens -- Django saves the query results in the QuerySet's ca...
[ 11, 1 ]
[]
[]
[ "django", "memcached", "python" ]
stackoverflow_0003804984_django_memcached_python.txt
Q: Create constants for offsets into a list I have a list similar to this: host_info = ['stackoverflow.com', '213.213.214.213', 'comments', 'desriprion', 'age'] Sometimes, I need to remove one or more elements from the list and then return the list to the caller. To remove the comments item as an example I'd do this...
Create constants for offsets into a list
I have a list similar to this: host_info = ['stackoverflow.com', '213.213.214.213', 'comments', 'desriprion', 'age'] Sometimes, I need to remove one or more elements from the list and then return the list to the caller. To remove the comments item as an example I'd do this: host_info.pop(2) I'd prefer to use a consta...
[ "The easiest approach would be to change your list to a dictionary:\n keys_list = ['host',...]\n host_info = dict(zip(['stackoverflow.com', '213.213.214.213', 'comments', 'desriprion', 'age'], keys_list))\n\nNow you don't have to worry about the key list and if you remove an item from the host_info dictionary it wo...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007138859_python.txt
Q: Launching python subprocess has different behavior depending on launcher I'm attempting to launch Python 2.5 from Python 2.6. The reason for this is a compiled library I'm trying to use (GDAL) isn't supported for the version of Python distributed with another program (ArcGIS). Here's what I'm attempting to do. T...
Launching python subprocess has different behavior depending on launcher
I'm attempting to launch Python 2.5 from Python 2.6. The reason for this is a compiled library I'm trying to use (GDAL) isn't supported for the version of Python distributed with another program (ArcGIS). Here's what I'm attempting to do. The main.py file in Python 2.6: import subprocess p = subprocess.Popen(['C:\OSG...
[ "Regardless of whether PATH is correct, a simple test would be to change to a different arbitrary directory and do python.exe C:\\full\\path\\to\\main.py. If that reproduces the problem then you know it's some sort of path problem.\nCheck sys.path, I'll bet that's where the difference is. If that's the case, you ...
[ 1, 1 ]
[]
[]
[ "arcgis", "gdal", "python", "subprocess" ]
stackoverflow_0007115107_arcgis_gdal_python_subprocess.txt
Q: Can I use a python regex for letters, dashes and underscores? I want to handle geographic names i.e /new_york or /new-york etc and since new-york is django-slugify for New york then maybe I should use the slugifed names even if names with underscores look better since I may want to automate the URL creation via an...
Can I use a python regex for letters, dashes and underscores?
I want to handle geographic names i.e /new_york or /new-york etc and since new-york is django-slugify for New york then maybe I should use the slugifed names even if names with underscores look better since I may want to automate the URL creation via an algorithm such as django slugify. A guess is that ([A-Za-z]+) or s...
[ "the first match wins.\nusually your URLs will differ in other parts of the path. for example you might have\n/cities/(?P<city>[^/]+)\n/users/(?P<user>[^/]+)\n\nand in many cases [^/]+ is a good regex because it will match anything except /, which you would normally avoid because it is used to separate path elemen...
[ 3 ]
[]
[]
[ "django", "google_app_engine", "operator_precedence", "python", "regex" ]
stackoverflow_0007139000_django_google_app_engine_operator_precedence_python_regex.txt
Q: TypeError: 'str' does not support the buffer interface import hashlib infile = open("P:\\r.mp3", 'r+b') data = infile.readline() hash = hashlib.md5() hash.update(data) hash_digest = hash.hexdigest() print(hash_digest) #hash_digest = hash_digest.encode('utf-8') print(hash_digest) with open("lt.txt", 'ab') as outf...
TypeError: 'str' does not support the buffer interface
import hashlib infile = open("P:\\r.mp3", 'r+b') data = infile.readline() hash = hashlib.md5() hash.update(data) hash_digest = hash.hexdigest() print(hash_digest) #hash_digest = hash_digest.encode('utf-8') print(hash_digest) with open("lt.txt", 'ab') as outfile: outfile.write(hash_digest + '\n') #error here wi...
[ "You're using Python 3, where there is a strict division between text (str) and data (bytes). Text can't be written to a file if you don't explicitly encode it first.\nThere are two ways to do this:\n1) Open the file in text mode (possibly with an encoding specified) so that strings are automatically encoded for yo...
[ 23 ]
[ "You must search in Google for 'str' does not support the buffer interface\nYou'll have plenty of answers like this one:\nstackoverflow.com/questions/5471158/typeerror-str-does-not-support-the-buffer-interface\nAnd for the second error **TypeError: can't concat bytes to str\n** , I think you must write b'\\n' in f....
[ -5 ]
[ "file_io", "md5", "python" ]
stackoverflow_0007139225_file_io_md5_python.txt
Q: "No module named appengine.base" error after deploying Django app on Google App Engine I'm attempting to deploy a Django application to Google App Engine. The app deploys successfully, but throws the following error when I try to access it in a web browser: <class 'django.core.exceptions.ImproperlyConfigured'>: 'a...
"No module named appengine.base" error after deploying Django app on Google App Engine
I'm attempting to deploy a Django application to Google App Engine. The app deploys successfully, but throws the following error when I try to access it in a web browser: <class 'django.core.exceptions.ImproperlyConfigured'>: 'appengine' isn't an available database backend. Available options are: 'dummy', 'mysql', 'ora...
[ "Because you have appengine_django in your project root you are using App Engine Helper. You might have some import path problems so you can try upgrading to the latest version of the helper. However, it is a deprecated project and you are better off porting to django-nonrel if possible. Part of the migration will ...
[ 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0006105181_django_google_app_engine_python.txt
Q: Why doesn't this regexp match? I am using python, and this regexp doesn't match, and I don't understand why. string = "15++12" if re.match("[-+*/][-+*/]+",string): # raise an error here I am trying to raise an error, if one or more of "-","+","*","/" follows another one of those. A: Use re.search() as re....
Why doesn't this regexp match?
I am using python, and this regexp doesn't match, and I don't understand why. string = "15++12" if re.match("[-+*/][-+*/]+",string): # raise an error here I am trying to raise an error, if one or more of "-","+","*","/" follows another one of those.
[ "Use re.search() as re.match() only searches at the beginning of the string:\nstring = \"15++12\"\nif re.search(\"[-+*/][-+*/]+\",string):\n # raise an error here\n\nAlso, this could be simplified to:\nstring = \"15++12\"\nif re.search(\"[-+*/]{2,}\",string):\n # raise an error here\n\nas the {2,} operator se...
[ 6, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007138560_python_regex.txt
Q: Translating a C binary data read function to Python (I've edited this for clarity, and changed the actual question a bit based on EOL's answer) I'm trying to translate the following function in C to Python but failing miserably (see C code below). As I understand it, it takes four 1-byte chars starting from the me...
Translating a C binary data read function to Python
(I've edited this for clarity, and changed the actual question a bit based on EOL's answer) I'm trying to translate the following function in C to Python but failing miserably (see C code below). As I understand it, it takes four 1-byte chars starting from the memory location pointed to by from, treats them as unsigned...
[ "Ah, I think I've got it. Note that the description says\n/*\n The claim algorithm for Alan files is:\n * For Alan 3, check for the magic word\n * load the file length in blocks\n * check that the file length is correct\n * For alan 2, each word between byte address 24 and 81 is a\n word address with...
[ 1, 0, 0 ]
[]
[]
[ "binary_data", "c", "python" ]
stackoverflow_0007137613_binary_data_c_python.txt
Q: how to access a website with python through tor, successfully? ports 8118 and 9050 don't work? I'm trying to access a website with python through tor, but I'm having problems. I started my attempts with this thread and the one referenced in it: How to make urllib2 requests through Tor in Python? First I tried the ...
how to access a website with python through tor, successfully? ports 8118 and 9050 don't work?
I'm trying to access a website with python through tor, but I'm having problems. I started my attempts with this thread and the one referenced in it: How to make urllib2 requests through Tor in Python? First I tried the original code snippet: import urllib2 proxy_handler = urllib2.ProxyHandler({"tcp":"http://127.0.0.1:...
[ "TOR provides a SOCKS proxy. Since urllib2 can only handle HTTP proxies, you'll have to use a SOCKS implementation.\n" ]
[ 2 ]
[]
[]
[ "python", "tor", "urllib2" ]
stackoverflow_0007139764_python_tor_urllib2.txt