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: Basic Python While loop compound conditional evaluation In Python IDLE Shell it seems I cannot use a compound conditional expression and a while loop. I tried it within brackets too. Take these two examples: k=0 m=0 while k<10 & m<10: print k k +=1 m+=1 This doesn't evaluate the second condition. But ...
Basic Python While loop compound conditional evaluation
In Python IDLE Shell it seems I cannot use a compound conditional expression and a while loop. I tried it within brackets too. Take these two examples: k=0 m=0 while k<10 & m<10: print k k +=1 m+=1 This doesn't evaluate the second condition. But if I write while k<10: print k k+=1 This does work...
[ "& should be and. & is the bitwise AND operator.\n" ]
[ 7 ]
[]
[]
[ "conditional_operator", "python", "while_loop" ]
stackoverflow_0003006521_conditional_operator_python_while_loop.txt
Q: Python SUDS - problem with sending a message encoded not in UTF-8 I need to send a SOAP message (with Python SUDS) with strings encoded in 'iso-8859-2'. Does anybody know how to do it? SUDS raises the following exception when I invoke a method on a client with parameters encoded in 'iso-8859-2': File "/home/bartek...
Python SUDS - problem with sending a message encoded not in UTF-8
I need to send a SOAP message (with Python SUDS) with strings encoded in 'iso-8859-2'. Does anybody know how to do it? SUDS raises the following exception when I invoke a method on a client with parameters encoded in 'iso-8859-2': File "/home/bartek/myenv/lib/python2.5/site-packages/suds/sax/text.py", line 43, in __new...
[ "Text = Text.decode('iso-8859-2')\n\nmight be all you need, if Text starts out as an 8-bit string that was encoded with iso-8859-2. If it needs to be sent as a UTF-8 string or something, however, then you'd probably want to use\nText = Text.decode('utf-8')\n\nIf neither of those, then just play around with the deco...
[ 0 ]
[]
[]
[ "django", "python", "soap", "suds", "web_services" ]
stackoverflow_0003006669_django_python_soap_suds_web_services.txt
Q: problem with python script I want to run a csh file from a python script, example, #!/usr/bin/python import os os.system("source path/to/file.csh") and I want this file to run in the same shell as I am running the python script, because the file.csh script is settings some environment variables that I need. Does...
problem with python script
I want to run a csh file from a python script, example, #!/usr/bin/python import os os.system("source path/to/file.csh") and I want this file to run in the same shell as I am running the python script, because the file.csh script is settings some environment variables that I need. Does anyone know how to do this in P...
[ "A child process cannot affect the environment of the parent process. The best you can do is to run your csh script in a separate process, get the environment variables that it defines, then set each environment variable in your python script.\nEven with that, the python script won't be able to affect the shell in ...
[ 3, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0003006481_python_subprocess.txt
Q: mutliprocessing.Pool.add_sync() eating up memory I want to use multithreading to make my script faster... I'm still new to this. The Python doc assumes you already understand threading and what-not. So... I have code that looks like this from itertools import izip from multiprocessing import Pool p = Pool() for ...
mutliprocessing.Pool.add_sync() eating up memory
I want to use multithreading to make my script faster... I'm still new to this. The Python doc assumes you already understand threading and what-not. So... I have code that looks like this from itertools import izip from multiprocessing import Pool p = Pool() for i, j in izip(hugeseta, hugesetb): p.apply_async(nu...
[ "The del statement deletes object references, so can free up memory when the garbage collector runs.\nfrom itertools import izip\nfrom multiprocessing import Pool\n\np = Pool()\nfor i, j in izip(hugeseta, hugesetb):\n p.apply_async(number_crunching, (i, j))\n\ndel i, j\n\n", "Not really an answer but I used Po...
[ 0, 0 ]
[]
[]
[ "multiprocessing", "pool", "python" ]
stackoverflow_0003001389_multiprocessing_pool_python.txt
Q: how to speed up the code? in my program i have a method which requires about 4 files to be open each time it is called,as i require to take some data.all this data from the file i have been storing in list for manupalation. I approximatily need to call this method about 10,000 times.which is making my program very...
how to speed up the code?
in my program i have a method which requires about 4 files to be open each time it is called,as i require to take some data.all this data from the file i have been storing in list for manupalation. I approximatily need to call this method about 10,000 times.which is making my program very slow? any method for handling ...
[ "As a general strategy, it's best to keep this data in an in-memory cache if it's static, and relatively small. Then, the 10k calls will read an in-memory cache rather than a file. Much faster.\nIf you are modifying the data, the alternative might be a database like SQLite, or embedded MS SQL Server (and there are ...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0003006769_optimization_python.txt
Q: Error in Python's os.walk? The os.walk documentation (http://docs.python.org/library/os.html? highlight=os.walk#os.walk), says I can skip traversing unwanted directories by removing them from the dir list. The explicit example from the docs: import os from os.path import join, getsize for root, dirs, files in o...
Error in Python's os.walk?
The os.walk documentation (http://docs.python.org/library/os.html? highlight=os.walk#os.walk), says I can skip traversing unwanted directories by removing them from the dir list. The explicit example from the docs: import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): ...
[ "Because you're modifying the list dirs while iterating over it. ONE was just skipped and never gets looked at. Compare:\n>>> a = [1, 2, 3]\n>>> for i in a:\n if i > 1:\n a.remove(i)\n\n\n>>> a\n[1, 3]\n\n", "You aren't removing it from the dirs list. If you were, you'd see your \"Removing\" print out, ...
[ 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003006911_python.txt
Q: Python module for drawing functions graphics Which python module should I use for drawing simple functions graphics? E.g f: M -> M, f(x) = x A: Matplotlib: http://matplotlib.sourceforge.net/gallery.html A: Check out the third party Gnuplot-py package. I have used it before with success. If you are familiar wi...
Python module for drawing functions graphics
Which python module should I use for drawing simple functions graphics? E.g f: M -> M, f(x) = x
[ "Matplotlib: http://matplotlib.sourceforge.net/gallery.html\n", "Check out the third party Gnuplot-py package. I have used it before with success.\nIf you are familiar with gnuplot syntax, this should be relatively easy. If not, there are plenty of good gnuplot examples online.\nhttp://pypi.python.org/pypi/gnuplo...
[ 5, 0 ]
[]
[]
[ "graphics", "python" ]
stackoverflow_0003006965_graphics_python.txt
Q: load a pickle file from a zipfile For some reason I cannot get cPickle.load to work on the file-type object returned by ZipFile.open(). If I call read() on the file-type object returned by ZipFile.open() I can use cPickle.loads though. Example .... import zipfile import cPickle # the data we want to store some_da...
load a pickle file from a zipfile
For some reason I cannot get cPickle.load to work on the file-type object returned by ZipFile.open(). If I call read() on the file-type object returned by ZipFile.open() I can use cPickle.loads though. Example .... import zipfile import cPickle # the data we want to store some_data = {1: 'one', 2: 'two', 3: 'three'} ...
[ "It's due to an imperfection in the pseudofile object implemented by the zipfile module (for the .open method of the ZipFile class introduced in Python 2.6). Consider:\n>>> f = zf.open('data.pkl')\n>>> f.read(1)\n'('\n>>> f.readline()\n'dp1\\n'\n>>> f.read(1)\n''\n>>> \n\nthe sequence of .read(1) -- .readline() is...
[ 8 ]
[]
[]
[ "pickle", "python", "python_zipfile" ]
stackoverflow_0003006727_pickle_python_python_zipfile.txt
Q: Django facebook integration error I'm trying to integrate facebook into my application so that users can use their FB login to login to my site. I've got everything up and running and there are no issues when I run my site using the command line python manage.py runserver But this same code refuses to run when I ...
Django facebook integration error
I'm trying to integrate facebook into my application so that users can use their FB login to login to my site. I've got everything up and running and there are no issues when I run my site using the command line python manage.py runserver But this same code refuses to run when I try and run it through Apache. I get th...
[ "It looks as though you are referencing app.models, which tends to work fine in development but fails in production. Change it to foodfolio.app.models, and it should be fine. This seems to be somewhere in your custom template tags.\n" ]
[ 0 ]
[]
[]
[ "django", "facebook", "python" ]
stackoverflow_0003004802_django_facebook_python.txt
Q: python `IN` module problem (FreeBSD) I'm trying to work with sockets and I have such problem In code example: setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,self.listen_address+'\0') I have error AttributeError: 'module' object has no attribute 'SO_BINDTODEVICE' On Linux machine this attribute is OK but on Fre...
python `IN` module problem (FreeBSD)
I'm trying to work with sockets and I have such problem In code example: setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,self.listen_address+'\0') I have error AttributeError: 'module' object has no attribute 'SO_BINDTODEVICE' On Linux machine this attribute is OK but on FreeBSD trere are no any SO_* attributes in m...
[ "SO_BINDTODEVICE socket option is not standard and is not supported on FreeBSD. Why can't you just use regular bind(2) for assigning local address/interface?\nEdit:\nTake a look at the socket object docs.\nHere's an example.\nEdit 2:\nYou didn't say what exactly you are trying to achieve, so assuming regular TCP/IP...
[ 1 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0003007084_python_sockets.txt
Q: Django: Page doesn't load images I am working on a Django project for a company. This project worked very well before today. Today I found a page can not show images (and their corrsponding links). I checked source code of THAT PAGE, I found there are images and links, I just can not find them on the page. I chec...
Django: Page doesn't load images
I am working on a Django project for a company. This project worked very well before today. Today I found a page can not show images (and their corrsponding links). I checked source code of THAT PAGE, I found there are images and links, I just can not find them on the page. I checked the auth of the server and I am su...
[ "Try exploring the site_media directory. If you're images are being served up as static content it could be related to the permissions of that folder on local disk or based on the settings.\nWithin your urls you may have something similar to:\n(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',\n {'docum...
[ 0 ]
[]
[]
[ "django", "python", "web" ]
stackoverflow_0002995648_django_python_web.txt
Q: In Python, how do I remove the "root" tag in an HTML snippet? Suppose I have an HTML snippet like this: <div> Hello <strong>There</strong> <div>I think <em>I am</em> feeing better!</div> <div>Don't you?</div> Yup! </div> What's the best/most robust way to remove the surrounding root element, so it looks ...
In Python, how do I remove the "root" tag in an HTML snippet?
Suppose I have an HTML snippet like this: <div> Hello <strong>There</strong> <div>I think <em>I am</em> feeing better!</div> <div>Don't you?</div> Yup! </div> What's the best/most robust way to remove the surrounding root element, so it looks like this: Hello <strong>There</strong> <div>I think <em>I am</em> ...
[ "This is a bit odd in lxml (or ElementTree). You'd have to do:\ndef inner_html(el):\n return (el.text or '') + ''.join(tostring(child) for child in el)\n\nNote that lxml (and ElementTree) have no special way to represent a document except rooted with a single element, but .drop_tag() would work like you want if...
[ 6, 1, 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003003049_html_python.txt
Q: Using localtime in a where clause for GqlQuery I'm trying to understand how I can use the local server time to quickly filter results on google appengine. It seems to me that there should be a simple way of doing this using DATETIME(time.localtime()). For example (where 'timestamp' is of type db.DateTimeProperty)....
Using localtime in a where clause for GqlQuery
I'm trying to understand how I can use the local server time to quickly filter results on google appengine. It seems to me that there should be a simple way of doing this using DATETIME(time.localtime()). For example (where 'timestamp' is of type db.DateTimeProperty)... q = db.GqlQuery("SELECT * FROM LiveData WHERE tim...
[ "You do not have to create strings when querying DateTimeProperty types. Try this:\nimport datetime\nq = db.GqlQuery(\"SELECT * FROM LiveData WHERE timestamp > :1\", datetime.datetime.now())\n\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "gqlquery", "python" ]
stackoverflow_0003007512_google_app_engine_gqlquery_python.txt
Q: Are there any tools for schema migration for NoSQL databases? I'm looking a way to automate schema migration for such databases like MongoDB or CouchDB. Preferably, this instument should be written in python, but any other language is ok. A: Since a nosql database can contain huge amounts of data you can not mig...
Are there any tools for schema migration for NoSQL databases?
I'm looking a way to automate schema migration for such databases like MongoDB or CouchDB. Preferably, this instument should be written in python, but any other language is ok.
[ "Since a nosql database can contain huge amounts of data you can not migrate it in the regular rdbms sence. Actually you can't do it for rdbms as well as soon as your data passes some size threshold. It is impractical to bring your site down for a day to add a field to an existing table, and so with rdbms you end u...
[ 19, 2, 2, 1 ]
[]
[]
[ "couchdb", "database", "mongodb", "nosql", "python" ]
stackoverflow_0001961013_couchdb_database_mongodb_nosql_python.txt
Q: Is there a way to programatically access a bazaar repository? I would like to access a bazaar repository and pull code from it with either a Python or PHP script. How is this done? Is there a Python module / PEAR library that makes this easy? If it helps, the repository is on Launchpad. Edit: As mentioned below, r...
Is there a way to programatically access a bazaar repository?
I would like to access a bazaar repository and pull code from it with either a Python or PHP script. How is this done? Is there a Python module / PEAR library that makes this easy? If it helps, the repository is on Launchpad. Edit: As mentioned below, running the bazaar commands directly is not an option. Also, an exam...
[ "There is bzrlib. Depending on your circumstance you could also just execute the command lines to do this.\nBased on the Integrating with BZR page you might do something like the following to checkout code. You can also Export code which might be more appropriate:\nfrom bzrlib.bzrdir BzrDir\n\naccelerator_tree, sou...
[ 4 ]
[]
[]
[ "bazaar", "php", "python" ]
stackoverflow_0003008054_bazaar_php_python.txt
Q: Python logging is outputting with the time 4 hours ahead of system My system is set to EDT in Linux, and I can confirm this in Python with datetime.now(). However the logger is outputting 4 hours ahead. What could be the cause of this? EDIT: Logging config looks like this: logging.basicConfig(level=logging.DEBUG) ...
Python logging is outputting with the time 4 hours ahead of system
My system is set to EDT in Linux, and I can confirm this in Python with datetime.now(). However the logger is outputting 4 hours ahead. What could be the cause of this? EDIT: Logging config looks like this: logging.basicConfig(level=logging.DEBUG) lf = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(messa...
[ "Your logger is using UTC time. If you show us your code it would be possible to say exactly why.\n", "I think it is significant that 4 hours ahead is GMT for you. Poking around logging's code - it seems that it uses time rather than datetime. Apparently they work differently in figuring out the localtime.\nWhat ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003005530_python.txt
Q: I need powerful interactive packet manipulation program like scapy I need powerful interactive packet manipulation program like Scapy for Ruby A: Did you try Scruby ? http://www.rubyinside.com/scruby-a-ruby-shell-for-packet-sending-and-sniffing-460.html A: http://github.com/ahobson/ruby-pcap here's one. Don't...
I need powerful interactive packet manipulation program like scapy
I need powerful interactive packet manipulation program like Scapy for Ruby
[ "Did you try Scruby ? http://www.rubyinside.com/scruby-a-ruby-shell-for-packet-sending-and-sniffing-460.html\n", "http://github.com/ahobson/ruby-pcap\nhere's one. Don't know how powerful it when compared to Scapy, but it was enough for my needs.\n" ]
[ 0, 0 ]
[]
[]
[ "packet", "python", "ruby", "scapy" ]
stackoverflow_0003008246_packet_python_ruby_scapy.txt
Q: In Python, how do I search a flat file for the closest match to a particular numeric value? have file data of format 3.343445 1 3.54564 1 4.345535 1 2.453454 1 and so on upto 1000 lines and i have number given such as a=2.44443 for the given file i need to find the row number of the numbers in file which i...
In Python, how do I search a flat file for the closest match to a particular numeric value?
have file data of format 3.343445 1 3.54564 1 4.345535 1 2.453454 1 and so on upto 1000 lines and i have number given such as a=2.44443 for the given file i need to find the row number of the numbers in file which is most close to the given number "a" how can i do this i am presently doing by loading whole file...
[ ">>> gen = (float(line.partition(' ')[0]) for line in open(fname))\n>>> min(enumerate(gen), key=lambda x: abs(x[1] - a))\n(3, 2.453454)\n\n", "If the file isn't sorted, no, there is no faster method.\nActually, let me rephrase: the fastest algorithm is to go through the file line by line and compare the first num...
[ 8, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003008212_python.txt
Q: Python Library installation I have two questions regarding python libraries: I would like to know if there is something like a "super" python library which lets me install ALL or at least all scientific useful python libraries, which I can install once and then I have all I need. There is a number of annoying pro...
Python Library installation
I have two questions regarding python libraries: I would like to know if there is something like a "super" python library which lets me install ALL or at least all scientific useful python libraries, which I can install once and then I have all I need. There is a number of annoying problems when installing different l...
[ "In Windows enviroments, pythonXY is what your are looking for.\n", "Enthought Python Distribution\n", "Several options are listed at http://new.scipy.org/download.html#software-distributions-that-include-numpy-scipy\n" ]
[ 5, 4, 3 ]
[]
[]
[ "matplotlib", "numpy", "python", "python_imaging_library" ]
stackoverflow_0003006844_matplotlib_numpy_python_python_imaging_library.txt
Q: Matplotlib autodatelocator custom date formatting? I'm using Matplotlib to dynamically generate .png charts from a database. The user may set as the x-axis any given range of datetimes, and I need to account for all of it. While Matplotlib has the dates.AutoDateLocator(), I want the datetime format printed on the ...
Matplotlib autodatelocator custom date formatting?
I'm using Matplotlib to dynamically generate .png charts from a database. The user may set as the x-axis any given range of datetimes, and I need to account for all of it. While Matplotlib has the dates.AutoDateLocator(), I want the datetime format printed on the chart to be context-specific - e.g. if the user is chart...
[ "Does AutoDateFormatter do what you want? Even if it doesn't, you may want to take a look at its source code for a somewhat more compact way of implementing the choice of format string.\nIn the released version, you cannot customize the per-level formats, but in the development code you can. You could probably just...
[ 2 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003002155_matplotlib_python.txt
Q: How to write a copyright message using matplotlib I am creating some graphs using matplotlib, and I want to be able to write a copyright message and my website address at the bottom of the image. Something like: © ACME Corp www.example.com Does anyone know how I may do this? A: To write text in the figure outs...
How to write a copyright message using matplotlib
I am creating some graphs using matplotlib, and I want to be able to write a copyright message and my website address at the bottom of the image. Something like: © ACME Corp www.example.com Does anyone know how I may do this?
[ "To write text in the figure outside the axis area, use figtext. \n", "Not sure if this answer your question but you can put any text in a figure with\n text(x, y, s, fontdict=None, **kwargs)\n\nsome examples of fonts are in here\n" ]
[ 3, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0002964009_matplotlib_python.txt
Q: Manipulating Directory Paths in Python Basically I've got this current url and this other key that I want to merge into a new url, but there are three different cases. Suppose the current url is localhost:32401/A/B/foo if key is bar then I want to return localhost:32401/A/B/bar if key starts with a slash and is /A...
Manipulating Directory Paths in Python
Basically I've got this current url and this other key that I want to merge into a new url, but there are three different cases. Suppose the current url is localhost:32401/A/B/foo if key is bar then I want to return localhost:32401/A/B/bar if key starts with a slash and is /A/bar then I want to return localhost:32401/A...
[ "Have you checked out the urlparse module?\nFrom the docs,\nfrom urlparse import urljoin\nurljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')\n\nShould help with your first case.\nObviously, you can always do basic string manipulation for the rest.\n", "String objects in Python all have startswith and e...
[ 1, 0, 0 ]
[]
[]
[ "absolute_path", "directory", "python", "relative_path" ]
stackoverflow_0003008756_absolute_path_directory_python_relative_path.txt
Q: How to hide Windows console with python Tkinter? I tried renaming my .py file to .pyw. But compiling with py2exe does not make a difference. I tried using root.withdraw() but all it does is freeze the application, prevent the initial canvas from popping up, and fail to remove the command prompt window anyways. Doe...
How to hide Windows console with python Tkinter?
I tried renaming my .py file to .pyw. But compiling with py2exe does not make a difference. I tried using root.withdraw() but all it does is freeze the application, prevent the initial canvas from popping up, and fail to remove the command prompt window anyways. Does anyone have a solution? My root is: root = Tk()
[ "I ended up finding the solution on http://ubuntuforums.org/showthread.php?t=728170\nIn short, the solution is to change the line setup(console=[\"yourapp.py\"]) to setup(windows=[\"yourapp.py\"]), otherwise, it is the same code as the rest of the py2exe tutorial.\n" ]
[ 5 ]
[]
[]
[ "console", "hide", "python", "tkinter", "windows" ]
stackoverflow_0003008731_console_hide_python_tkinter_windows.txt
Q: how to speed up code? i want to speed my code compilation..I have searched the internet and heard that psyco is a very tool to improve the speed.i have searched but could get a site for download. i have installed any additional libraries or modules till date in my python.. can psyco user,tell where we can download...
how to speed up code?
i want to speed my code compilation..I have searched the internet and heard that psyco is a very tool to improve the speed.i have searched but could get a site for download. i have installed any additional libraries or modules till date in my python.. can psyco user,tell where we can download the psyco and its installa...
[ "I suggest to not rely on this tools, anyway psycho is being replaced by the new python implementations as PyPy and unladen swallow. To speed up \"for free\" you can use Cython and Shedskin. Anyway this is not the right way to speedup the code in my opinion.\nIf you are looking for speed here are some hints:\n\nPro...
[ 11, 3, 2, 2 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0003007678_optimization_python.txt
Q: downloading full page text from a web domain First time here -- thought I'd field a question on behalf of a coworker. Somebody in my lab is doing a content analysis (e.g. reading an article or transcript line by line and identifying relevant themes) of the web presences of various privatized neuroimaging centers (...
downloading full page text from a web domain
First time here -- thought I'd field a question on behalf of a coworker. Somebody in my lab is doing a content analysis (e.g. reading an article or transcript line by line and identifying relevant themes) of the web presences of various privatized neuroimaging centers (e.g. http://www.canmagnetic.com/). She's been c/pi...
[ "Here is pretty much everything you need to get started. Read the section \"Listing 7. Simple Python Web site crawler\". The examples are even written in python.\nhttp://www.ibm.com/developerworks/linux/library/l-spider/\nGood luck!\n", "A popular web scraping module for Python is Scrapy. Go ahead and take a look...
[ 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003009253_python.txt
Q: More elegant way to initialize list of duplicated items in Python If I want a list initialized to 5 zeroes, that's very nice and easy: [0] * 5 However if I change my code to put a more complicated data structure, like a list of zeroes: [[0]] * 5 will not work as intended, since it'll be 10 copies of the same lis...
More elegant way to initialize list of duplicated items in Python
If I want a list initialized to 5 zeroes, that's very nice and easy: [0] * 5 However if I change my code to put a more complicated data structure, like a list of zeroes: [[0]] * 5 will not work as intended, since it'll be 10 copies of the same list. I have to do: [[0] for i in xrange(5)] that feels bulky and uses a ...
[ "After thinking a bit about it, I came up with this solution: (7 lines without import)\n# helper\ndef cl(n, func):\n # return a lambda, that returns a list, where func(tion) is called\n return (lambda: [func() for _ in range(n)])\n\ndef matrix(base, *ns):\n # the grid lambda (at the start it returns the ba...
[ 9, 5, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003009091_python.txt
Q: Use Python to search one .txt file for a list of words or phrases (and show the context) Basically as the question states. I am fairly new to Python and like to learn by seeing and doing. I would like to create a script that searches through a text document (say the text copied and pasted from a news article for ...
Use Python to search one .txt file for a list of words or phrases (and show the context)
Basically as the question states. I am fairly new to Python and like to learn by seeing and doing. I would like to create a script that searches through a text document (say the text copied and pasted from a news article for example) for certain words or phrases. Ideally, the list of words and phrases would be stored ...
[ "Despite the frequently expressed antipathy for Regular Expressions on the part of many in the Python community, they're really a precious tool for the appropriate use cases -- which definitely include identifying words and phrases (thanks to the \\b \"word boundary\" element in regular expression patterns -- strin...
[ 7, 3 ]
[]
[]
[ "python", "search", "text" ]
stackoverflow_0003007889_python_search_text.txt
Q: Compute the total RAM used by Python dict or list My problem: I am writing a simple Python tool to help me visualize my data as a function of many parameters. Each change in parameters involves a non-trivial amount of time, so I would like to cache each step's resulting imagery and supporting data in a dictionary...
Compute the total RAM used by Python dict or list
My problem: I am writing a simple Python tool to help me visualize my data as a function of many parameters. Each change in parameters involves a non-trivial amount of time, so I would like to cache each step's resulting imagery and supporting data in a dictionary. But then I worry that this dictionary could grow too ...
[ "Use a memory profiler such as PySizer or Heapy.\n" ]
[ 3 ]
[]
[]
[ "dictionary", "memory", "python" ]
stackoverflow_0003009686_dictionary_memory_python.txt
Q: Boost.Python tutorial in Ubuntu 10.04 I downloaded the latest version of Boost and I'm trying to get the Boost.python tutorial up and running on Ubuntu 10.04: http://www.boost.org/doc/libs/1_43_0/libs/python/doc/tutorial/doc/html/python/hello.html I navigated to the correct directory, ran "bjam" and it compiled us...
Boost.Python tutorial in Ubuntu 10.04
I downloaded the latest version of Boost and I'm trying to get the Boost.python tutorial up and running on Ubuntu 10.04: http://www.boost.org/doc/libs/1_43_0/libs/python/doc/tutorial/doc/html/python/hello.html I navigated to the correct directory, ran "bjam" and it compiled using default settings. I did not yet create ...
[ "How did you install boost ?\nAssuming you have use the following: http://www.boost.org/doc/libs/1_43_0/more/getting_started/unix-variants.html#easy-build-and-install\nliboost_python shard library will be install in /usr/local/lib\nTo run the hello.py example, try the following:\nLD_LIBRARY_PATH=/usr/local/lib pyth...
[ 5, 2, 0 ]
[]
[]
[ "boost_python", "c++", "python" ]
stackoverflow_0003009533_boost_python_c++_python.txt
Q: PyGTK: how to make a clipboard monitor? How can I make a simple clipboard monitor in Python using the PyGTK GUI? I found gtk.clipboard class and but I couldn't find any solution to get the "signals" to trigger the event when the clipboard content has changed. Any ideas? A: Without a proper notification API, such...
PyGTK: how to make a clipboard monitor?
How can I make a simple clipboard monitor in Python using the PyGTK GUI? I found gtk.clipboard class and but I couldn't find any solution to get the "signals" to trigger the event when the clipboard content has changed. Any ideas?
[ "Without a proper notification API, such as WM_DrawClipboard messages, you would probably have to resort to a polling loop. And then you will cause major conflicts with other apps that are trying to use this shared resource.\nDo not resort to a polling loop. \n" ]
[ 4 ]
[]
[]
[ "clipboard", "monitor", "pygtk", "python" ]
stackoverflow_0003005522_clipboard_monitor_pygtk_python.txt
Q: Django dictionary in templates: Grab key from another objects attribute I have a dictionary called number_devices I'm passing to a template, the dictionary keys are the ids of a list of objects I'm also passing to the template (called implementations). I'm iterating over the list of objects and then trying to use...
Django dictionary in templates: Grab key from another objects attribute
I have a dictionary called number_devices I'm passing to a template, the dictionary keys are the ids of a list of objects I'm also passing to the template (called implementations). I'm iterating over the list of objects and then trying to use the object.id to get a value out of the dict like so: {% for implementat...
[ "A workaround could be using the keys from number_devices and check in the for loop if it is equal to the key provided by number_devices.\n{% for key in number_devices.keys %}\n {% for implementation in implementations %}\n {% ifequal key implementation.id %} you got it {% endifequal %}\n {% endfor %}\...
[ 1 ]
[]
[]
[ "dictionary", "django", "python", "templates" ]
stackoverflow_0003009760_dictionary_django_python_templates.txt
Q: Parameters with braces in python If you look at the following line of python code: bpy.ops.object.particle_system_add({"object":bpy.data.objects[2]}) you see that in the parameters there is something enclosed in braces. Can anyone tell me what the braces are for (generically anyway)? I haven't really seen this ...
Parameters with braces in python
If you look at the following line of python code: bpy.ops.object.particle_system_add({"object":bpy.data.objects[2]}) you see that in the parameters there is something enclosed in braces. Can anyone tell me what the braces are for (generically anyway)? I haven't really seen this type of syntax in python and I can't f...
[ "From the docs:\n\nDictionaries can be created by placing a comma-separated list of key: value pairs within braces, for example: {'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}, or by the dict constructor.\n\n", "The braces create a dictionary. particle_system_add seems to be accepting a diction...
[ 6, 2, 2, 1 ]
[]
[]
[ "curly_braces", "parameters", "python", "python_3.x" ]
stackoverflow_0003010225_curly_braces_parameters_python_python_3.x.txt
Q: ldapsearch and vcard creation I'm using openldap on Mac OS X Server 10.6 and need to generate a vcard for all the users in a given group. By using the ldapsearch I can list all the memberUid's for all users in that group. I found a perl script (Advanced LDAP Search or ALS) that was written by someone that will gen...
ldapsearch and vcard creation
I'm using openldap on Mac OS X Server 10.6 and need to generate a vcard for all the users in a given group. By using the ldapsearch I can list all the memberUid's for all users in that group. I found a perl script (Advanced LDAP Search or ALS) that was written by someone that will generate the vcard easily. ALS can be ...
[ "My language of choice would be Perl - but only because I've done similar operations using Perl and LDAP.\nIf I remember correctly, that ldapsearch command will give you the full LDIF entry for each uid in the testgroup cn. If that's the case, then you'll need to clean it up a bit before it's ready for the als par...
[ 1 ]
[]
[]
[ "ldap", "perl", "python" ]
stackoverflow_0003007739_ldap_perl_python.txt
Q: Selecting dictionary items by key efficiently in Python suppose I have a dictionary whose keys are strings. How can I efficiently make a new dictionary from that which contains only the keys present in some list? for example: # a dictionary mapping strings to stuff mydict = {'quux': ..., 'bar': ..., ...
Selecting dictionary items by key efficiently in Python
suppose I have a dictionary whose keys are strings. How can I efficiently make a new dictionary from that which contains only the keys present in some list? for example: # a dictionary mapping strings to stuff mydict = {'quux': ..., 'bar': ..., 'foo': ...} # list of keys to be selected from mydict ...
[ "dict((k, mydict[k]) for k in keys_to_select)\n\nif you know all the keys to select are also keys in mydict; if that's not the case,\ndict((k, mydict[k]) for k in keys_to_select if k in mydict)\n\n" ]
[ 15 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0003010326_numpy_python_scipy.txt
Q: In Django, how do I filter where language column = "null"? MyTable.objects.filter(where language column = null) How can that be done? Thanks. A: MyTable.objects.filter(language__isnull=True) Link to documentation.
In Django, how do I filter where language column = "null"?
MyTable.objects.filter(where language column = null) How can that be done? Thanks.
[ "MyTable.objects.filter(language__isnull=True)\n\nLink to documentation.\n" ]
[ 3 ]
[]
[]
[ "database", "django", "mysql", "python" ]
stackoverflow_0003010492_database_django_mysql_python.txt
Q: Efficient way to store tuples in the datastore If I have a pair of floats, is it any more efficient (computationally or storage-wise) to store them as a GeoPtProperty than it would be pickle the tuple and store it as a BlobProperty? If GeoPt is doing something more clever to keep multiple values in a single proper...
Efficient way to store tuples in the datastore
If I have a pair of floats, is it any more efficient (computationally or storage-wise) to store them as a GeoPtProperty than it would be pickle the tuple and store it as a BlobProperty? If GeoPt is doing something more clever to keep multiple values in a single property, can it be leveraged for arbitrary data? Can I st...
[ "Here are some empirical answers:\nGeoPtProperty uses 31B of storage space.\nUsing BlobProperty varies based on what exactly you store:\n\nstruct.pack('>2f', lat, lon) => 21B.\nUsing pickle (v2) to packe a 2-tuple containing floats => 37B.\nUsing pickle (v0) to packe a 2-tuple containing floats => about 30B-32B (v0...
[ 3, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003010375_google_app_engine_google_cloud_datastore_python.txt
Q: Can you dynamically combine multiple conditional functions into one in Python? I'm curious if it's possible to take several conditional functions and create one function that checks them all (e.g. the way a generator takes a procedure for iterating through a series and creates an iterator). The basic usage case ...
Can you dynamically combine multiple conditional functions into one in Python?
I'm curious if it's possible to take several conditional functions and create one function that checks them all (e.g. the way a generator takes a procedure for iterating through a series and creates an iterator). The basic usage case would be when you have a large number of conditional parameters (e.g. "max_a", "min_...
[ "Based on your example, if your list of possible parameters is just a sequence of max,min,max,min,max,min,... then here's an easy way to do it:\ndef combining_function(*args):\n maxs, mins = zip(*zip(*[iter(args)]*2))\n minv = max(m for m in mins if m is not None)\n maxv = min(m for m in maxs if m is not N...
[ 1, 1, 1 ]
[]
[]
[ "functional_programming", "python" ]
stackoverflow_0003010381_functional_programming_python.txt
Q: Prepopulate drop-box according to another drop-box choice in Django Admin I have models like this: class User(models.Model): Switch = models.ForeignKey(Switch, related_name='SwitchUsers') Port = models.ForeignKey(Port) class Switch(models.Model): Name = models.CharField(max_length=50) class Port(m...
Prepopulate drop-box according to another drop-box choice in Django Admin
I have models like this: class User(models.Model): Switch = models.ForeignKey(Switch, related_name='SwitchUsers') Port = models.ForeignKey(Port) class Switch(models.Model): Name = models.CharField(max_length=50) class Port(models.Model): PortNum = models.PositiveIntegerField() Switch = models...
[ "You are correct that you will need some js to create this. You don't need to re-write the django admin interface. You only need to customize it. This type of a thing requires a few things.\nStart here: http://docs.djangoproject.com/en/1.2/ref/contrib/admin/#modeladmin-objects\nTo include your javascript use the ...
[ 1, 0, 0 ]
[]
[]
[ "django", "jquery", "python" ]
stackoverflow_0003000664_django_jquery_python.txt
Q: Python: mysqldb install error So i've been pulling my hair out trying to install the mysqldb package. When i run the build i get a long transcript of errors, heres just part of it, i would posit it all but its huge list of errors [rv@med240-183 MySQL-python-1.2.3c1]$ sudo python setup.py build [sudo] password for ...
Python: mysqldb install error
So i've been pulling my hair out trying to install the mysqldb package. When i run the build i get a long transcript of errors, heres just part of it, i would posit it all but its huge list of errors [rv@med240-183 MySQL-python-1.2.3c1]$ sudo python setup.py build [sudo] password for rv: running build running build_py ...
[ "yum install mysql-devel\n\n" ]
[ 3 ]
[]
[]
[ "database", "installation", "mysql", "python" ]
stackoverflow_0003010752_database_installation_mysql_python.txt
Q: Python - wxPython custom button -> unbound method __init__()? what? After looking at questions like this it doesn't make sense that my __init__(self, parrent, id) would be throwing a unbound error? help? main.py import wx from customButton import customButton from wxPython.wx import * class MyFrame(wx.Frame): ...
Python - wxPython custom button -> unbound method __init__()? what?
After looking at questions like this it doesn't make sense that my __init__(self, parrent, id) would be throwing a unbound error? help? main.py import wx from customButton import customButton from wxPython.wx import * class MyFrame(wx.Frame): def __init__(self, parent, ID, title): wxFrame.__init__(self, pa...
[ "You don't create an object like this:\nself.Button1 = customButton.__init__(self, parent, -1)\n\nyou do it like this:\nself.Button1 = customButton(parent, -1)\n\n__init__ is an implicitly invoked method during object creation.\n", "Don't call __init__() explicitly unless you know you need to.\nself.Button1 = cus...
[ 3, 1 ]
[]
[]
[ "custom_controls", "pydev", "python", "wxpython" ]
stackoverflow_0003010789_custom_controls_pydev_python_wxpython.txt
Q: Connect to an existing process Hole thing is happening on the mac os x. Let's assume that I've opened an program by clicking on an .app icon. It's a python program with GUI which has a separate process that waits for a user input. But as I've opened it by clickin .app icon I dont have access to it's input as I wou...
Connect to an existing process
Hole thing is happening on the mac os x. Let's assume that I've opened an program by clicking on an .app icon. It's a python program with GUI which has a separate process that waits for a user input. But as I've opened it by clickin .app icon I dont have access to it's input as I would have if I opened it in Terminal. ...
[ "If you need to have a Terminal window connected to your \"separate process\", I would use the Terminal to launch that process in your python script. I can do that with some applescript code. Here's a simple applescript example. I can open a Terminal window and run the \"cd\" command like this:\ntell application \"...
[ 0 ]
[]
[]
[ "macos", "pipe", "process", "python", "terminal" ]
stackoverflow_0003004791_macos_pipe_process_python_terminal.txt
Q: How do I do import hooks in IronPython/Silverlight? I'm extending TryPython to (along with various other things) allow users to save a file and subsequently import that file. TryPython overloads the built in file operations, so I need to know what parts of import need to hooked into in order for import to use the ...
How do I do import hooks in IronPython/Silverlight?
I'm extending TryPython to (along with various other things) allow users to save a file and subsequently import that file. TryPython overloads the built in file operations, so I need to know what parts of import need to hooked into in order for import to use the overloaded file operations. Really, a basic overview of ...
[ "IronPython's import basically works as usual but the file system is abstracted away in Silverlight. This is done by the DLR hosting API's PlatformAdaptionLayer. The end result is that all requests for files to be imported go to the XAP file rather than going to the file system.\nI would suggest using one of the ...
[ 2 ]
[]
[]
[ "ironpython", "python", "silverlight" ]
stackoverflow_0003011031_ironpython_python_silverlight.txt
Q: viewing files in python? I am creating a sort of "Command line" in Python. I already added a few functions, such as changing login/password, executing, etc., But is it possible to browse files in the directory that the main file is in with a command/module, or will I have to make the module myself and use the impo...
viewing files in python?
I am creating a sort of "Command line" in Python. I already added a few functions, such as changing login/password, executing, etc., But is it possible to browse files in the directory that the main file is in with a command/module, or will I have to make the module myself and use the import command? Same thing with ch...
[ "Browsing files is as easy as using the standard os module. If you want to do something with those files, that's entirely different.\nimport os\nall_files = os.listdir('.') # gets all files in current directory\n\nTo change directories you can issue os.chdir('path/to/change/to'). In fact there are plenty of usefu...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003010864_python.txt
Q: New wxpython controls not displaying until resize I have created a custom control (based on a panel) in wxPython that provides a list of custom controls on panel within it. The user needs to be able to add rows at will and have those rows displayed. I'm having trouble getting the new controls to actually appear af...
New wxpython controls not displaying until resize
I have created a custom control (based on a panel) in wxPython that provides a list of custom controls on panel within it. The user needs to be able to add rows at will and have those rows displayed. I'm having trouble getting the new controls to actually appear after they are added. I know they are present, because th...
[ "Try self.Layout()\nTry self.GetParent().Layout()\nIncluding a Refresh().\nUpdate() shouldn't be necessary.\n" ]
[ 3 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0003011231_python_user_interface_wxpython.txt
Q: Why is my simple python gtk+cairo program running so slowly/stutteringly? My program draws circles moving on the window. I think I must be missing some basic gtk/cairo concept because it seems to be running too slowly/stutteringly for what I am doing. Any ideas? Thanks for any help! #!/usr/bin/python import gtk ...
Why is my simple python gtk+cairo program running so slowly/stutteringly?
My program draws circles moving on the window. I think I must be missing some basic gtk/cairo concept because it seems to be running too slowly/stutteringly for what I am doing. Any ideas? Thanks for any help! #!/usr/bin/python import gtk import gtk.gdk as gdk import math import random import gobject # The number of...
[ "One of the problems is that you are drawing the same basic object again and again. I'm not sure about GTK+ buffering behavior, but also keep in mind that basic function calls incur a cost in Python. I've added a frame counter to your program, and I with your code, I got around 30fps max.\nThere are several things ...
[ 12, 2, 0 ]
[]
[]
[ "animation", "cairo", "gtk", "pygtk", "python" ]
stackoverflow_0002172525_animation_cairo_gtk_pygtk_python.txt
Q: Global name not defined I wrote a CPU monitoring program in Python. For some reason sometimes the the program will run without any problem. Then other times the program won't even start because of the following error. Traceback (most recent call last): File "", line 244, in run_nodebug File "C:\Python26\CPUR1....
Global name not defined
I wrote a CPU monitoring program in Python. For some reason sometimes the the program will run without any problem. Then other times the program won't even start because of the following error. Traceback (most recent call last): File "", line 244, in run_nodebug File "C:\Python26\CPUR1.7.pyw", line 601, in app...
[ "Edit:\nIf that if self.selectedM.get() =='Options...': statement in E() isn't satisfied, then the global variable TL is never declared which I'm quite sure is what is happening. Then, when F() tries to use TL, it doesn't exist.\n" ]
[ 2 ]
[]
[]
[ "global_variables", "python", "tkinter" ]
stackoverflow_0003011573_global_variables_python_tkinter.txt
Q: IDLE wont start Python 2.6.5 I was using it as my primary text editor for quite sometime. However, one day it just stopped working. This had happened to me several times before, so I simply tried to end all procceses using windows task manager. However that didn't work. I've recently tried getting it to work again...
IDLE wont start Python 2.6.5
I was using it as my primary text editor for quite sometime. However, one day it just stopped working. This had happened to me several times before, so I simply tried to end all procceses using windows task manager. However that didn't work. I've recently tried getting it to work again. Whenever I try to reopen it it i...
[ "Honestly I would advise you to stop using IDLE, the fact that it runs program code in the same process as itself caused me a lot of problems when I used it, including things like not refreshing imported modules that were modified. Personally I switched to emacs, but you might like to try something like Notepad++.\...
[ 0 ]
[]
[]
[ "python", "python_idle" ]
stackoverflow_0003010030_python_python_idle.txt
Q: Any faster alternative to reading nth line of a file I have to read a file from a particular line number and I know the line number say "n": I have been thinking of two ways: 1. for i in range(n): fname.readline() k=readline() print k 2. i=0 for line in fname: dictionary[i]=line i=i+1 but I want a faster alternati...
Any faster alternative to reading nth line of a file
I have to read a file from a particular line number and I know the line number say "n": I have been thinking of two ways: 1. for i in range(n): fname.readline() k=readline() print k 2. i=0 for line in fname: dictionary[i]=line i=i+1 but I want a faster alternative as I might have to perform this on different files 2000...
[ "If the files aren't too huge, the linecache module of the standard library is pretty good -- it lets you very directly ask for the Nth line of such-and-such file.\nIf the files are huge, I recommend something like (warning, untested code):\ndef readlinenum(filepath, n, BUFSIZ=65536):\n bufs = [None] * 2\n previo...
[ 5, 2, 0 ]
[]
[]
[ "io", "performance", "python" ]
stackoverflow_0003011686_io_performance_python.txt
Q: How to detect non-graceful disconnect of Twisted on Linux? I wrote a server based on Twisted, and I encountered a problem, some of the clients are disconnected not gracefully. For example, the user pulls out the network cable. For a while, the client on Windows is disconnected (the connectionLost is called, and it...
How to detect non-graceful disconnect of Twisted on Linux?
I wrote a server based on Twisted, and I encountered a problem, some of the clients are disconnected not gracefully. For example, the user pulls out the network cable. For a while, the client on Windows is disconnected (the connectionLost is called, and it is also written in Twisted). And on the Linux server side, my c...
[ "You're describing the behavior of TCP connections on an unreliable network. Twisted is merely exposing this behavior: after all, when you set up a TCP connection with Twisted, it is nothing more than a TCP connection.\nYou're mistaken when you say that the connectionLost callback isn't invoked even if you try to ...
[ 3, 1 ]
[]
[]
[ "networking", "python", "twisted" ]
stackoverflow_0003003450_networking_python_twisted.txt
Q: Reading UTF-8 XML and writing it to a file with Python I'm trying to parse UTF-8 XML file and save some parts of it to another file. Problem is, that this is my first Python script ever and I'm totally confused about the character encoding problems I'm finding. My script fails immediately when it tries to write no...
Reading UTF-8 XML and writing it to a file with Python
I'm trying to parse UTF-8 XML file and save some parts of it to another file. Problem is, that this is my first Python script ever and I'm totally confused about the character encoding problems I'm finding. My script fails immediately when it tries to write non-ascii character to a file, but it can print it to command ...
[ "You'll need to remove the call to encode() - that is, replace nodeValue.encode(\"utf-8\") with nodeValue - and then change the call to open() to\nwith open(\"uiStrings-fi.py\", \"w\", \"utf-8\") as f:\n\nThis uses a \"Unicode-aware\" version of open() which you will need to import from the codecs module, so also a...
[ 8, 0 ]
[]
[]
[ "python", "utf_8", "xml" ]
stackoverflow_0003011939_python_utf_8_xml.txt
Q: Track window/control resize in PyQt? I have a window with 2 QTableWidgets, having their scrolling synchronized. The 1st one usually has horizontal scroll, while the 2nd usually (automatically) not. In order for them to show consistent data (row against row) I make the 2nd have the scroll (through property Horizont...
Track window/control resize in PyQt?
I have a window with 2 QTableWidgets, having their scrolling synchronized. The 1st one usually has horizontal scroll, while the 2nd usually (automatically) not. In order for them to show consistent data (row against row) I make the 2nd have the scroll (through property HorizontalScrollBar -> AlwaysOn). But sometimes th...
[ "The answer was to reimplement the resizeEvent and check table.horizontalScrollBar().isVisible()\n" ]
[ 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0002916052_pyqt4_python.txt
Q: Python style: if statements vs. boolean evaluation One of the ideas of Python's design philosophy is "There should be one ... obvious way to do it." (PEP 20), but that can't always be true. I'm specifically referring to (simple) if statements versus boolean evaluation. Consider the following: if words: self.wo...
Python style: if statements vs. boolean evaluation
One of the ideas of Python's design philosophy is "There should be one ... obvious way to do it." (PEP 20), but that can't always be true. I'm specifically referring to (simple) if statements versus boolean evaluation. Consider the following: if words: self.words = words else: self.words = {} versus self.words...
[ "\"There should be only one\" can perfectly well always be true; it's the positive assertion \"there is only one\" that cannot be -- \"should\" implies a target, a goal, not the possibility of always reaching it (e.g., for numbers a and b, forbidding either b + a or a + b would be so absurd that there just cannot s...
[ 9, 2, 0 ]
[]
[]
[ "coding_style", "if_statement", "python" ]
stackoverflow_0003011763_coding_style_if_statement_python.txt
Q: HowTo init Django model, before using it? I'm new to python and django. Apps | Versions: Python 2.6.2 Django (working with PostgreSQL) Question: I wrote a simple model: class OperationType(models.Model): eid = models.IntegerField() name = models.TextField(blank=True) description...
HowTo init Django model, before using it?
I'm new to python and django. Apps | Versions: Python 2.6.2 Django (working with PostgreSQL) Question: I wrote a simple model: class OperationType(models.Model): eid = models.IntegerField() name = models.TextField(blank=True) description = models.TextField(blank=True) def __u...
[ "Here.\n", "You can use fixtures, check the Django Document.\n" ]
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003012481_django_python.txt
Q: Importing data from a text file using python I have a text file containing data in rows and columns (~17000 rows in total). Each column is a uniform number of characters long, with the 'unused' characters filled in by spaces. For example, the first column is 11 characters long, but the last four characters in th...
Importing data from a text file using python
I have a text file containing data in rows and columns (~17000 rows in total). Each column is a uniform number of characters long, with the 'unused' characters filled in by spaces. For example, the first column is 11 characters long, but the last four characters in that column are always spaces (so that it appears to...
[ "Python's struct.unpack is probably the quickest way to split fixed-length fields. Here's a function that will lazily read your file and return tuples of numbers that match your criteria:\nimport struct\n\ndef parsefile(filename):\n with open(filename) as myfile:\n for line in myfile:\n line = ...
[ 4, 3, 0, 0 ]
[ "entries = []\nwith open('my_file.txt', 'r') as f:\n for line in f.read().splitlines()\n line = line.split()\n if line[1].find('OW') >= 0\n entries.append( ( int(line[-2]) , int(line[-1]) ) )\n\nentries is an array containing tuples of the last two entries\nedit: oops\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0003012353_python.txt
Q: How to make a increasing numbers after filenames in C? I have a little problem. I need to do some little operations on quite many files in one little program. So far I have decided to operate them in a single loop where I just change the number after the name. The files are all named TFxx.txt where xx is increasin...
How to make a increasing numbers after filenames in C?
I have a little problem. I need to do some little operations on quite many files in one little program. So far I have decided to operate them in a single loop where I just change the number after the name. The files are all named TFxx.txt where xx is increasing number from 1 to 80. So how can I open them all in a singl...
[ "You can use sprintf as follows:\nfor(i=0; i<=80; i++) {\n char name[32];\n memset(name, 0, sizeof(name));\n FILE *fp;\n sprintf(name, \"TF%d.txt\", i);\n fp = fopen(name, \"r\");\n /* Do something */\n }\n\n", "In addition to Daniels answer I would like to add that\nchar name[8] should be little big...
[ 5, 1, 1, 0, 0 ]
[]
[]
[ "c", "file_io", "python" ]
stackoverflow_0003012161_c_file_io_python.txt
Q: python threading and performance? I had to do heavy I/o bound operation, i.e Parsing large files and converting from one format to other format. Initially I used to do it serially, i.e parsing one after another..! Performance was very poor ( it used take 90+ seconds). So I decided to use threading to improve the ...
python threading and performance?
I had to do heavy I/o bound operation, i.e Parsing large files and converting from one format to other format. Initially I used to do it serially, i.e parsing one after another..! Performance was very poor ( it used take 90+ seconds). So I decided to use threading to improve the performance. I created one thread for e...
[ "Under the usual Python interpreter, threading will not allocate more CPU cores to your program because of the global interpreter lock (aka. the GIL).\nThe multiprocessing module could help you out here. (Note that it was introduced in Python 2.6, but backports exist for Python 2.5.)\nAs MSalters says, if your prog...
[ 10, 2 ]
[]
[]
[ "multithreading", "performance", "python" ]
stackoverflow_0003012508_multithreading_performance_python.txt
Q: Character Encoding My text editor allows me to code in several different character formats Ansi, UTF-8, UTF-8(No BOM), UTF-16LE, and UTF-16BE. What is the difference between them? What is commonly regarded as the best format (I'm using Python if that makes a diffrence)? A: "Ansi" is a misnomer and usually re...
Character Encoding
My text editor allows me to code in several different character formats Ansi, UTF-8, UTF-8(No BOM), UTF-16LE, and UTF-16BE. What is the difference between them? What is commonly regarded as the best format (I'm using Python if that makes a diffrence)?
[ "\n\"Ansi\" is a misnomer and usually refers to some 8-bit encoding that's the default on the current platform (on \"western\" Windows installations that's usually Windows-1252). It only supports a small set of characters (256 different characters at most).\nUTF-8 is a variable-length, ASCII-compatible encoding cap...
[ 8, 3, 3 ]
[]
[]
[ "ansi", "python", "utf_16", "utf_8" ]
stackoverflow_0003012821_ansi_python_utf_16_utf_8.txt
Q: How do Django signals work? How does Django's event routing system work? A: Django signals are synchronous. The handlers are executed as soon as the signal is fired, and control returns only when all appropriate handlers have finished. A: You may find the documentation helpful.
How do Django signals work?
How does Django's event routing system work?
[ "Django signals are synchronous. The handlers are executed as soon as the signal is fired, and control returns only when all appropriate handlers have finished.\n", "You may find the documentation helpful.\n" ]
[ 18, 1 ]
[]
[]
[ "django", "python", "signals" ]
stackoverflow_0003012863_django_python_signals.txt
Q: When you write a Titanium app, is the source code visible to users? When you write an HTML/CSS/JavaScript app for Adobe AIR, the source files sit in a directory visible to anyone who looks. Appcelerator Titanium lets you code in JavaScript, Python, and Ruby. Is the bundling similar to AIR, with all the source expo...
When you write a Titanium app, is the source code visible to users?
When you write an HTML/CSS/JavaScript app for Adobe AIR, the source files sit in a directory visible to anyone who looks. Appcelerator Titanium lets you code in JavaScript, Python, and Ruby. Is the bundling similar to AIR, with all the source exposed?
[ "According to the Titanium FAQ, yes, your source code will be accessible to anyone who looks for it.\n", "As Nosredna added in the comment they seem to have gotten arround to that change in their newer framework versions. \nLook at this question to get some insight from an appcelerator found on how the framework ...
[ 5, 2 ]
[]
[]
[ "javascript", "python", "ria", "ruby", "titanium" ]
stackoverflow_0001020838_javascript_python_ria_ruby_titanium.txt
Q: Anyone Know a Great Sparse One Dimensional Array Library in Python? I am working on an algorithm in Python that uses arrays of int64s heavily. The arrays are typically sparse and are read from and written to constantly. I am currently using relatively large native arrays and the performance is good but the memory ...
Anyone Know a Great Sparse One Dimensional Array Library in Python?
I am working on an algorithm in Python that uses arrays of int64s heavily. The arrays are typically sparse and are read from and written to constantly. I am currently using relatively large native arrays and the performance is good but the memory usage is high (as expected). I would like to be able to have the array i...
[ "It sounds like the blist type (documentation, download) might be just what you're looking for (disclaimer: I'm the author). It has exactly the same interface as Python's list, so there's no learning curve, but it has different performance characteristics. In particular, it can efficiently handle sparse lists in...
[ 4, 1, 1, 1, 1 ]
[]
[]
[ "algorithm", "arrays", "performance", "python", "sparse_array" ]
stackoverflow_0003003008_algorithm_arrays_performance_python_sparse_array.txt
Q: Sequence and merge jpeg images using Python? im doing a project as part of academic programme.Im doing this in linux platform.here i wanted to create a application which retrieve some information from some pdf files .for eg i have pdfs of subject2,subject1,in both the whole pdf is divided in to 4 modules and i wa...
Sequence and merge jpeg images using Python?
im doing a project as part of academic programme.Im doing this in linux platform.here i wanted to create a application which retrieve some information from some pdf files .for eg i have pdfs of subject2,subject1,in both the whole pdf is divided in to 4 modules and i want to get the data of module 1 from pdf..for this ...
[ "Not exactly knowing what you mean my sequence - ImageMagick, esp. its 'montage' is probably the tool you need. IM has python interface, too, altough I have never used it. \nEDIT: As after your edit I do not get the point of this any more, I cannot recommend anything, either. :(\n" ]
[ 2 ]
[]
[]
[ "jpeg", "linux", "merge", "pdf", "python" ]
stackoverflow_0003013134_jpeg_linux_merge_pdf_python.txt
Q: add extra data to response object to render in template İ ned to write a code sniplet that enables to disable connection to some parts of a site. Admin and the mainpage will be displayable, but user section (which uses ajax) will be displayed, but can not be used (vith a transparent div set over the page). Also th...
add extra data to response object to render in template
İ ned to write a code sniplet that enables to disable connection to some parts of a site. Admin and the mainpage will be displayable, but user section (which uses ajax) will be displayed, but can not be used (vith a transparent div set over the page). Also there is a few pages which will be disabled. my logic is that, ...
[ "here documentation for process_view\nUsage is simple. process_view is called just before Django calls the view, and get few arguments:\n request - Request object\n view_func - View function\n view_args - Arguments\n view_kwargs - Keyword arguments\nWhich example do you need?\n" ]
[ 1 ]
[]
[]
[ "django", "middleware", "python", "request", "response" ]
stackoverflow_0003012341_django_middleware_python_request_response.txt
Q: trunk works tag doesn't? ---ImportError: No module named 2.1.2 Very confused. In my workspace, the trunk works fine when I do a: python ./manage.py runserver 9090 However when I tag it @ 2.1.2 and then check it out clean from the repository to a temporary directory on my desktop.. I get the following error: Tra...
trunk works tag doesn't? ---ImportError: No module named 2.1.2
Very confused. In my workspace, the trunk works fine when I do a: python ./manage.py runserver 9090 However when I tag it @ 2.1.2 and then check it out clean from the repository to a temporary directory on my desktop.. I get the following error: Traceback (most recent call last): File "./manage.py", line 33, in ...
[ "Django does not like it when the project directory contains periods. Rename it before running the project.\n" ]
[ 4 ]
[]
[]
[ "django", "importerror", "python" ]
stackoverflow_0003013819_django_importerror_python.txt
Q: Python : get all exe files in current directory and run them? First of all this is not homework, I'm in a desperate need for a script that will do the following, my problem is, I've never had to deal with python before so I barely know how to use it - and I need it to launch unit tests in TeamCity via a commandlin...
Python : get all exe files in current directory and run them?
First of all this is not homework, I'm in a desperate need for a script that will do the following, my problem is, I've never had to deal with python before so I barely know how to use it - and I need it to launch unit tests in TeamCity via a commandline build runner What I need exactly is : a *.bat file that will run ...
[ "import glob, os\ndef solution():\n for fn in glob.glob(\"*_text.exe\"):\n os.startfile(fn)\n\n", "If you copy this into a file, the script should do as you asked.\nimport os # Access the operating system.\n\ndef solution(): # Create a function for later.\n for name in os.listdir(os.getcwd()):\...
[ 9, 3 ]
[]
[]
[ "python", "teamcity_5.1" ]
stackoverflow_0003014120_python_teamcity_5.1.txt
Q: Talking to an Authentication Server I'm building my startup and I'm thinking ahead for shared use of services. So far I want to allow people who have a user account on one app to be able to use the same user account on another app. This means I will have to build an authentication server. I would like some opinion...
Talking to an Authentication Server
I'm building my startup and I'm thinking ahead for shared use of services. So far I want to allow people who have a user account on one app to be able to use the same user account on another app. This means I will have to build an authentication server. I would like some opinions on how to allow an app to talk to the a...
[ "Assuming you plan to write your own auth client code, it isn't event-driven, and you don't need to validate an https certificate, I would suggest using python's built-in urllib2 to call the auth server. This will minimize dependencies, which ought to make deployment and upgrades easier.\nThat being said, there ar...
[ 1, 0, 0 ]
[]
[]
[ "authentication", "python", "rest" ]
stackoverflow_0002986317_authentication_python_rest.txt
Q: voice communication for python help! I'm currently trying to write a voicechat program in python. All tips/trick is welcome to do this. So far I found pyAudio to be a wrapper of PortAudio. So I played around with that and got an input stream from my microphone to be played back to my speakers. Only RAW of course. ...
voice communication for python help!
I'm currently trying to write a voicechat program in python. All tips/trick is welcome to do this. So far I found pyAudio to be a wrapper of PortAudio. So I played around with that and got an input stream from my microphone to be played back to my speakers. Only RAW of course. But I can't send RAW-data over the netowrk...
[ "You could try Huffman encoding, it's a pretty neat concept. I don't know how fast you could make it, but I'm sure if you created your own C/C++ module you could make it a lot faster.\nOf course, there may be already some modules out there that do exactly what you need - I've just never used them, so I'm completely...
[ 0 ]
[]
[]
[ "networking", "python", "speex", "tcp", "voip" ]
stackoverflow_0003013592_networking_python_speex_tcp_voip.txt
Q: How to delete every reference of an object in Python? Supose you have something like: x = "something" b = x l = [b] How can you delete the object only having one reference, say x? del x won't do the trick; the object is still reachable from b, for example. A: No no no. Python has a garbage collector that has ve...
How to delete every reference of an object in Python?
Supose you have something like: x = "something" b = x l = [b] How can you delete the object only having one reference, say x? del x won't do the trick; the object is still reachable from b, for example.
[ "No no no. Python has a garbage collector that has very strong territory issues - it won't mess with you creating objects, you don't mess with it deleting objects.\nSimply put, it can't be done, and for a good reason.\nIf, for instance, your need comes from cases of, say, caching algorithms that keep references, bu...
[ 18, 12, 4 ]
[]
[]
[ "del", "garbage_collection", "python", "reference", "weak_references" ]
stackoverflow_0003013304_del_garbage_collection_python_reference_weak_references.txt
Q: PyQt4: My database displays empty cells I am using the pyqt4 framework to do some displays for database forms. Unfortunately, I hit a snag while trying to filter and display my database by last name. Assume that the database connection works. Also assume that I have the correct amount of items in my tupleHeader...
PyQt4: My database displays empty cells
I am using the pyqt4 framework to do some displays for database forms. Unfortunately, I hit a snag while trying to filter and display my database by last name. Assume that the database connection works. Also assume that I have the correct amount of items in my tupleHeader since I use the same initializeModel method ...
[ "While I could not find the solution to my problem, it solved itself. I am not certain, but I think it was this code snippet that made it work.\nself.dbmanip = CoreDB(self.userTableView, self.table)\n\nThis was put inside of the SetupUi() method created by the Qt4 Designer. I think either the dbmanip that contain...
[ 0 ]
[]
[]
[ "pyqt4", "python", "qt", "qt4", "qt4.6" ]
stackoverflow_0002997418_pyqt4_python_qt_qt4_qt4.6.txt
Q: Python ftplib - any way to shut it up? I am writing a test harness in python and as part of the testing I need to initialise an FTP server and upload various files. I am using ftplib and everything is working ok. The only problem I have is that I am seeing loads of FTP text appearing in the console window intermix...
Python ftplib - any way to shut it up?
I am writing a test harness in python and as part of the testing I need to initialise an FTP server and upload various files. I am using ftplib and everything is working ok. The only problem I have is that I am seeing loads of FTP text appearing in the console window intermixed with my test results, which makes scannin...
[ "You need to manually pass empty (or otherwise customized) callbacks to at least retrlines and dir. By default they print to stdout (questionable design). By default calls (probably for debugging) like \nmyFTP.retrlines(command)\nmyFTP.dir(someDir)\n\nwill print to your terminal. Remove them or use custom callba...
[ 4 ]
[]
[]
[ "ftplib", "python" ]
stackoverflow_0003014624_ftplib_python.txt
Q: What are the implications of running python with the optimize flag? What does Python do differently when running with the -O (optimize) flag? A: assert statements are completely eliminated, as are statement blocks of the form if __debug__: ... (so you can put your debug code in such statements blocks and just ru...
What are the implications of running python with the optimize flag?
What does Python do differently when running with the -O (optimize) flag?
[ "assert statements are completely eliminated, as are statement blocks of the form if __debug__: ... (so you can put your debug code in such statements blocks and just run with -O to avoid that debug code).\nWith -OO, in addition, docstrings are also eliminated.\n", "From the docs:\n\n\nYou can use the -O or -OO s...
[ 39, 34, 10, 9 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0002830358_optimization_python.txt
Q: How to accept localized date format (e.g dd/mm/yy) in a DateField on an admin form? Is it possible to customize a django application to have accept localized date format (e.g dd/mm/yy) in a DateField on an admin form ? I have a model class : class MyModel(models.Model): date = models.DateField("Date") ...
How to accept localized date format (e.g dd/mm/yy) in a DateField on an admin form?
Is it possible to customize a django application to have accept localized date format (e.g dd/mm/yy) in a DateField on an admin form ? I have a model class : class MyModel(models.Model): date = models.DateField("Date") And associated admin class class MyModelAdmin(admin.ModelAdmin): pass On django a...
[ "The admin system uses a default ModelForm for editing the objects. You'll need to provide a custom form so that you can begin overriding field behaviour.\nInside your modelform, override the field using a DateField, and use the input_formats option.\nMY_DATE_FORMATS = ['%d/%m/%Y',]\n\nclass MyModelForm(forms.Model...
[ 5, 2 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0002439801_django_django_admin_python.txt
Q: Problem with eastern european characters when scraping data from the European Parliament Website EDIT: thanks a lot for all the answers an points raised. As a novice I am a bit overwhelmed, but it is a great motivation for continuing learning python!! I am trying to scrape a lot of data from the European Parliamen...
Problem with eastern european characters when scraping data from the European Parliament Website
EDIT: thanks a lot for all the answers an points raised. As a novice I am a bit overwhelmed, but it is a great motivation for continuing learning python!! I am trying to scrape a lot of data from the European Parliament website for a research project. The first step is to create a list of all parliamentarians, however ...
[ "I was able to show 31 names starting with A with code:\nextended_chars = srange(r\"[\\0x80-\\0x7FF]\")\nspecial_chars = ' -'''\nname = Word(alphanums + alphas8bit + extended_chars + special_chars)\n\nAs John noticed you need more unicode characters (extended_chars) and some names have hypehen etc. (special chars)....
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "html_parsing", "python", "screen_scraping" ]
stackoverflow_0003013355_html_parsing_python_screen_scraping.txt
Q: Preserve file attributes in ZipFile I'm looking for a way to preserve the file attributes (eg. read-only) of a file that gets written to a zipfile.ZipFile instance. The files I add to the zip archive gets their file attributes reset, eg. the read-only flag is gone when inspecting the archive with zip applications ...
Preserve file attributes in ZipFile
I'm looking for a way to preserve the file attributes (eg. read-only) of a file that gets written to a zipfile.ZipFile instance. The files I add to the zip archive gets their file attributes reset, eg. the read-only flag is gone when inspecting the archive with zip applications and after unzip. My current environment i...
[ "The problem I had was the heavily undocumented zipfile.ZipInfo.external_attr. All examples I found of this object refeered to the *nix file permission style.\nMy implementation will run on windows.\nSo I went about some \"reverse engineering\". Heh.\nThe magic number for windows read-only ZipInfo.external_attr is ...
[ 4 ]
[]
[]
[ "file", "python", "python_zipfile", "zip" ]
stackoverflow_0003007233_file_python_python_zipfile_zip.txt
Q: How to expose a web appication via API? we have create a web application on top of google app engine and python. which is almost about to complete it web front phase. I would also like to make it available almost all part of it to external applications. { via , xml , json , http , as many as possible. } . what's t...
How to expose a web appication via API?
we have create a web application on top of google app engine and python. which is almost about to complete it web front phase. I would also like to make it available almost all part of it to external applications. { via , xml , json , http , as many as possible. } . what's the best way to do it ? any library either for...
[ "Maybe django-piston could be of interest for you. But I do not know if there are restrictions for appengine.\n", "First of all there is no much difference between service for humans and for robots (web-services).\nBut restish -- mini-framework for building RESTful web services can be your choice.\n" ]
[ 4, 2 ]
[]
[]
[ "api", "google_app_engine", "python" ]
stackoverflow_0003014631_api_google_app_engine_python.txt
Q: Using RE to retrieve an ID I am trying to use RE to match a changing ID and extract it. I am having some bother getting it working. The String is: m = 'Some Text That exists version 1.0.41.476 Fri Jun 4 16:50:56 EDT 2010' The code I have tried so far is: r = re.compile(r'(s*\s*)(\S+)') m = m.match(r) Can anyone...
Using RE to retrieve an ID
I am trying to use RE to match a changing ID and extract it. I am having some bother getting it working. The String is: m = 'Some Text That exists version 1.0.41.476 Fri Jun 4 16:50:56 EDT 2010' The code I have tried so far is: r = re.compile(r'(s*\s*)(\S+)') m = m.match(r) Can anyone help extract this string. Thank...
[ ">>> m = 'Some Text That exists version 1.0.41.476 Fri Jun 4 16:50:56 EDT 2010'\n>>> import re\n>>> re.search(r'version (\\S+)', m).group(1)\n('1.0.41.476',)\n\n", "Here are RE-based and string-based versions:\nimport re\n\ndef bystr(text):\n words = text.split()\n index = words.index('version') + 1\n r...
[ 4, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003015028_python_regex.txt
Q: Python and libpcap. find source mac address of packet I'm writing python program to build mac-address cache using pcap. But pcap module for python has no good documentation. I have found this page http://pylibpcap.sourceforge.net/ with code example and it works fine. Can anybody modify this example to make it able...
Python and libpcap. find source mac address of packet
I'm writing python program to build mac-address cache using pcap. But pcap module for python has no good documentation. I have found this page http://pylibpcap.sourceforge.net/ with code example and it works fine. Can anybody modify this example to make it able to show the source mac-address for each packet? Or point m...
[ "Google \"Ethernet frame formats\". The first 6 octets of a packet is the destination MAC address, which is immediately followed by the 6 octets of source MAC address.\nThis Wikipedia page may help.\n", "Oh my god man, why are you doing this ? Use Scapy instead.\n" ]
[ 3, 2 ]
[]
[]
[ "libpcap", "mac_address", "pcap", "python" ]
stackoverflow_0003014218_libpcap_mac_address_pcap_python.txt
Q: When will Unladen Swallow be "done" or "ready" for real use? It looks like Google hasn't updated the results section since the Q4 2009 posting. I've been wondering when it will be put in the Python trunk, and if it's, in any way, production ready. Also, "We aspire to do no original work" is in the Q4 plan. Did Goo...
When will Unladen Swallow be "done" or "ready" for real use?
It looks like Google hasn't updated the results section since the Q4 2009 posting. I've been wondering when it will be put in the Python trunk, and if it's, in any way, production ready. Also, "We aspire to do no original work" is in the Q4 plan. Did Google bite off more than what they could handle, or does anyone know...
[ "According to this, Unladen Swallow will be a part of python 3, it is an officially accepted PEP: http://www.python.org/dev/peps/pep-3146/\n" ]
[ 2 ]
[]
[]
[ "python", "unladen_swallow" ]
stackoverflow_0003016134_python_unladen_swallow.txt
Q: Editing django code within django - Django just wondering if it would be possible in some experimental way, to edit django app code within django safely to then refresh the compiled files. Would be great if someone has tried something similar already or has some ideas. I would like to be able to edit small bits of...
Editing django code within django - Django
just wondering if it would be possible in some experimental way, to edit django app code within django safely to then refresh the compiled files. Would be great if someone has tried something similar already or has some ideas. I would like to be able to edit small bits of code from a web interface, so I can easily main...
[ "Providing an editing interface is one half of the battle but it's pretty straightforward. There are already apps out there to provide editing of templates and media files so it's pretty much just an extension of that.\nThe hardest part is restarting the server which would have to happen in order for the new code t...
[ 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003015825_django_python.txt
Q: Give a reference to a python instance attribute at class definition I have a class with attributes which have a reference to another attribute of this class. See class Device, value1 and value2 holding a reference to interface: class Interface(object): def __init__(self): self.port=None class Value(ob...
Give a reference to a python instance attribute at class definition
I have a class with attributes which have a reference to another attribute of this class. See class Device, value1 and value2 holding a reference to interface: class Interface(object): def __init__(self): self.port=None class Value(object): def __init__(self, interface, name): self.interface=in...
[ "interface is a class attribute. So when you do\nd2=Device(\"Bar\")\n\nyou are changing the port of the interface for all objects of class Device. \n\nIf you want to have these attributes per object instance, you have to put them into the __init__ method:\nclass Device(object):\n def __init__(self, port):\n ...
[ 4, 2 ]
[]
[]
[ "attributes", "class", "python", "reference" ]
stackoverflow_0003016770_attributes_class_python_reference.txt
Q: How to change the amount of increments in pyplot axis Hi probably quite a simple question but.. When plotting a graph using matplotlib.pyplot my Y axis goes from -0.04 to 0.03 which is fine but there are 8 labels for increments (eg 0.03,0.02,0.01 etc.). I need more maybe 16 or so. Thanks for your help A: Matplo...
How to change the amount of increments in pyplot axis
Hi probably quite a simple question but.. When plotting a graph using matplotlib.pyplot my Y axis goes from -0.04 to 0.03 which is fine but there are 8 labels for increments (eg 0.03,0.02,0.01 etc.). I need more maybe 16 or so. Thanks for your help
[ "Matplotlib has several different algorithms for choosing tick locations automatically, and e.g. LinearLocator or MaxNLocator may suit your purpose. See the major_minor demo for how to use Locators in general, and the ticker api documentation for the various Locators available. The documentation for the individual ...
[ 5, 3 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003013350_matplotlib_python.txt
Q: Import problem with PyCrypto in Jython I am currently trying to get python bittorrent tracker running inside of jython and i encountered this problem: the tracker uses PyCrypto library which i compiled for my platform and added into the python path. When i try to run code, however, i get following error: Exception...
Import problem with PyCrypto in Jython
I am currently trying to get python bittorrent tracker running inside of jython and i encountered this problem: the tracker uses PyCrypto library which i compiled for my platform and added into the python path. When i try to run code, however, i get following error: Exception in thread "MainThread" Traceback (most rece...
[ "This is happening probably because pycrypto is a C-extension, and Jython will not be able to call it without a Java wrapper for this extension.\n", "I am not sure this applies to your situation, but some googling led to this:\n(from http://wiki.python.org/jython/JythonFaq/InstallingJython)\n\nJython cannot find ...
[ 4, 0 ]
[]
[]
[ "jython", "pycrypto", "python" ]
stackoverflow_0003017341_jython_pycrypto_python.txt
Q: CherryPy behind Nginx reverse-proxy POST requests corrupted/truncated I have put my application using Cherrypy 3.1.2 behind Nginx configured as a reverse-proxy. All is working right for GET requests, but all POST requests return HTTP 400 - Malformed header. I traced into CherryPy WSGI-Server source code to see the...
CherryPy behind Nginx reverse-proxy POST requests corrupted/truncated
I have put my application using Cherrypy 3.1.2 behind Nginx configured as a reverse-proxy. All is working right for GET requests, but all POST requests return HTTP 400 - Malformed header. I traced into CherryPy WSGI-Server source code to see the request-handling code and found out that if for GET requests the first req...
[ "you could try the parameters:\nignore_invalid_headers on;\nsendfile on;\n\nin the http block... also might try disabling keepalives and ensure you're logging access/errors to debug.\n" ]
[ 1 ]
[]
[]
[ "cherrypy", "nginx", "python", "reverse_proxy" ]
stackoverflow_0002272931_cherrypy_nginx_python_reverse_proxy.txt
Q: Idea on parsing character syntax diagram Folks I'm implementing a weird thing, I have to write a utility to parse a syntax diagram in plain text format and convert it to xml format, the thing basically is identical as this from IBM(like in the "Creating a No-Conversion Job" part): http://publib.boulder.ibm.com/inf...
Idea on parsing character syntax diagram
Folks I'm implementing a weird thing, I have to write a utility to parse a syntax diagram in plain text format and convert it to xml format, the thing basically is identical as this from IBM(like in the "Creating a No-Conversion Job" part): http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.s...
[ "I've never done anything like that before, but this is how I would approach it.\nFirst, I'd start off with something like this:\nclass CharGrid(object):\n def __init__(self, text):\n self.lines = text.split('\\n')\n\n def __getitem__(self, pos):\n try:\n col, row = pos\n excep...
[ 2, 1 ]
[]
[]
[ "parsing", "python", "xml" ]
stackoverflow_0003015569_parsing_python_xml.txt
Q: python distutils does not include data_files I am new to distutils.. I am trying to include few data files along with the package.. here is my code.. from distutils.core import setup setup(name='Scrapper', version='1.0', description='Scrapper', packages=['app', 'db', 'model', 'util'], ...
python distutils does not include data_files
I am new to distutils.. I am trying to include few data files along with the package.. here is my code.. from distutils.core import setup setup(name='Scrapper', version='1.0', description='Scrapper', packages=['app', 'db', 'model', 'util'], data_files=[('app', ['app/scrapper.db'])] ...
[ "You probably need to add a MANIFEST.in file containing \"include app/scrapper.db\". \nIt's a bug in distutils that makes this necessary: anything in data_files or package_data should be included in the generated MANIFEST automatically. But in Python 2.6 and earlier, it is not, so you have to include it in MANIFEST...
[ 21, 1 ]
[]
[]
[ "distutils", "installation", "python" ]
stackoverflow_0002994396_distutils_installation_python.txt
Q: How to create a translucid/alpha-transparent rectangle using wxpython? I have a wx.panel and I want to put a translucid rectangle on a part of it. How can I do that using wxpython? A: You can do this using a wx.GraphicsContext, and there's a good example in the wxPython demo (located in the Miscellaneous categor...
How to create a translucid/alpha-transparent rectangle using wxpython?
I have a wx.panel and I want to put a translucid rectangle on a part of it. How can I do that using wxpython?
[ "You can do this using a wx.GraphicsContext, and there's a good example in the wxPython demo (located in the Miscellaneous category).\n" ]
[ 1 ]
[]
[]
[ "python", "translucency", "transparency", "transparent", "wxpython" ]
stackoverflow_0003016497_python_translucency_transparency_transparent_wxpython.txt
Q: Pylons 1.0 AttributeError: 'module' object has no attribute 'metadata' Python noob trying to learn Pylons. I'm using the QuickWiki tutorial (http://pylonshq.com/docs/en/1.0/tutorials/quickwiki_tutorial/) from the 1.0 documentation, but this alleged "1.0" doc seems to just be "0.9.7"; I suspect that this has someth...
Pylons 1.0 AttributeError: 'module' object has no attribute 'metadata'
Python noob trying to learn Pylons. I'm using the QuickWiki tutorial (http://pylonshq.com/docs/en/1.0/tutorials/quickwiki_tutorial/) from the 1.0 documentation, but this alleged "1.0" doc seems to just be "0.9.7"; I suspect that this has something to do with the error I'm getting. When I execute "paster setup-app devel...
[ "This is mistake in documentation http://pylonshq.com/docs/en/1.0/tutorials/quickwiki_tutorial/ \nDeclare pages_table like this\nfrom quickwiki.model.meta import Base\npages_table = sa.Table('pages', Base.metadata,\n sa.Column('title', sa.types.Unicode(40), primary_key=True),\n sa.Colu...
[ 4, 2, 2 ]
[]
[]
[ "attributeerror", "metadata", "pylons", "python", "sqlalchemy" ]
stackoverflow_0003011108_attributeerror_metadata_pylons_python_sqlalchemy.txt
Q: Create a color generator from given colormap in matplotlib I have a series of lines that each need to be plotted with a separate colour. Each line is actually made up of several data sets (positive, negative regions etc.) and so I'd like to be able to create a generator that will feed one colour at a time across a...
Create a color generator from given colormap in matplotlib
I have a series of lines that each need to be plotted with a separate colour. Each line is actually made up of several data sets (positive, negative regions etc.) and so I'd like to be able to create a generator that will feed one colour at a time across a spectrum, for example the gist_rainbow map shown here. I have f...
[ "To index colors from a specific colormap you can use:\nimport pylab\nNUM_COLORS = 22\n\ncm = pylab.get_cmap('gist_rainbow')\nfor i in range(NUM_COLORS):\n color = cm(1.*i/NUM_COLORS) # color will now be an RGBA tuple\n\n# or if you really want a generator:\ncgen = (cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS...
[ 35 ]
[]
[]
[ "color_mapping", "matplotlib", "python" ]
stackoverflow_0003016283_color_mapping_matplotlib_python.txt
Q: How can I display multiple django modelformset forms in grouped fieldsets? I have a problem with needing to provide multiple model backed forms on the same page. I understand how to do this with single forms, i.e. just create both the forms call them something different then use the appropriate names in the templ...
How can I display multiple django modelformset forms in grouped fieldsets?
I have a problem with needing to provide multiple model backed forms on the same page. I understand how to do this with single forms, i.e. just create both the forms call them something different then use the appropriate names in the template. Now how exactly do you expand that solution to work with modelformsets? Th...
[ "In the view:\nforms = itertools.izip(base_forms, likes_forms)\n\nIn the template:\n{% for (base_form,like_form) in forms %}\n\n", "After doing a fair amount of poking around and hack experimenting I've come up with the following solution thanks in huge part to Ignacio Vazquez-Abrams :)\nIn the view:\nforms = ite...
[ 2, 0 ]
[]
[]
[ "django_forms", "django_models", "django_templates", "python" ]
stackoverflow_0003010783_django_forms_django_models_django_templates_python.txt
Q: Problems replacing a Python extension module while Python script is executing I'm trying to solve the following problem: Say I have a Python script (let's call it Test.py) which uses a C++ extension module (made via SWIG, let's call the module "Example"). I have Test.py, Example.py, and _Example.so in the same d...
Problems replacing a Python extension module while Python script is executing
I'm trying to solve the following problem: Say I have a Python script (let's call it Test.py) which uses a C++ extension module (made via SWIG, let's call the module "Example"). I have Test.py, Example.py, and _Example.so in the same directory. Now, in the middle of running Test.py, I want to make a change to my Exam...
[ "You could, on starting Test.py, copy the Example.* files to a temp folder unique for that instance (take a look at tempfile.mkdtemp, it can create safe, unique folders), add that to sys.path and then import Example; and on Test.py shutdown remove that folder (shutils.rmtree) at the cleanup stage.\nThis would mean ...
[ 2, 0 ]
[]
[]
[ "python", "segmentation_fault", "swig" ]
stackoverflow_0003018122_python_segmentation_fault_swig.txt
Q: Finding new IP in a file I have a file of IP addresses called "IPs". When I parse a new IP from my logs, I'd like to see if the new IP is already in file IPs, before I add it. I know how to add the new IP to the file, but I'm having trouble seeing if the new IP is already in the file. !/usr/bin/python from IPy imp...
Finding new IP in a file
I have a file of IP addresses called "IPs". When I parse a new IP from my logs, I'd like to see if the new IP is already in file IPs, before I add it. I know how to add the new IP to the file, but I'm having trouble seeing if the new IP is already in the file. !/usr/bin/python from IPy import IP IP = IP('192.168.1.2') ...
[ "iplist = []\n\n# With takes care of all the fun file handling stuff (closing, etc.)\nwith open('ips.txt', 'r') as f:\n for line in f:\n iplist.append(line.strip()) # Gets rid of the newlines at the end\n\n# Change the above to this for Python versions < 2.6\nf = open('ips.txt', 'r')\nfor line in f:\n ...
[ 3, 2, 1 ]
[]
[]
[ "compare", "ip_address", "ironpython", "python" ]
stackoverflow_0003017176_compare_ip_address_ironpython_python.txt
Q: Missing 'read' prompt in bash when using ssh? Please tell me I'm missing something really obvious here: $ cat ~/bashplay/f #!/bin/bash read -p 'RDY> ' x echo $x $ ~/bashplay/f RDY> direct execution direct execution $ ssh somehost ~/bashplay/f indirect via ssh indirect via ssh Note the missing "RDY>" prompt when...
Missing 'read' prompt in bash when using ssh?
Please tell me I'm missing something really obvious here: $ cat ~/bashplay/f #!/bin/bash read -p 'RDY> ' x echo $x $ ~/bashplay/f RDY> direct execution direct execution $ ssh somehost ~/bashplay/f indirect via ssh indirect via ssh Note the missing "RDY>" prompt when using ssh. I see the same thing in python when usi...
[ "From man bash:\n\n-p prompt\n Display prompt on standard error, without a trailing new‐\n line, before attempting to read any input. The prompt is\n displayed only if input is coming from a terminal.\n\nUse the ssh option -t which forces pseudo tty...
[ 5 ]
[]
[]
[ "bash", "python", "readline", "ssh" ]
stackoverflow_0003018036_bash_python_readline_ssh.txt
Q: How exactly does a python (django) request happen? does it have to reparse all the codebase? With a scripting language like python (or php), things are not compiled down to bytecode like in .net or java. So does this mean that on every request, it has to go through the entire application and parse/compile it? Or ...
How exactly does a python (django) request happen? does it have to reparse all the codebase?
With a scripting language like python (or php), things are not compiled down to bytecode like in .net or java. So does this mean that on every request, it has to go through the entire application and parse/compile it? Or at least all the code required for the given call stack?
[ "\nWith a scripting language like python\n (or php), things are not compiled down\n to bytecode like in .net or java.\n\nWrong: everything you import in Python gets compiled to bytecode (and saved as .pyc files if you can write to the directory containing the source you're importing -- standard libraries &c are g...
[ 5, 3 ]
[]
[]
[ "django", "pipeline", "python", "request_pipeline" ]
stackoverflow_0003018690_django_pipeline_python_request_pipeline.txt
Q: Form values in a list item Here is the site mock-up I'm working on for my job: http://dev.arm.gov/~noensie/dqhands/cgi-bin/explorer. I'm still a novice in web developing and I need help with placing form values in a list item to pass on to another page. I'd rather not go in great detail the purpose of this website...
Form values in a list item
Here is the site mock-up I'm working on for my job: http://dev.arm.gov/~noensie/dqhands/cgi-bin/explorer. I'm still a novice in web developing and I need help with placing form values in a list item to pass on to another page. I'd rather not go in great detail the purpose of this website, but in terms of its basic use,...
[ "You should use hidden input fields.\nIt depends on what server side language you fancy using, but I'd go for the following naming scheme for your hidden fields:\nrequest[][site]\nrequest[][datastream]\nrequest[][facility]\nrequest[][date]\n\nThe \"[]\" notation places the data in an array (for PHP at least). The p...
[ 2 ]
[]
[]
[ "html", "javascript", "jquery", "python" ]
stackoverflow_0003018760_html_javascript_jquery_python.txt
Q: How do i print a table in python? I am trying to print the output of the following code in two columns using the python launcher: def main(): print "This program illustrates a chaotic function" n = input("How many numbers should I print? ") x = input("Enter a numbers between 0 and 1: ") y = input("...
How do i print a table in python?
I am trying to print the output of the following code in two columns using the python launcher: def main(): print "This program illustrates a chaotic function" n = input("How many numbers should I print? ") x = input("Enter a numbers between 0 and 1: ") y = input("Enter another number between 0 and 1: "...
[ "for x, y in listOfTwotuples:\n print x, y\n\nGiven that you've provided no details I've gone ahead and assumed that you've got a list of two-tuples. Update your question with more info and I'll update my answer to match!\nedit: with actual details now\nIf in each loop you store the numbers in a list, you can t...
[ 3, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003018295_python.txt
Q: The LoadLibraryA method returns error code 1114 (ERROR_DLL_INIT_FAILED) after more than 1000 cycles of loading/unloading I'm programing on C++, I'm using Visual Studio 2008, Windows XP, and I have the following problem: My application, that is a DLL that can be used from Python, loads an external dll, uses the req...
The LoadLibraryA method returns error code 1114 (ERROR_DLL_INIT_FAILED) after more than 1000 cycles of loading/unloading
I'm programing on C++, I'm using Visual Studio 2008, Windows XP, and I have the following problem: My application, that is a DLL that can be used from Python, loads an external dll, uses the required methods, and then unloads this external Dll. It's working properly, but after more than 1000 cycles the method "LoadLibr...
[ "Make sure that initialization code of the loaded/unloaded library doesn't leak memory. Many libraries expect to be loaded only once and not always clean up their resources properly.\nE.g. in C++ file at the top level one can declare and initialize a variable like this:\nAClass *a = new AClass(1,2,3);\n\nThe code w...
[ 1 ]
[]
[]
[ "c++", "loadlibrary", "python" ]
stackoverflow_0003018348_c++_loadlibrary_python.txt
Q: 64-bit integers in Cython I'm trying to interface a C++ library (pHash) with Python using Cython, but I have trouble with some of the types. The library functions use "unsigned long long" and I can't find a way to declare variables and parameters with this type. I searched for a list of the types that I can use wi...
64-bit integers in Cython
I'm trying to interface a C++ library (pHash) with Python using Cython, but I have trouble with some of the types. The library functions use "unsigned long long" and I can't find a way to declare variables and parameters with this type. I searched for a list of the types that I can use with cdef but I found nothing. Ca...
[ "I've been able to use both unsigned long long and long long just fine with cdef. See for instance my answer to this question here. I just tried running the same code there with unsigned long long instead of long long and it worked just fine. Can you be more specific about what problems you are having with these ty...
[ 5, 3 ]
[]
[]
[ "cython", "python", "types" ]
stackoverflow_0003018425_cython_python_types.txt
Q: How do I get the key of an item when doing a FOR loop through a dictionary or list in Python? I am new to Python. Say I have a list: list = ['A','B','C','D'] The key for each item respectively here is 0,1,2,3 - right? Now I am going to loop through it with a for loop... for item in list: print item That's gr...
How do I get the key of an item when doing a FOR loop through a dictionary or list in Python?
I am new to Python. Say I have a list: list = ['A','B','C','D'] The key for each item respectively here is 0,1,2,3 - right? Now I am going to loop through it with a for loop... for item in list: print item That's great, I can print out my list. How do I get the key here? For example being able to do: print key pr...
[ "The answer is different for lists and dicts. \nA list has no key. Each item will have an index. You can enumerate a list like this:\n>>> l = ['A','B','C','D']\n>>> for index, item in enumerate(l):\n... print index\n... print item\n... \n0\nA\n1\nB\n2\nC\n3\nD\n\nI used your example here, but called the lis...
[ 24, 11, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003019049_python.txt
Q: Binning into timeslots - Is there a better way than using list comp? I have a dataset of events (tweets to be specific) that I am trying to bin / discretize. The following code seems to work fine so far (assuming 100 bins): HOUR = timedelta(hours=1) start = datetime.datetime(2009,01,01) z = [dt + x*HOUR for x in x...
Binning into timeslots - Is there a better way than using list comp?
I have a dataset of events (tweets to be specific) that I am trying to bin / discretize. The following code seems to work fine so far (assuming 100 bins): HOUR = timedelta(hours=1) start = datetime.datetime(2009,01,01) z = [dt + x*HOUR for x in xrange(1, 100)] But then, I came across this fateful line at python docs '...
[ "The expression from the docs looks like this:\nzip(*[iter(s)]*n)\n\nThis is equivalent to:\nit = iter(s)\nzip(*[it, it, ..., it]) # n times\n\nThe [...]*n repeats the list n times, and this results in a list that contains nreferences to the same iterator.\nThis is again equal to:\nit = iter(s)\nzip(it, it, ..., it...
[ 5, 5 ]
[]
[]
[ "python" ]
stackoverflow_0003019084_python.txt
Q: Python's string.translate() doesn't fully work? Given this example, I get the error that follows: print u'\2033'.translate({2033:u'd'}) C:\Python26\lib\encodings\cp437.pyc in encode(self, input, errors) 10 11 def encode(self,input,errors='strict'): ---> 12 return codecs.charmap_encode(input,...
Python's string.translate() doesn't fully work?
Given this example, I get the error that follows: print u'\2033'.translate({2033:u'd'}) C:\Python26\lib\encodings\cp437.pyc in encode(self, input, errors) 10 11 def encode(self,input,errors='strict'): ---> 12 return codecs.charmap_encode(input,errors,encoding_map) 13 14 def decode(s...
[ "Try this instead:\n>>> print u'\\u2033'.translate({0x2033:u'd'})\nd\n\nSince you used u'\\2033' instead of u'\\u2033', The result was two characters: u'\\203'+u'3'. Trying to print this gave an exception because your terminal's encoding doesn't support the character u'\\203' (which is the same as u'\\x83').\nAlso ...
[ 6 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0003019381_python_unicode.txt
Q: How can I build a wrapper to wait for listening on a port? I am looking for a way of programmatically testing a script written with the asyncore Python module. My test consists of launching the script in question -- if a TCP listen socket is opened, the test passes. Otherwise, if the script dies before getting to ...
How can I build a wrapper to wait for listening on a port?
I am looking for a way of programmatically testing a script written with the asyncore Python module. My test consists of launching the script in question -- if a TCP listen socket is opened, the test passes. Otherwise, if the script dies before getting to that point, the test fails. The purpose of this is knowing if a ...
[ "This felt like code-golf:\n#!/bin/sh\n# iamwaiting: run a command for a specified time then kill it\n# returns the status of cmd on normal termination\n\n\nopath=$PATH\nPATH=/bin:/usr:/bin\n\nSIGNAL=\ncase $1 in\n -*) SIGNAL=$1; shift;;\nesac\n\ncase $# in\n 0|1) echo 'usage iamwaiting [-signal] wait cmd [ar...
[ 0, 0 ]
[]
[]
[ "python", "sockets", "testing", "wrapper" ]
stackoverflow_0003014686_python_sockets_testing_wrapper.txt