content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: python: quickest way to split a file into two files randomly python: what is the quickest way to split a file into two files, each file having half of the number of lines in the original file, such that the lines in each of the two files are random? for example: if the file is 1 2 3 4 5 6 7 8 9 10 it could be spli...
python: quickest way to split a file into two files randomly
python: what is the quickest way to split a file into two files, each file having half of the number of lines in the original file, such that the lines in each of the two files are random? for example: if the file is 1 2 3 4 5 6 7 8 9 10 it could be split into: 3 2 10 9 1 4 6 8 5 7
[ "This sort of operation is often called \"partition\". Although there isn't a built-in partition function, I found this article: Partition in Python.\nGiven that definition, you can do this:\nimport random\n\ndef partition(l, pred):\n yes, no = [], []\n for e in l:\n if pred(e):\n yes.append...
[ 5, 5, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003895482_python.txt
Q: using subprocess.popen in python with os.tmp file while passing in optional parameters I am writing a python program in linux and in part of it running the pdftotext executable to convert a pdf text. The code I am currently using is given below. pdfData = currentPDF.read() tf = os.tmpfile() tf.write(pdfData) tf.s...
using subprocess.popen in python with os.tmp file while passing in optional parameters
I am writing a python program in linux and in part of it running the pdftotext executable to convert a pdf text. The code I am currently using is given below. pdfData = currentPDF.read() tf = os.tmpfile() tf.write(pdfData) tf.seek(0) out, err = subprocess.Popen(["pdftotext", "-", "-"], stdin = tf, stdout=subprocess.P...
[ "This works for me:\nout, err = subprocess.Popen(\n [\"pdftotext\", '-layout', \"-\", \"-\"], stdin = tf, stdout=subprocess.PIPE ).communicate()\n\nAlthough I couldn't find explicit confirmation in the man page, I believe the first - tells pdftotext to expect PDF-file to come from stdin, and the second - tells p...
[ 2, 0 ]
[]
[]
[ "linux", "pdftotext", "python" ]
stackoverflow_0003896795_linux_pdftotext_python.txt
Q: Finding rendered HTML element positions using WebKit (or Gecko) I would like to get the dimensions (coordinates) for all the HTML elements of a webpage as they are rendered by a browser, that is the positions they are rendered at. For example, (top-left,top-right,bottom-left,bottom-right) Could not find this in lx...
Finding rendered HTML element positions using WebKit (or Gecko)
I would like to get the dimensions (coordinates) for all the HTML elements of a webpage as they are rendered by a browser, that is the positions they are rendered at. For example, (top-left,top-right,bottom-left,bottom-right) Could not find this in lxml. So, is there any library in Python that does this? I had also loo...
[ "lxml isn't going to help you at all. It isn't concerned about front-end rendering at all.\nTo accurately work out how something renders, you need to render it. For that you need to hook into a browser, spawn the page and run some JS on the page to find the DOM element and get its attributes.\nIt's totally possible...
[ 3, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "html", "perl", "python", "rendering", "rendering_engine" ]
stackoverflow_0000980058_html_perl_python_rendering_rendering_engine.txt
Q: How can I programmatically send events to Qt's webkit? I would like to create a specialized browser that can enter certain information semi-automatically into pages that are browsed. I am using for this Qt Webkit (in particular the python bindings). How can I do this? A: it's doable, using javascript code-snippe...
How can I programmatically send events to Qt's webkit?
I would like to create a specialized browser that can enter certain information semi-automatically into pages that are browsed. I am using for this Qt Webkit (in particular the python bindings). How can I do this?
[ "it's doable, using javascript code-snippets. take a look at the pyjamas-desktop \"failed experiment\" pyjd/pyqt4.py runtime, noting the rather important addition of the words \"failed\".\nyou would be strongly advised to avoid pywebkitqt4 for this particular purpose, instead looking at either python-hulahop (orig...
[ 0 ]
[]
[]
[ "browser", "pyqt4", "python", "qt4", "webbrowser_control" ]
stackoverflow_0003372841_browser_pyqt4_python_qt4_webbrowser_control.txt
Q: Dictionaries in Python I have a problem. I want to make a dictionary that translates english words to estonian. I started, but don't know how to continue. Please, help. Dictionary is a text document where tab separates english and estonian words. file = open("dictionary.txt","r") eng = [] est = [] while True : ...
Dictionaries in Python
I have a problem. I want to make a dictionary that translates english words to estonian. I started, but don't know how to continue. Please, help. Dictionary is a text document where tab separates english and estonian words. file = open("dictionary.txt","r") eng = [] est = [] while True : lines = file.readline() ...
[ "For a dictionary, you should use the dictionary type which maps keys to values and is much more efficient for lookups. I also made some other changes to your code, keep them if you wish:\nengToEstDict = {}\n\n# The with statement automatically closes the file afterwards. Furthermore, one shouldn't\n# overwrite bui...
[ 3, 1 ]
[]
[]
[ "dictionary", "iteration", "python" ]
stackoverflow_0003897460_dictionary_iteration_python.txt
Q: How to change file names using regular expressions in Python? I have a directory which contains subdirectories which contain files. All the file names have a prefix which I want to eliminate. The prefix is not exactly the same among all the files, but I have a regular expression that represents exactly the languag...
How to change file names using regular expressions in Python?
I have a directory which contains subdirectories which contain files. All the file names have a prefix which I want to eliminate. The prefix is not exactly the same among all the files, but I have a regular expression that represents exactly the language of these prefixes. I'm trying to write a script in Python to chan...
[ "You might find these functions useful:\n\nos.listdir\nos.path.join\nos.rename\n\nYou might want to look at using glob.glob if the prefixes you are trying to match are supported by the language glob uses (it doesn't support full regular expressions, but it does allow some wildcards).\n" ]
[ 4 ]
[]
[]
[ "file", "python", "regex" ]
stackoverflow_0003897654_file_python_regex.txt
Q: Which language to use for writing an admin console à la webmin? We have an in house developed web-based admin console that uses a combination of C CGI and Perl scripts to administer our mail server stack. Of late we have been thinking of cleaning up the code (well, replacing most of it), making the implementation ...
Which language to use for writing an admin console à la webmin?
We have an in house developed web-based admin console that uses a combination of C CGI and Perl scripts to administer our mail server stack. Of late we have been thinking of cleaning up the code (well, replacing most of it), making the implementation more secure, and improving the overall behavior. I don't have much pr...
[ "Have you considered writing your applications as Webmin modules?\nYou get a lot of stuff for free when you do so (users and groups, tons of security features, a pretty big variety of helper functions related to config files, and tons of existing code for most aspects of a UNIX/Linux system). You also get a lot of ...
[ 2, 0, 0, 0 ]
[]
[]
[ "administration", "migration", "python", "ruby" ]
stackoverflow_0003861102_administration_migration_python_ruby.txt
Q: Start simple web server and launch browser simultaneously in Python I want to start a simple web server locally, then launch a browser with an url just served. This is something that I'd like to write, from wsgiref.simple_server import make_server import webbrowser srv = make_server(...) srv.blocking = False srv....
Start simple web server and launch browser simultaneously in Python
I want to start a simple web server locally, then launch a browser with an url just served. This is something that I'd like to write, from wsgiref.simple_server import make_server import webbrowser srv = make_server(...) srv.blocking = False srv.serve_forever() webbrowser.open_new_tab(...) try: srv.blocking = True e...
[ "You either have to spawn a thread with the server, so you can continue with your control flow, or you have to use 2 python processes.\nuntested code, you should get the idea\n\nclass ServerThread(threading.Thread):\n\n def __init__(self, port):\n threading.Thread.__init__(self)\n\n def run(self):\n ...
[ 1 ]
[]
[]
[ "nonblocking", "python", "webserver", "wsgiref" ]
stackoverflow_0003897896_nonblocking_python_webserver_wsgiref.txt
Q: Python: how can i find minimum and maximum values in subarrays elements? I've the following array: [[499, 3], [502, 3], [502, 353], [499, 353]] They are the verteces of a rectangle. I need to find the top-left, top-right, bottom-left and bottom-right vertex. What's the best python code to do it ? thanks A: edit...
Python: how can i find minimum and maximum values in subarrays elements?
I've the following array: [[499, 3], [502, 3], [502, 353], [499, 353]] They are the verteces of a rectangle. I need to find the top-left, top-right, bottom-left and bottom-right vertex. What's the best python code to do it ? thanks
[ "edit: thanks to tokand for pointing out that this can be done with tuple unpacking.\nyou could sort it.\n(bottomleft, bottomright,topleft, topright) = sorted(vertices)\n\nor you could do it in place with\ncorners.sort()\n(bottomleft, bottomright,topleft, topright) = corners\n# the unpacking here is redundant but d...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003897938_python.txt
Q: Can I use Python to run html i am writing an HTML editor and would like to make a section so that you can view how it would look in web browser directly in the program is this possible? Thanks so much A: I wouldn't do this - your renderer will quickly differ from real browsers.
Can I use Python to run html
i am writing an HTML editor and would like to make a section so that you can view how it would look in web browser directly in the program is this possible? Thanks so much
[ "I wouldn't do this - your renderer will quickly differ from real browsers.\n" ]
[ 2 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003897932_html_python.txt
Q: Is there way to turn list of answers from script as yielded values? I have long running program that I want to keep responsive. The algorithm is recursive, so sometimes even the sub-tasks in longer running calls can be longer than shorter whole runs. I have tried to make it to use yield but only ended up with list...
Is there way to turn list of answers from script as yielded values?
I have long running program that I want to keep responsive. The algorithm is recursive, so sometimes even the sub-tasks in longer running calls can be longer than shorter whole runs. I have tried to make it to use yield but only ended up with list full of generators in various levels of recursive list structure (list a...
[ "You're a little bit short on details of what you're actually trying to do, but here's my best guess (note: you'll need Python 2.6):\ndef do_stuff(num):\n children = [ _do_stuff(x + 1) for x in range(num) ]\n for child in children:\n child.send(None)\n\n count = 0\n while children:\n child...
[ 1, 0 ]
[]
[]
[ "generator", "python", "recursion", "yield" ]
stackoverflow_0003897712_generator_python_recursion_yield.txt
Q: How would I save time with or statements in Python? I'm writing a AI program in Python and want to save time when interacting with the bot. Instead of using this code: if "how are you" or "How are you" in talk: perform_action() I want to be able to interpret it even if it's not capitalize or not. If you don'...
How would I save time with or statements in Python?
I'm writing a AI program in Python and want to save time when interacting with the bot. Instead of using this code: if "how are you" or "How are you" in talk: perform_action() I want to be able to interpret it even if it's not capitalize or not. If you don't what I'm saying let's say I asked the bot, "how are you...
[ "if talk.upper() == \"HOW ARE YOU\":\n perform_action()\n\nor, if you prefer to search for substrings\nif \"HOW ARE YOU\" in talk.upper():\n perform_action()\n\n", "Easy way would be to lowercase everything:\nif \"how are you\" == talk.lower():\n\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003898010_python.txt
Q: How to get setuptools to use a relative path in easy-install.pth when doing "setup.py develop" I'm installing a python egg using setuptools with the "python setup.py develop" command. It's important that all install paths be relative. I see that I can do: python setup.py develop --egg-path ../../../../my_directo...
How to get setuptools to use a relative path in easy-install.pth when doing "setup.py develop"
I'm installing a python egg using setuptools with the "python setup.py develop" command. It's important that all install paths be relative. I see that I can do: python setup.py develop --egg-path ../../../../my_directory and the .egg-link file uses that relative path. However, the path added to easy-install.pth sti...
[ "If your sourcecode is in a subdirectory of the installation directory, it will be made relative automatically.\nWhy do you need it to be relative, anyway?\n" ]
[ 0 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0003886667_python_setuptools.txt
Q: Python: how can I get rid of the second element of each sublist? I have a list of sublists, such as: [[501, 4], [501, 4], [501, 4], [501, 4]] How can I get rid of the second element for each sublist ? (i.e. 4) [501, 501, 501, 501] Should I iterate the list or is there a faster way ? thanks A: You can use a list ...
Python: how can I get rid of the second element of each sublist?
I have a list of sublists, such as: [[501, 4], [501, 4], [501, 4], [501, 4]] How can I get rid of the second element for each sublist ? (i.e. 4) [501, 501, 501, 501] Should I iterate the list or is there a faster way ? thanks
[ "You can use a list comprehension to take the first element of each sublist:\nxs = [[501, 4], [501, 4], [501, 4], [501, 4]]\n[x[0] for x in xs]\n# [501, 501, 501, 501]\n\n", "a = [[501, 4], [501, 4], [501, 4], [501, 4]]\nb = [c[0] for c in a]\n\n", "A less pythonic, functional version using map:\na = [[501, 4],...
[ 7, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003898065_python.txt
Q: Simple interpreter to embed and extend inside an C++ Windows application I need a simple interpreter which will do execution (evaluation) of simple expressions/statements and also call functions from main C++ applications. At the moment I do not need scripting of the application, but it may be useful later. It sho...
Simple interpreter to embed and extend inside an C++ Windows application
I need a simple interpreter which will do execution (evaluation) of simple expressions/statements and also call functions from main C++ applications. At the moment I do not need scripting of the application, but it may be useful later. It should also be strait-forward for other team members to pull my application from ...
[ "Two great options you've already listed are Python and Lua. Here are some of the tradeoffs for your consideration:\nPython\n\nA much more complete and powerful language (IMHO!) with libraries for anything and tons of support and communities everywhere you look.\nSyntax is not entirely C-like\nAlthough Python wasn'...
[ 4, 3, 2, 1 ]
[]
[]
[ "c++", "lua", "python", "scripting" ]
stackoverflow_0003896313_c++_lua_python_scripting.txt
Q: South's syncdb/migrate creates pages of output? I'm working a small, personal Django project and I've added South (latest mercurial as of 10/9/10) to my project. However, whenever I run "./manage.py syncdb" or "./manage.py migrate " I get about 13 pages (40 lines each) of output solely regarding 'initial_data' fil...
South's syncdb/migrate creates pages of output?
I'm working a small, personal Django project and I've added South (latest mercurial as of 10/9/10) to my project. However, whenever I run "./manage.py syncdb" or "./manage.py migrate " I get about 13 pages (40 lines each) of output solely regarding 'initial_data' files not being found. I don't have any initial_data nor...
[ "How is Your logging configured?\nI have turned much of the output by configuring logging to higher level, as in:\n[formatters]\nkeys=simple\n\n[handlers]\nkeys=console\n\n[loggers]\nkeys=root,south\n\n[formatter_simple]\nformat=%(asctime)s %(levelname)7s %(message)s\ndatefmt=%Y-%m-%d %H:%M:%S\n\n[handler_console]\...
[ 2 ]
[]
[]
[ "django", "django_south", "python" ]
stackoverflow_0003898239_django_django_south_python.txt
Q: Calculating the remaining time to a repeating event in Python The scenario is as follows: given a totally arbitrary starting date in UTC there is an event that repeats every 24 hours. I need to calculate, given the current local time, how much time is left before the next event. Ideally an ideal function would do:...
Calculating the remaining time to a repeating event in Python
The scenario is as follows: given a totally arbitrary starting date in UTC there is an event that repeats every 24 hours. I need to calculate, given the current local time, how much time is left before the next event. Ideally an ideal function would do: time_since_start = now - start_time remaining_seconds = time_remai...
[ "What you want is start_time - now + (one day)\n" ]
[ 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0003898397_datetime_python.txt
Q: Ordering a django model on many-to-may field. Denormalization required? I have a system for composing items from parts in certain categories For instance take the following categories: 1: (Location) 2: (Material) And the following parts: Wall (FK=1) Roof (FK=1) Roof (FK=1) Brick (FK=2) Tile (FK=2) Wood (FK=2) ...
Ordering a django model on many-to-may field. Denormalization required?
I have a system for composing items from parts in certain categories For instance take the following categories: 1: (Location) 2: (Material) And the following parts: Wall (FK=1) Roof (FK=1) Roof (FK=1) Brick (FK=2) Tile (FK=2) Wood (FK=2) To compose these items: Wall.Brick, Roof.Wood, Wall.Wood class Category(mode...
[ "If I understand correctly, sort key do not exist in database, so database cannot sort it (or at least on trivially, like using Django ORM).\nUnder those conditions, yes - denormalize.\nIt's no shame. As said, normalized dataset is for sissies...\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003896310_django_python.txt
Q: Import from a Django project with a different top-level folder name I recently setup a deployment solution for my Django project using Fabric. The basic workflow being: Check out the latest source from git on the server. Copy it to a 'releases' directory and add a timestamp to the directory name. Update the 'curr...
Import from a Django project with a different top-level folder name
I recently setup a deployment solution for my Django project using Fabric. The basic workflow being: Check out the latest source from git on the server. Copy it to a 'releases' directory and add a timestamp to the directory name. Update the 'current' symlink to point to the latest build. This works just fine, only pr...
[ "Simply put, you really shouldn't be using your project name hard-coded anywhere, especially in specific apps, as it just completely breaks their portability and re-usability.\n", "It seems that You have manage.py, urls.py and friends directly in the root of Your repository.\nThis is not right: on top-level, ther...
[ 4, 0 ]
[]
[]
[ "django", "fabric", "importerror", "python" ]
stackoverflow_0003864615_django_fabric_importerror_python.txt
Q: python thread queue question Hell All. i was made some python script with thread which checking some of account exist in some website if i run thread 1 , it working well but if increase thread such like 3~5 and above, result was very different compare with thread 1 and i was checked manually and if i increase th...
python thread queue question
Hell All. i was made some python script with thread which checking some of account exist in some website if i run thread 1 , it working well but if increase thread such like 3~5 and above, result was very different compare with thread 1 and i was checked manually and if i increase thread result was not correct. i thi...
[ "Can You please specify what are different results?\nFrom what I see, code is doing much more than verifying account.\nFrom what I see, You're appending to a single file from multiple threads, I'd say it's not thread-safe.\nAlso, AFAIK Mechanize uses shared cookie storage for all requests, so they are probably inte...
[ 0 ]
[]
[]
[ "multithreading", "python", "queue" ]
stackoverflow_0003836565_multithreading_python_queue.txt
Q: django.contrib.admin like application for cherrypy Is there a django.contrib.admin like app / module for cherrypy? I really like the simplicity of cherrypy, but it would be nice, to have the user authentication and password management type things taken care of... Or is it possible to run a cherrypy application b...
django.contrib.admin like application for cherrypy
Is there a django.contrib.admin like app / module for cherrypy? I really like the simplicity of cherrypy, but it would be nice, to have the user authentication and password management type things taken care of... Or is it possible to run a cherrypy application behind the django admin app ?
[ "Django admin is much more, but is bound to Models. Without them, You will not gain much and as there is no such concept in CherryPy, I doubt there is similar application.\nHowever, Django admin is phpmyadmin for masses exploited. Don't be constrained by it and create much more usable admin apps, leveraging CherryP...
[ 3, 2 ]
[]
[]
[ "cherrypy", "django", "python" ]
stackoverflow_0003861027_cherrypy_django_python.txt
Q: Is it time to cut over to Python 3.x now or not? Is 2.x still the norm or would you recommend just coding in v3 at this point? A: Python 3 is still a long way off having universal support from tools, libraries and distros, so its use in production would depend very much on whether the bits you need (or are likel...
Is it time to cut over to Python 3.x now or not?
Is 2.x still the norm or would you recommend just coding in v3 at this point?
[ "Python 3 is still a long way off having universal support from tools, libraries and distros, so its use in production would depend very much on whether the bits you need (or are likely to need in the near future) have been ported.\nFor exploratory, educational and other uses, it depends very much on your own procl...
[ 3, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003898411_python.txt
Q: How to do cloud computing with Python and Java? Final Year project For my final year project I plan to code a cloud in Python. The client will be written in Java by the other member of my team. The client will have a tabbed interface and it will provide a text editor, a media player, a couple of small Java based g...
How to do cloud computing with Python and Java? Final Year project
For my final year project I plan to code a cloud in Python. The client will be written in Java by the other member of my team. The client will have a tabbed interface and it will provide a text editor, a media player, a couple of small Java based games and a maybe a few more services. The server will work like this: ...
[ "Q1: how should I transfer data between client/server securely\nA: HTTPS to support encryption & JSON to serialise objects between languages (Python/Java) seems to be the most natural. You could experiment with XML-RPC over SSL or TSL if you want to be creative.\nQ2: How do I send queries to the server's db?\nA: My...
[ 1, 0, 0 ]
[]
[]
[ "cloud", "django", "python" ]
stackoverflow_0003896741_cloud_django_python.txt
Q: Python, Webkit: how to get the DOM after the page has loaded? In my code I've connected to the WebView's load-finished event. The particular callback function takes a webview object and frame object as arguments. Then I tried executing get_dom_document() on the frame & the webview objects respectively. It seems th...
Python, Webkit: how to get the DOM after the page has loaded?
In my code I've connected to the WebView's load-finished event. The particular callback function takes a webview object and frame object as arguments. Then I tried executing get_dom_document() on the frame & the webview objects respectively. It seems this method doesn't exist for those objects... PS: i started with the...
[ "it's definitely there.\nand you can't just \"take the tips from http://www.gnu.org/software/pythonwebkit/\" you actually have to COMPILE THE CODE (reason: standard pywebkitgtk DOES NOT have W3C DOM accessor functions).\nthen take a look in pythonwebkit/pywebkitgtk/examples and run browser.py and you'll see what t...
[ 2, 0 ]
[]
[]
[ "gtk", "pygtk", "python", "webkit" ]
stackoverflow_0003893577_gtk_pygtk_python_webkit.txt
Q: Django/Celery can't find importlib So I just updated django to 1.2.3 and now when I try to run 'python manage.py shell' to work in the django environment, I'm getting the following error. Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/opt/local/Lib...
Django/Celery can't find importlib
So I just updated django to 1.2.3 and now when I try to run 'python manage.py shell' to work in the django environment, I'm getting the following error. Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/opt/local/Library/Frameworks/Python.framework/Versio...
[ "importlib which was added in Python 2.7/3.1, I believe. You can download a port for pyton 2.5 here:\n\nimportlib 1.0.1 - Backport of importlib.import_module() from Python 2.7\n\nAlso check the setup.cfg for celery near the bottom and make sure all the other requirements are met (toward the bottom of the script).\...
[ 8, 1 ]
[]
[]
[ "celery", "django", "python" ]
stackoverflow_0003897436_celery_django_python.txt
Q: Is using multiple Timers in Python dangerous? I am working on a text-based game in Python 3.1 that would use timing as it's major source of game play. In order to do this effectively (rather than check the time every mainloop, my current method, which can be inaccurate, and slow if multiple people are playing the ...
Is using multiple Timers in Python dangerous?
I am working on a text-based game in Python 3.1 that would use timing as it's major source of game play. In order to do this effectively (rather than check the time every mainloop, my current method, which can be inaccurate, and slow if multiple people are playing the game at once) I was thinking about using the Thread...
[ "I think its a bad idea to use Timers in your case.\nUsing the delayed threads in python will result in more complex code, less accuracy, and quite possible worse performance. Basically, the rule is that if you think you need threads, you don't. Very few programs benefit from the use of threads.\nI don't know what ...
[ 3, 1 ]
[]
[]
[ "python", "timer" ]
stackoverflow_0003898740_python_timer.txt
Q: Python audio library for simultaneous audio creation and playback I'm working on an audio creation framework. It'll be generating large audio files, say 3 minute long audio files that take about 1 minute to generate. So what I want is a system much like streaming audio from the internet, where I play the sound as ...
Python audio library for simultaneous audio creation and playback
I'm working on an audio creation framework. It'll be generating large audio files, say 3 minute long audio files that take about 1 minute to generate. So what I want is a system much like streaming audio from the internet, where I play the sound as I generate it. Pygame's mixer allows me to edit the sound as it's playi...
[ "pymedia.audio does work with Python 2.6. Take a look at this SO post: Pymedia installation on Windows with Python 2.6\nYou can append audio to Output objects, as they are playing. So as each sample is generated, it can also be appended to the stream. The example in their documentation shows just how to do this: ht...
[ 0 ]
[]
[]
[ "audio", "audio_player", "c++", "python" ]
stackoverflow_0003895757_audio_audio_player_c++_python.txt
Q: what's wrong with the way I am splitting a string in python? I looked in my book and in the documentation, and did this: a = "hello" b = a.split(sep= ' ') print(b) I get an error saying split() takes no keyword arguments. What is wrong? I want to have ['h','e','l','l','o'] I tried not passing sep and just a.split...
what's wrong with the way I am splitting a string in python?
I looked in my book and in the documentation, and did this: a = "hello" b = a.split(sep= ' ') print(b) I get an error saying split() takes no keyword arguments. What is wrong? I want to have ['h','e','l','l','o'] I tried not passing sep and just a.split(' '), and got ['hello']
[ "Python allows a concept called \"keyword arguments\", where you tell it which parameter you're passing in the call to the function. However, the standard split() function does not take this kind of parameter.\nTo split a string into a list of characters, use list():\n>>> a = \"hello\"\n>>> list(a)\n['h', 'e', 'l',...
[ 6, 4, 2, 0 ]
[]
[]
[ "python", "split" ]
stackoverflow_0003898882_python_split.txt
Q: What is this cProfile result telling me I need to fix? I would like to improve the performance of a Python script and have been using cProfile to generate a performance report: python -m cProfile -o chrX.prof ./bgchr.py ...args... I opened this chrX.prof file with Python's pstats and printed out the statistics: P...
What is this cProfile result telling me I need to fix?
I would like to improve the performance of a Python script and have been using cProfile to generate a performance report: python -m cProfile -o chrX.prof ./bgchr.py ...args... I opened this chrX.prof file with Python's pstats and printed out the statistics: Python 2.7 (r27:82500, Oct 5 2010, 00:24:22) [GCC 4.1.2 200...
[ "ncalls is relevant only to the extent that comparing the numbers against other counts such as number of chars/fields/lines in a file may highligh anomalies; tottime and cumtime is what really matters. cumtime is the time spent in the function/method including the time spent in the functions/methods that it calls; ...
[ 29, 2 ]
[ "The entries relevant for possible optimization are those with high values for ncalls and tottime. bgchr:4(<module>) and <string>:1(<module>) probably refer to the execution of your module body and are not relevant here.\nObviously, your performance problem comes from string processing. This should perhaps be reduc...
[ -1 ]
[ "cprofile", "performance", "profile", "profiling", "python" ]
stackoverflow_0003898266_cprofile_performance_profile_profiling_python.txt
Q: How do I actually use WSGI? Suppose I have a function def app2(environ, start_response) If I know that a server implements WSGI, how can I tell the server to call app2 when it receives a HTTP request? app2 here is a function that takes a dictionary and returns a response (a WSGI application). A: Depends on th...
How do I actually use WSGI?
Suppose I have a function def app2(environ, start_response) If I know that a server implements WSGI, how can I tell the server to call app2 when it receives a HTTP request? app2 here is a function that takes a dictionary and returns a response (a WSGI application).
[ "Depends on the server. The WSGI-Spec says nothing about that. But mod_wsgi for example expects to find the WSGI-Applications under the name application in the specified module, but you can configure that with the WSGICallableObject configuration directive.\n", "If, as it sounds from your comment, your question i...
[ 0, 0 ]
[]
[]
[ "http", "python", "wsgi" ]
stackoverflow_0003898229_http_python_wsgi.txt
Q: Google App Engine Example Modified I took an official example of Google App Engine, that creates a Shoppinglist, and modified it so it would: Create two tables (contact and Phonenumber) instead of one Shoppinglist. This is to understand how google deals with two tables and the Foreignkey (see code below). It displ...
Google App Engine Example Modified
I took an official example of Google App Engine, that creates a Shoppinglist, and modified it so it would: Create two tables (contact and Phonenumber) instead of one Shoppinglist. This is to understand how google deals with two tables and the Foreignkey (see code below). It displays everything until line 47: data = Pho...
[ "I haven't used Django forms, but my guess would be something like this:\ndef post(self): \n #print self.request \n #print self.request.POST \n data = PhoneNumberForm(data=self.request.POST) \n data2 = ContactForm(data=self.request.POST) \n if data.is_valid() and data2.is_valid(): \n # Save th...
[ 1, 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003656357_google_app_engine_python.txt
Q: How to accelerate reads from batches of files I read many files from my system. I want to read them faster, maybe like this: results=[] for file in open("filenames.txt").readlines(): results.append(open(file,"r").read()) I don't want to use threading. Any advice is appreciated. the reason why i don't want to ...
How to accelerate reads from batches of files
I read many files from my system. I want to read them faster, maybe like this: results=[] for file in open("filenames.txt").readlines(): results.append(open(file,"r").read()) I don't want to use threading. Any advice is appreciated. the reason why i don't want to use threads is because it will make my code unreada...
[ "results = [open(f.strip()).read() for f in open(\"filenames.txt\").readlines()]\n\nThis may be insignificantly faster, but it's probably less readable (depending on the reader's familiarity with list comprehensions).\nYour main problem here is that your bottleneck is disk IO - buying a faster disk will make much m...
[ 1, 0, 0, 0 ]
[]
[]
[ "concurrency", "file", "io", "performance", "python" ]
stackoverflow_0003869357_concurrency_file_io_performance_python.txt
Q: How do I set the timeout of a SocketServer in Python? I want to use server.get_request() to receive requests, but I want it to timeout after 500 milliseconds. Is this correct? Doesn't seem to work... thanks. class UDPServer(SocketServer.BaseRequestHandler): timeout = .500 if __name__ == "__main__": server...
How do I set the timeout of a SocketServer in Python?
I want to use server.get_request() to receive requests, but I want it to timeout after 500 milliseconds. Is this correct? Doesn't seem to work... thanks. class UDPServer(SocketServer.BaseRequestHandler): timeout = .500 if __name__ == "__main__": server = SocketServer.UDPServer(('localhost', '12345'), UDPServer...
[ "I feel there are some places wrong:\n\nThe class derived from SocketServer.BaseRequestHandler should be MyUDPServerHandler or something else, but should not be UDPServer which is a built-in class in SocketServer\nIt should be server = SocketServer.UDPServer(('localhost', '12345'), MyUDPServerhandler)\nThen maybe i...
[ 3 ]
[]
[]
[ "python", "sockets", "udp" ]
stackoverflow_0003899200_python_sockets_udp.txt
Q: Does python's fcntl.flock function provide thread level locking of file access? Python's fcnt module provides a method called [flock][1] to proved file locking. It's description reads: Perform the lock operation op on file descriptor fd (file objects providing a fileno() method are accepted as well). See th...
Does python's fcntl.flock function provide thread level locking of file access?
Python's fcnt module provides a method called [flock][1] to proved file locking. It's description reads: Perform the lock operation op on file descriptor fd (file objects providing a fileno() method are accepted as well). See the Unix manual flock(2) for details. (On some systems, this function is emulated u...
[ "flock locks don't care about threads--in fact, they don't care about processes, either. If you take the same file descriptor in two processes (inherited through a fork), either process locking the file with that FD will acquire a lock for both processes. In other words, in the following code both flock calls wil...
[ 5 ]
[]
[]
[ "flock", "linux", "locking", "multithreading", "python" ]
stackoverflow_0003899435_flock_linux_locking_multithreading_python.txt
Q: Finding length of items from a list I have two list in a python list1=['12aa','2a','c2'] list2=['2ac','c2a','1ac'] First- Finding combinations of each two item from list1. Second- Finding combinations of each two item from list2. Third- Finding combinations of each two items from list1 and list2 Fourth- Calculat...
Finding length of items from a list
I have two list in a python list1=['12aa','2a','c2'] list2=['2ac','c2a','1ac'] First- Finding combinations of each two item from list1. Second- Finding combinations of each two item from list2. Third- Finding combinations of each two items from list1 and list2 Fourth- Calculating each combinations total length Advice...
[ "import itertools as it\n\nlist1=['12aa','2a','c2']\nlist2=['2ac','c2a','1ac']\n\n# First- Finding combinations of each two item from list1.\nfirst = list(it.combinations(list1, 2))\n\n# Second- Finding combinations of each two item from list2.\nsecond = list(it.combinations(list2, 2))\n\n# Third- Finding combinati...
[ 3 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0003899593_arrays_python.txt
Q: Convert SHA Hash Computation in Python to C# Can someone please help me convert the following two lines of python to C#. hash = hmac.new(secret, data, digestmod = hashlib.sha1) key = hash.hexdigest()[:8] The rest looks like this if you're intersted: #!/usr/bin/env python import hmac import hashlib secret = 'myS...
Convert SHA Hash Computation in Python to C#
Can someone please help me convert the following two lines of python to C#. hash = hmac.new(secret, data, digestmod = hashlib.sha1) key = hash.hexdigest()[:8] The rest looks like this if you're intersted: #!/usr/bin/env python import hmac import hashlib secret = 'mySecret' data = 'myData' hash = hmac.new(secr...
[ "You could use the HMACSHA1 class to compute the hash:\nclass Program\n{\n static void Main()\n {\n var secret = \"secret\";\n var data = \"data\";\n var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secret));\n var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(data));\n Conso...
[ 7 ]
[]
[]
[ "c#", "hash", "python", "sha1" ]
stackoverflow_0003899644_c#_hash_python_sha1.txt
Q: How google docs shows my .PPT files without using a flash viewer? I want to show .ppt (PowerPoint) files uploaded by my user on my website. I could do this by converting them into Flash files, then showing the Flash files on the web page. But I don't want to use Flash to do this. I want to show it, like google doc...
How google docs shows my .PPT files without using a flash viewer?
I want to show .ppt (PowerPoint) files uploaded by my user on my website. I could do this by converting them into Flash files, then showing the Flash files on the web page. But I don't want to use Flash to do this. I want to show it, like google docs shows, without using Flash. I've already solved the problem for .pdf ...
[ "I would maybe try using google docs API to first upload a ppt presentation and then download it back in a different format. I think it should be possible though I have not tested it. \n", "You can embed Google docs presentations in your site.\n", "Now i found a solution to showing .ppt file on my website witho...
[ 1, 1, 0 ]
[]
[]
[ "c++", "google_docs", "java", "powerpoint", "python" ]
stackoverflow_0003882249_c++_google_docs_java_powerpoint_python.txt
Q: Emulate javascript _dopostback in python, web scraping Here LINK it is suggested that it is possible to "Figure out what the JavaScript is doing and emulate it in your Python code: " This is what I would like help doing ie my question. How do I emulate javascript:__doPostBack ? Code from a website (full page sourc...
Emulate javascript _dopostback in python, web scraping
Here LINK it is suggested that it is possible to "Figure out what the JavaScript is doing and emulate it in your Python code: " This is what I would like help doing ie my question. How do I emulate javascript:__doPostBack ? Code from a website (full page source here LINK: <a style="color: Black;" href="javascript:__doP...
[ "The mechanize page is not suggesting that you can emulate JavaScript in Python. It is saying that you can change a hidden field in a form, thus tricking the web server that a human1 has selected the field. You still need to analyse the target yourself. \nThere will be no Python-based solution to this problem, unle...
[ 3 ]
[]
[]
[ "dopostback", "javascript", "mechanize", "python", "web_scraping" ]
stackoverflow_0003898660_dopostback_javascript_mechanize_python_web_scraping.txt
Q: How to save and load QListWidjet contents to/from QSetting with PyQt4? I've got a QListWidget in my PyQt4 app. It contains folders paths. I want to save its contents to QSettings and load them later. I used this code to do this: def foldersSave(self): folders = {} '''create dict to store data''' foldersnum...
How to save and load QListWidjet contents to/from QSetting with PyQt4?
I've got a QListWidget in my PyQt4 app. It contains folders paths. I want to save its contents to QSettings and load them later. I used this code to do this: def foldersSave(self): folders = {} '''create dict to store data''' foldersnum = self.configDialog.FolderLIST.count() '''get number of items''' if fol...
[ "The solution is very simply. I were to use QStringList.\ndef foldersSave(self):\n folders = QtCore.QStringList()\n foldersnum = self.configDialog.FolderLIST.count()\n if foldersnum:\n for i in range(foldersnum):\n print (i, \" position is saved: \", self.configDialog.FolderLIST.item(i).t...
[ 0 ]
[]
[]
[ "pyqt4", "python", "qlistwidget", "qt4" ]
stackoverflow_0003870081_pyqt4_python_qlistwidget_qt4.txt
Q: How do I close a Python 2.5.2 Popen subprocess once I have the data I need? I am running the following version of Python: $ /usr/bin/env python --version Pytho...
How do I close a Python 2.5.2 Popen subprocess once I have the data I need?
I am running the following version of Python: $ /usr/bin/env python --version Python 2.5.2 I am running the following Python co...
[ "Hmmm. I've seen some \"Broken pipe\" strangeness with subprocess + gzip before. I never did figure out exactly why it was happening but by changing my implementation approach, I was able to avoid the problem. It looks like you're just trying to use a backend gzip process to decompress a file (probably because Pyth...
[ 4, 1, 0, 0 ]
[]
[]
[ "pipe", "popen", "python" ]
stackoverflow_0003861087_pipe_popen_python.txt
Q: How o Delete ALL Pages of agw.aui.notebook in One shot? I have a auiNotebook built from agw library. Now i have added few pages Now i have to delete ALL pages at one shot. Please let me know how to do this. Or is there any method which gives me List of Page Indexs for All Added Pages so that i can use Delete Page ...
How o Delete ALL Pages of agw.aui.notebook in One shot?
I have a auiNotebook built from agw library. Now i have added few pages Now i have to delete ALL pages at one shot. Please let me know how to do this. Or is there any method which gives me List of Page Indexs for All Added Pages so that i can use Delete Page method to delete all pages Enviroment: Windows,wxpython
[ "This works.\n while(notebook.GetPageCount()):\n notebook.DeletePage(0)\n\n" ]
[ 3 ]
[]
[]
[ "python", "wxnotebook", "wxpython" ]
stackoverflow_0003900052_python_wxnotebook_wxpython.txt
Q: Accessing a Panatone Huey via Python I have a Panatone Huey, a monitor calibration probe (device you attach to the monitor, and it gives you colour readings) - I want to get readings from the device in Python. Having never written such a device driver before, I'm not sure where to start. I've found are two open-so...
Accessing a Panatone Huey via Python
I have a Panatone Huey, a monitor calibration probe (device you attach to the monitor, and it gives you colour readings) - I want to get readings from the device in Python. Having never written such a device driver before, I'm not sure where to start. I've found are two open-source C/C++ projects that interface with th...
[ "Given the existence of spotread the easiest (though perhaps not the best) way to proceed would be to use pexpect. It allows you to interact with other command-line programs.\n" ]
[ 3 ]
[]
[]
[ "colors", "device_driver", "python", "usb" ]
stackoverflow_0003900118_colors_device_driver_python_usb.txt
Q: list.extend and list comprehension When I need to add several identical items to the list I use list.extend: a = ['a', 'b', 'c'] a.extend(['d']*3) Result ['a', 'b', 'c', 'd', 'd', 'd'] But, how to do the similar with list comprehension? a = [['a',2], ['b',2], ['c',1]] [[x[0]]*x[1] for x in a] Result [['a', 'a']...
list.extend and list comprehension
When I need to add several identical items to the list I use list.extend: a = ['a', 'b', 'c'] a.extend(['d']*3) Result ['a', 'b', 'c', 'd', 'd', 'd'] But, how to do the similar with list comprehension? a = [['a',2], ['b',2], ['c',1]] [[x[0]]*x[1] for x in a] Result [['a', 'a'], ['b', 'b'], ['c']] But I need this on...
[ "Stacked LCs.\n[y for x in a for y in [x[0]] * x[1]]\n\n", "An itertools approach:\nimport itertools\n\ndef flatten(it):\n return itertools.chain.from_iterable(it)\n\npairs = [['a',2], ['b',2], ['c',1]]\nflatten(itertools.repeat(item, times) for (item, times) in pairs)\n# ['a', 'a', 'b', 'b', 'c']\n\n", ">>>...
[ 59, 14, 6, 6, 2, 1 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0003899645_list_list_comprehension_python.txt
Q: Ignore an element while building list in python I need to build a list from a string in python using the [f(char) for char in string] syntax and I would like to be able to ignore (not insert in the list) the values of f(x) which are equal to None. How can I do that ? A: We could create a "subquery". [r for r in ...
Ignore an element while building list in python
I need to build a list from a string in python using the [f(char) for char in string] syntax and I would like to be able to ignore (not insert in the list) the values of f(x) which are equal to None. How can I do that ?
[ "We could create a \"subquery\".\n[r for r in (f(char) for char in string) if r is not None]\n\nIf you allow all False values (0, False, None, etc.) to be ignored as well, filter could be used:\nfilter(None, (f(char) for char in string) )\n# or, using itertools.imap,\nfilter(None, imap(f, string))\n\n" ]
[ 37 ]
[]
[]
[ "list", "python", "syntactic_sugar" ]
stackoverflow_0003900215_list_python_syntactic_sugar.txt
Q: How to check whether elements appears in the list only once in python? I have a list: a = [1, 2, 6, 4, 3, 5, 7] Please, explain to me how to check whether element appears only once in in the list? Please, also explain if all elements from 1 to len(a) are in the list. For instance, in list 'a' element from 1 to 7 ...
How to check whether elements appears in the list only once in python?
I have a list: a = [1, 2, 6, 4, 3, 5, 7] Please, explain to me how to check whether element appears only once in in the list? Please, also explain if all elements from 1 to len(a) are in the list. For instance, in list 'a' element from 1 to 7 are in the list, but if the list is b = [1, 4, 3, 5], then not all elements ...
[ "When I read your question, I took a different meaning from it than mark did. If you want to check if a particular element appears only once, then\ndef occurs_once(a, item):\n return a.count(item) == 1\n\nwill be true only if item occurs in the list exactly once. \nSee Pokes answer for the second question \n", ...
[ 8, 6, 5, 4, 3 ]
[]
[]
[ "iteration", "list", "python" ]
stackoverflow_0003899782_iteration_list_python.txt
Q: Lists in Python Possible Duplicate: What is the easiest way to convert list with str into list with int? =) Is it possible to transform: a = ['1', '2', '3', '4'] to a = [1, 2, 3, 4] Thank You! A: You could use map to apply a function to each element of a list, and a get the resulting list (Python 2.x) / ite...
Lists in Python
Possible Duplicate: What is the easiest way to convert list with str into list with int? =) Is it possible to transform: a = ['1', '2', '3', '4'] to a = [1, 2, 3, 4] Thank You!
[ "You could use map to apply a function to each element of a list, and a get the resulting list (Python 2.x) / iterable (Python 3.x) back.\nmap(int, a)\n\nIt could be done with list comprehension too.\n[int(x) for x in a]\n\n", "Another way:\nresult = [int(x) for x in a]\n\nThis is called a list comprehension.\n" ...
[ 2, 2 ]
[]
[]
[ "list", "python", "transformation" ]
stackoverflow_0003900344_list_python_transformation.txt
Q: python: Convert tcpdump into text2pcap readable format Recently there was a requirement for me to convert the textual output of "tcpdump -i eth0 -neXXs0" into a pcap file. So I wrote a python script which converts the information into an intermediate format understandable by text2pcap. Since this is my first progr...
python: Convert tcpdump into text2pcap readable format
Recently there was a requirement for me to convert the textual output of "tcpdump -i eth0 -neXXs0" into a pcap file. So I wrote a python script which converts the information into an intermediate format understandable by text2pcap. Since this is my first program in python there would obviously be scope for improvement....
[ "Use the -w option of tcpdump to write to a pcap format file\ntcpdump -w filename.pcap\n\nWireshark should be able to read it.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003900431_python.txt
Q: access to google with python how i can access to google !! i had try that code urllib.urlopen('http://www.google.com') but it's show message prove you are human or some think like dat some people say try user agent !! i dunno ! A: You should use the Google API for accessing the search. Here's an example for pyt...
access to google with python
how i can access to google !! i had try that code urllib.urlopen('http://www.google.com') but it's show message prove you are human or some think like dat some people say try user agent !! i dunno !
[ "You should use the Google API for accessing the search. Here's an example for python. Unutbu provided a link to an older SO answer which contains a corrected version of the same example code.\n#!/usr/bin/python\nimport urllib, urllib2\nimport json\n\napi_key, userip = None, None\nquery = {'q' : 'search google pyth...
[ 10, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003900610_python.txt
Q: Writing a TCP to RS232 driver I need to expose an RS232 connection to clients via a network socket. I plan to write in python a TCP socket server which will listen on some port, allow client to connect and handle outgoing and manage and control requests and replies to from the R2232 port. My question is, how do I...
Writing a TCP to RS232 driver
I need to expose an RS232 connection to clients via a network socket. I plan to write in python a TCP socket server which will listen on some port, allow client to connect and handle outgoing and manage and control requests and replies to from the R2232 port. My question is, how do I synchronize the clients, each clie...
[ "To expand on Sjoerd's answer, building a single-thread server (e.g. http://docs.python.org/library/basehttpserver.html) that then controls the port (via something like http://pyserial.sourceforge.net/pyserial_api.html), plus a trivial URL structure, gives you a simple, RESTful way of exposing and handling the requ...
[ 2, 1 ]
[]
[]
[ "python", "serial_port", "sockets" ]
stackoverflow_0003900403_python_serial_port_sockets.txt
Q: Python - question about factory functions I have a series of classes that I'll be registering as services to a higher level abstraction class. The high-level class will have a function that gets the lower level class based on init args, etc. Does this sound berserk? Also, what is this called? I call it factory fun...
Python - question about factory functions
I have a series of classes that I'll be registering as services to a higher level abstraction class. The high-level class will have a function that gets the lower level class based on init args, etc. Does this sound berserk? Also, what is this called? I call it factory function/class, but I really have no idea (which m...
[ "It's called \"metaclass programming\". In recent versions of Python it's implemented by defining the __new__() static method and returning an object of the appropriate type.\nclass C(object):\n def __new__(cls, val):\n if val == 5:\n return 'five'\n else:\n return super(C, cls).__new__(cls)\n\nc1 ...
[ 2 ]
[]
[]
[ "factory_pattern", "python" ]
stackoverflow_0003900896_factory_pattern_python.txt
Q: Adding and removing audio sources to/from GStreamer pipeline on-the-go I wrote a little Python script which uses an Adder plugin to mix two source streams together. After starting the program, you hear a 1kHz tone generated by the audiotestsrc plugin. When you press Enter, an another 500Hz test tone is connected t...
Adding and removing audio sources to/from GStreamer pipeline on-the-go
I wrote a little Python script which uses an Adder plugin to mix two source streams together. After starting the program, you hear a 1kHz tone generated by the audiotestsrc plugin. When you press Enter, an another 500Hz test tone is connected to the Adder so you hear them together. (By the way, i don't really get why s...
[ "I've found the solution on my own. I had to use request pads with Adder and use the pad blocking capability of GStreamer.\nHere's the working source code with some descriptions:\n#!/usr/bin/python\n\nimport gobject;\ngobject.threads_init()\nimport gst;\n\nif __name__ == \"__main__\":\n # First create our pipeli...
[ 6 ]
[]
[]
[ "audio", "gstreamer", "mixing", "python" ]
stackoverflow_0003899666_audio_gstreamer_mixing_python.txt
Q: What is better in python, a Dictionary or Mysql? What would be faster ? Query mysql to see if the piece of information i need is there, OR load a python dictionary with all the information then just check if the id is there If python is faster, then whats the best what to check if the id exists? Im using python 2....
What is better in python, a Dictionary or Mysql?
What would be faster ? Query mysql to see if the piece of information i need is there, OR load a python dictionary with all the information then just check if the id is there If python is faster, then whats the best what to check if the id exists? Im using python 2.4.3 Im searching for data which is tagged to a square ...
[ "Generally speaking, if you want information from a database, ask the database for what you need. MySQL (and other database engines) are designed to retrieve data as efficiently as possible. \nTrying to write your own procedures for retrieving data is trying to outsmart the talented people who have already imbued M...
[ 5, 2, 1, 1 ]
[]
[]
[ "dictionary", "mysql", "python", "variables" ]
stackoverflow_0003900762_dictionary_mysql_python_variables.txt
Q: Edit regex in python script The following python script allows me to scrape email addresses from a given file using regular expressions. I'm trying to add phone numbers to the regular expression also. I created this regex and seems to work on 7 and 10 digit numbers: (\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\...
Edit regex in python script
The following python script allows me to scrape email addresses from a given file using regular expressions. I'm trying to add phone numbers to the regular expression also. I created this regex and seems to work on 7 and 10 digit numbers: (\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??...
[ "I would not advise combining the two regexes. It's possible, but it will make for code which is harder to understand and maintain down the road. \n(Also, leaving the regexes separate will let you handle emails and phone numbers differently down the line, which you're likely to want to do.)\n", "For one, I would ...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003901252_python_regex.txt
Q: Nested Lists in Dict : Accessing members of list within the list of a dictionary def index_dir(self, base_path): num_files_indexed = 0 allfiles = os.listdir(base_path) self._documents = os.listdir(base_path) num_files_indexed = len(allfiles) docnumber = 0 self._inverted_index = collections....
Nested Lists in Dict : Accessing members of list within the list of a dictionary
def index_dir(self, base_path): num_files_indexed = 0 allfiles = os.listdir(base_path) self._documents = os.listdir(base_path) num_files_indexed = len(allfiles) docnumber = 0 self._inverted_index = collections.defaultdict(list) docnumlist = [] for file in allfiles: self.docu...
[ ">>> from itertools import groupby\n>>> from operator import itemgetter\n>>> cat = [[1,1],[1,1],[1,1],[3,1],[3,1]]\n>>> [(k,len(list(v))) for k, v in groupby(cat,itemgetter(0))]\n[(1, 3), (3, 2)]\n\nwill fix your code. But that doesn't solve the problem of why the code is doing the wrong thing in the first place! T...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003861597_python.txt
Q: Performance comparison of immutable string concatenation between Java and Python UPDATES: thanks a lot to Gabe and Glenn for the detailed explanation. The test is wrote not for language comparison benchmark, just for my studying on VM optimization technologies. I did a simple test to understand the performance of...
Performance comparison of immutable string concatenation between Java and Python
UPDATES: thanks a lot to Gabe and Glenn for the detailed explanation. The test is wrote not for language comparison benchmark, just for my studying on VM optimization technologies. I did a simple test to understand the performance of string concatenation between Java and Python. The test is target for the default imm...
[ "@Gabe's answer is correct, but needs to be shown clearly rather than hypothesized.\nCPython (and probably only CPython) does an in-place string append when it can. There are limitations on when it can do this.\nFirst, it can't do it for interned strings. That's why you'll never see this if you test with a = \"te...
[ 6, 3, 1, 0, 0 ]
[]
[]
[ "concatenation", "java", "performance", "python", "string" ]
stackoverflow_0003901124_concatenation_java_performance_python_string.txt
Q: gnuplot syntax error when using python I am just about to find out how python and gnuplot work together. On http://wiki.aims.ac.za/mediawiki/index.php/Python:Gnuplot_module I found an introduction and I wanted to execute it on my Ubuntu machine. import Gnuplot gp = Gnuplot.Gnuplot(persist = 1) gp('set data ...
gnuplot syntax error when using python
I am just about to find out how python and gnuplot work together. On http://wiki.aims.ac.za/mediawiki/index.php/Python:Gnuplot_module I found an introduction and I wanted to execute it on my Ubuntu machine. import Gnuplot gp = Gnuplot.Gnuplot(persist = 1) gp('set data style lines') # The first data set (a qua...
[ "Did you put the bangline in the first line? i.e:\n#!/usr/bin/python\n\nLooks like it is not the Python interpreter who is executing the file.\n", "Well the python interpreter thinks that while parsing there was an syntax error.\nCheck again your quotes, make sure that for convenience sake you only use either dou...
[ 2, 0, 0, 0 ]
[ "I've been using pylab instead. Pylab homepage\nFrom debian repos:\npython-matplotlib - Python based plotting system in a style similar to Matlab.\n\n" ]
[ -1 ]
[ "gnuplot", "python" ]
stackoverflow_0001037919_gnuplot_python.txt
Q: Characters not making it from a master to a slave pseudo-terminal I am currently trying to send binary data out through pexpect. For some reason, the data gets through just find except for a 0x04, which is just skipped over. I tracked down the pexpect call to determine that all thats happening is an os.write() c...
Characters not making it from a master to a slave pseudo-terminal
I am currently trying to send binary data out through pexpect. For some reason, the data gets through just find except for a 0x04, which is just skipped over. I tracked down the pexpect call to determine that all thats happening is an os.write() call to a file descriptor opened from a pty.fork() command. Any ideas? ...
[ "0x04 is ^D, which is the end-of-file keypress. Has the pty been set in raw mode? Maybe the driver is eating it.\nIf you make it:\nos.write(child_fd, b\"'\\x04hmm\\x16\\x04'\\n\")\n\nyou can see that indeed the driver is doing translation. \\x16 is the same as ^V, which is how you quote things. It makes sense th...
[ 2 ]
[]
[]
[ "pty", "python", "unix" ]
stackoverflow_0003901658_pty_python_unix.txt
Q: Following the result of pressing a submit button in Python Mechanize So I have an authenticated site that I want to access via the mechanize module. I'm able to log in, and then go to the page I want. However, because the page recognizes that mechanize doesn't have javascript enabled, it wants me to click a submit...
Following the result of pressing a submit button in Python Mechanize
So I have an authenticated site that I want to access via the mechanize module. I'm able to log in, and then go to the page I want. However, because the page recognizes that mechanize doesn't have javascript enabled, it wants me to click a submit button to get redirected to a non javascript part of the site. How can I ...
[ "if that submit button is really a submit input element of the form, and the redirection works as usual form submit action, and provided that it's the only form in the page, your mechanize browser instance is br, following should work\nbr.select_form(nr=0) # select the first form\nbr.submit()\n\nafaik, there's no s...
[ 3 ]
[]
[]
[ "browser", "mechanize", "python" ]
stackoverflow_0003901218_browser_mechanize_python.txt
Q: pymongo (python+mongodb) drop collection/gridfs? Anyone know the commands to drop a collection of documents and also drop a gridfs database? A: To delete a collection, you can either call the drop() method on it, or use the drop_collection() method on the database object: my_collection = db['collection_name'] my...
pymongo (python+mongodb) drop collection/gridfs?
Anyone know the commands to drop a collection of documents and also drop a gridfs database?
[ "To delete a collection, you can either call the drop() method on it, or use the drop_collection() method on the database object:\nmy_collection = db['collection_name']\nmy_collection.drop()\n\n# Or...\n\ndb.drop_collection('collection_name')\n\nGridFS files are stored in a collection called fs by default. To delet...
[ 11 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0003895572_mongodb_pymongo_python.txt
Q: how reduce the number of points of a waveform? I have this, f = audiolab.Sndfile('test.wav', 'r') data = f.read_frames(f.nframes, dtype=numpy.int16) pyplot.rcParams['figure.figsize'] = 10, 2 pyplot.plot(data) pyplot.xticks([]) pyplot.yticks([]) pyplot.show() but the ploting is slow and freeze the pc, hoy I c...
how reduce the number of points of a waveform?
I have this, f = audiolab.Sndfile('test.wav', 'r') data = f.read_frames(f.nframes, dtype=numpy.int16) pyplot.rcParams['figure.figsize'] = 10, 2 pyplot.plot(data) pyplot.xticks([]) pyplot.yticks([]) pyplot.show() but the ploting is slow and freeze the pc, hoy I can reduce the numbers of points or how can I increas...
[ "Use something like NumPy to resample the data to a lower frequency before adding it to the plot.\n", "You could take (roughly) 1000 evenly spaced points from your data this way:\nn = len(data)\npyplot.plot(data[::n/1000])\n\n" ]
[ 0, 0 ]
[]
[]
[ "audio", "python", "waveform" ]
stackoverflow_0003901324_audio_python_waveform.txt
Q: Installing rpy2 -2.1.5 on Mac OS X 10.5.8 fails I've searched far and wide, read a previous question in stackoverflow but cant seem to solve the problem of installing rpy2 on my Mac with OS X 10.5.8. I have Xcode 3.1.4 installed and R 2.1.11. when I run: sudo python setup.py build install I get this: running bui...
Installing rpy2 -2.1.5 on Mac OS X 10.5.8 fails
I've searched far and wide, read a previous question in stackoverflow but cant seem to solve the problem of installing rpy2 on my Mac with OS X 10.5.8. I have Xcode 3.1.4 installed and R 2.1.11. when I run: sudo python setup.py build install I get this: running build running build_py running build_ext building 'rpy2....
[ "Can you try a snapshot from the mercurial repository ?\n(either branch version_2.1.x - future version 2.1.6 -, or version_2.2.x - future version 2.2.0)\nThe build procedure has been streamlined and should accomodate better OS X.\n" ]
[ 1 ]
[]
[]
[ "macos", "python", "r", "rpy2" ]
stackoverflow_0003900790_macos_python_r_rpy2.txt
Q: I'm new to python, and trying to program a sales tax button for a calculator I just started programming in python not long ago, and I'm having trouble figuring out the rounding issue when it comes to tax and money. I can't seem to get decimals to always round up to the nearest hundredths place. for instance, in ...
I'm new to python, and trying to program a sales tax button for a calculator
I just started programming in python not long ago, and I'm having trouble figuring out the rounding issue when it comes to tax and money. I can't seem to get decimals to always round up to the nearest hundredths place. for instance, in our state, sales takes is 9.5%, so a purchase of 5 dollars would make tax $.48, bu...
[ "For money amounts it is better to use Python's decimal, where you don't have problems with floating-point representation and the numbers will keep rounded to two decimals (cents).\nimport decimal\n\ndef calculateVat(price):\n VAT = decimal.Decimal('0.095')\n return (price * VAT).quantize(price, rounding=deci...
[ 6, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003901444_python.txt
Q: Finding combination in Python without importing itertools I want following task to be done in Python without importing any modules. My Code consists Two List --------- list1=['aun','2ab','acd','3aa'] list2=['ca3','ba2','dca','aa3'] Function --------- Where it will: Generates 2 items combination from list1 Gener...
Finding combination in Python without importing itertools
I want following task to be done in Python without importing any modules. My Code consists Two List --------- list1=['aun','2ab','acd','3aa'] list2=['ca3','ba2','dca','aa3'] Function --------- Where it will: Generates 2 items combination from list1 Generates 2 items combination from list2 Generates 2 items combinati...
[ "Well, you already got the answer how to do it with itertools. If you want to do it without importing that module (for whatever reason...), you could still take a look at the docs and read the source:\ndef product(*args, **kwds):\n # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy\n # product(range(2), repe...
[ 6 ]
[]
[]
[ "combinations", "python" ]
stackoverflow_0003902009_combinations_python.txt
Q: Calling C# object from IronPython I have the following C# code to compile it into MyMath.dll assembly. namespace MyMath { public class Arith { public Arith() {} public int Add(int x, int y) { return x + y; } } } And I have the following IronPython code to use this objec...
Calling C# object from IronPython
I have the following C# code to compile it into MyMath.dll assembly. namespace MyMath { public class Arith { public Arith() {} public int Add(int x, int y) { return x + y; } } } And I have the following IronPython code to use this object. import clr clr.AddReferenceToFile("M...
[ "You should be doing the following:\nfrom MyMath import Arith\n\nOr:\nfrom MyMath import *\n\nOtherwise, you'll have to refer to the Arith class as MyMath.Arith.\n" ]
[ 6 ]
[]
[]
[ "c#", "ironpython", "python" ]
stackoverflow_0003902018_c#_ironpython_python.txt
Q: How to detect CPU speed and H.D.D rpm in objective-c or python I'm new to objective-c, for an academic reason I need to read CPU speed and H.D.D rpm What is the simplest way to access some system setting in objective-c or python I can choose between objective-c and python for this project. A: I think you would ...
How to detect CPU speed and H.D.D rpm in objective-c or python
I'm new to objective-c, for an academic reason I need to read CPU speed and H.D.D rpm What is the simplest way to access some system setting in objective-c or python I can choose between objective-c and python for this project.
[ "I think you would have to use a C++ module with Python to detect CPU speed or RPM of a hard drive. Calculate total CPU usage could help you here\nI don't know anything about Obj-C, so couldn't tell you if it is possible with that language!\n", "This can get the reported CPU speed for Windows 2000 and up by readi...
[ 2, 1, 1 ]
[]
[]
[ "objective_c", "python", "system_setting" ]
stackoverflow_0003900345_objective_c_python_system_setting.txt
Q: findPattern() Python Code...not executing correctly? my homework assignment was to: "write a function called findPattern() which accepts two strings as parameters, a filename and a pattern. The function reads in the file specified by the given filename and searches the file’s contents for the given pattern. It th...
findPattern() Python Code...not executing correctly?
my homework assignment was to: "write a function called findPattern() which accepts two strings as parameters, a filename and a pattern. The function reads in the file specified by the given filename and searches the file’s contents for the given pattern. It then returns the line number and index of the line where the...
[ "Your variable names are misspelled: linecount vs. lineCount, lettern vs. letter. Python doesn't always warn against this type of error. If this is just a copying error, then line(letter) is the error: an index is given by []. What kind of pattern are you searching for, a single character or a string? line[letter] ...
[ 1, 0 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0003902102_design_patterns_python.txt
Q: resources for learning 3D basics (Python / JavaScript) While I consider myself a reasonably competent programmer, I have no experience with even the most basic graphics programming. Are there any recommended resources for learning the basics of 3D programming - preferably using a high-level language like Python or...
resources for learning 3D basics (Python / JavaScript)
While I consider myself a reasonably competent programmer, I have no experience with even the most basic graphics programming. Are there any recommended resources for learning the basics of 3D programming - preferably using a high-level language like Python or JavaScript? Ideally, I'd like a simple hello world example ...
[ "http://learningwebgl.com/blog/\n", "Unity is what I recommend but I've also heard about (but never tried)\nPanda3D and Worldviz Vizard. If you want to build it from the ground up yourself you might try Pygame though you may have to hunt for the right libraries. Other things you might look at:VPython, and PyOpe...
[ 2, 1 ]
[]
[]
[ "3d", "canvas", "javascript", "python" ]
stackoverflow_0003902054_3d_canvas_javascript_python.txt
Q: How do I count words in an nltk plaintextcorpus faster? I have a set of documents, and I want to return a list of tuples where each tuple has the date of a given document and the number of times a given search term appears in that document. My code (below) works, but is slow, and I'm a n00b. Are there obvious wa...
How do I count words in an nltk plaintextcorpus faster?
I have a set of documents, and I want to return a list of tuples where each tuple has the date of a given document and the number of times a given search term appears in that document. My code (below) works, but is slow, and I'm a n00b. Are there obvious ways to make this faster? Any help would be much appreciated, ...
[ "If you just want a frequency of word counts, then you don't need to create nltk.Text objects, or even use nltk.PlainTextReader. Instead, just go straight to nltk.FreqDist.\nfiles = list_of_files\nfd = nltk.FreqDist()\nfor file in files:\n with open(file) as f:\n for sent in nltk.sent_tokenize(f.lower()):...
[ 8 ]
[]
[]
[ "corpus", "nlp", "nltk", "python" ]
stackoverflow_0003902044_corpus_nlp_nltk_python.txt
Q: Converting flat sequence to 2d sequence in python I have a piece of code that will return a flat sequence for every pixel in a image. import Image im = Image.open("test.png") print("Picture size is ", width, height) data = list(im.getdata()) for n in range(width*height): if data[n] == (0, 0, 0): print(...
Converting flat sequence to 2d sequence in python
I have a piece of code that will return a flat sequence for every pixel in a image. import Image im = Image.open("test.png") print("Picture size is ", width, height) data = list(im.getdata()) for n in range(width*height): if data[n] == (0, 0, 0): print(data[n], n) This codes returns something like this ((0...
[ "Simple math: you have n, width, height and want x, y\nx, y = n % width, n / width\n\nor (does the same but more efficient)\ny, x = divmod(n, width)\n\n", "You could easily make a function that would emulate 2d data:\ndef data2d(x,y,width):\n return data[y*width+x]\n\nBut if you want to put the data in a 2dish d...
[ 1, 0 ]
[]
[]
[ "image", "python", "python_imaging_library" ]
stackoverflow_0003902306_image_python_python_imaging_library.txt
Q: What are methods of programmatically detecting many-to-many relationships in a RDMBS? I'm currently busy making a Python ORM which gets all of its information from a RDBMS via introspection (I would go with XRecord if I was happy with it in other respects) — meaning, the end-user only tells which tables/views to l...
What are methods of programmatically detecting many-to-many relationships in a RDMBS?
I'm currently busy making a Python ORM which gets all of its information from a RDBMS via introspection (I would go with XRecord if I was happy with it in other respects) — meaning, the end-user only tells which tables/views to look at, and the ORM does everything else automatically (if it makes you actually write some...
[ "If you have to ask, you shouldn't be doing this. I'm not saying that to be cruel, but Python already has several excellent ORMs that are well-tested and widely used. For example, SQLAlchemy supports the autoload=True attribute when defining tables that makes it read the table definition - including all the stuff y...
[ 1, 0, 0 ]
[]
[]
[ "introspection", "metaprogramming", "orm", "python", "relationships" ]
stackoverflow_0003901961_introspection_metaprogramming_orm_python_relationships.txt
Q: Can't *copy* an index from list to another with a twist in Python I'm pretty new to python and am trying to grab the ropes and decided a fun way to learn would be to make a cheesy MUD type game. My goal for the piece of code I'm going to show is to have three randomly selected enemies(from a list) be presented for...
Can't *copy* an index from list to another with a twist in Python
I'm pretty new to python and am trying to grab the ropes and decided a fun way to learn would be to make a cheesy MUD type game. My goal for the piece of code I'm going to show is to have three randomly selected enemies(from a list) be presented for the "hero" to fight. The issue I am running into is that python is cop...
[ "Change\ngenENE.insert(i,enemies[0])\n\nto\ngenENE.insert(i,enemies[0][:])\n\nThis will force the list to be copied rather than referenced. Also, I would use append rather than insert in this instance.\n", "they all subtract that value What do you mean do they all? If you mean both lists, you're problem is beca...
[ 1, 0 ]
[]
[]
[ "copy", "indexing", "list", "python" ]
stackoverflow_0003902608_copy_indexing_list_python.txt
Q: Jython/Grinder/Grinderstone: self arg can't be coerced to net.grinder.plugin.http.HTTPUtilities A grinder script i have been building out for the past few days has been working pretty well up until just now. I am getting a runtime error initially saying: self.token___LASTFOCUS = HTTPUtilities.valueFromHiddenIn...
Jython/Grinder/Grinderstone: self arg can't be coerced to net.grinder.plugin.http.HTTPUtilities
A grinder script i have been building out for the past few days has been working pretty well up until just now. I am getting a runtime error initially saying: self.token___LASTFOCUS = HTTPUtilities.valueFromHiddenInput('__LASTFOCUS') TypeError: valueFromHiddenInput(): expected 2-3 args; got 1 so i added [an...
[ "found the answer i needed these lines\nfrom net.grinder.plugin.http import HTTPPluginControl\nhttpUtilities = HTTPPluginControl.getHTTPUtilities()\n\nIt looks like HTTPUtilities might be a singleton or has a factory method.\nNot to sure on what that specific architecture is.\n" ]
[ 1 ]
[]
[]
[ "grinder", "java", "jython", "python" ]
stackoverflow_0003902029_grinder_java_jython_python.txt
Q: Python, is it proper for one thread to spawn another I am writing an update application in Python 2.x. I have one thread (ticket_server) sitting on a database (CouchDB) url in longpoll mode. Update requests are dumped into this database from an outside application. When a change comes, ticket_server triggers a wor...
Python, is it proper for one thread to spawn another
I am writing an update application in Python 2.x. I have one thread (ticket_server) sitting on a database (CouchDB) url in longpoll mode. Update requests are dumped into this database from an outside application. When a change comes, ticket_server triggers a worker thread (update_manager). The heavy lifting is done in ...
[ "The main thread of a program is a thread; the only way to spawn a thread is from another thread.\nOf course, you need to make sure your blocking thread is releasing the GIL while it waits, or other Python threads won't run. All mature Python database bindings will do this, but I've never heard of couchdb.\n" ]
[ 3 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003902696_multithreading_python.txt
Q: How to change default django User model to fit my needs? The default Django's User model has some fields, and validation rules, that I don't really need. I want to make registration as simple as possible, i.e. require either email or username, or phone number - all those being unique, hence good as user identifier...
How to change default django User model to fit my needs?
The default Django's User model has some fields, and validation rules, that I don't really need. I want to make registration as simple as possible, i.e. require either email or username, or phone number - all those being unique, hence good as user identifiers. I also don't like default character set for user name that...
[ "Rather than modify the User class directly or do subclassing, you can also just repurpose the existing fields. \nFor one site I used the \"first_name\" field as the \"publicly displayed name\" of a user and stuff a slugified version of that into the \"username\" field (for use in URLs). I wrote a custom auth bac...
[ 10, 7, 7, 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000896421_django_django_models_python.txt
Q: How to replace openSSL calls with C# code? Today I ran into a problem when I was making a new theme creator for chrome. As you may know, Chrome uses a "new" file format, called CRX, to manage it's plugins and themes. It is a basic zip file, but a bit modified: "Cr24" + derkey + signature + zipFile And here comes t...
How to replace openSSL calls with C# code?
Today I ran into a problem when I was making a new theme creator for chrome. As you may know, Chrome uses a "new" file format, called CRX, to manage it's plugins and themes. It is a basic zip file, but a bit modified: "Cr24" + derkey + signature + zipFile And here comes the problem. There are only two CRX creators, wri...
[ "For Linux, there are a variety of utilities to do this - including one for bash - but it sounds like you want something for windows (guessing from your C# comment).\nI had tried to include links to all of them - but I am new stackoverflow user, and can only post 1 link..\nAnyway, all of those can work in windows, ...
[ 0 ]
[]
[]
[ "c#", "openssl", "python" ]
stackoverflow_0002528810_c#_openssl_python.txt
Q: Convert Python List to Column in CSV I have a list of values (v1, v2, v3) and I want to write these to a column called VALUES in a csv. I'm using csvreader and csvwriter to get as far as I have. I've only figured out how to write them to rows using csvwriter.writerow. A: It sounds like you have tried: values =...
Convert Python List to Column in CSV
I have a list of values (v1, v2, v3) and I want to write these to a column called VALUES in a csv. I'm using csvreader and csvwriter to get as far as I have. I've only figured out how to write them to rows using csvwriter.writerow.
[ "It sounds like you have tried:\nvalues = [1, 2, 3, 4, 5]\nthecsv = csv.writer(open(\"your.csv\", 'wb'))\nthecsv.writerow(values)\n\nPerhaps you should try:\nvalues = [1, 2, 3, 4, 5]\nthecsv = csv.writer(open(\"your.csv\", 'wb'))\nfor value in values:\n thecsv.writerow(value)\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003902944_python.txt
Q: How to know which row a user selects from an HTML table - GAE Python Sorry if this is a newbie question. I have searched but found nothing... Using Python on GAE, I will display a table of, say, customers on an HTML table. The table will show their name and phone number. I want the user to double-click on a row ...
How to know which row a user selects from an HTML table - GAE Python
Sorry if this is a newbie question. I have searched but found nothing... Using Python on GAE, I will display a table of, say, customers on an HTML table. The table will show their name and phone number. I want the user to double-click on a row and have the python Post() method know either the row number double-clicke...
[ "I have never used Python or Delphi (assuming by \"I come from Delphi\" you mean you are using the Delphi programming language) so forgive me if my answer is not relevant.\nOne method you could use is to give each tr a custom attribute. For example <tr custID='...'>...</tr>. You could then use jQuery to extract the...
[ 3 ]
[]
[]
[ "google_app_engine", "html", "python" ]
stackoverflow_0003903414_google_app_engine_html_python.txt
Q: Taking list's tail in a Pythonic way? from random import randrange data = [(randrange(8), randrange(8)) for x in range(8)] And we have to test if the first item equals to one of a tail. I am curious, how we would do it in most simple way without copying tail items to the new list? Please take into account this pi...
Taking list's tail in a Pythonic way?
from random import randrange data = [(randrange(8), randrange(8)) for x in range(8)] And we have to test if the first item equals to one of a tail. I am curious, how we would do it in most simple way without copying tail items to the new list? Please take into account this piece of code gets executed many times in, sa...
[ "Nick D's Answer is better\nuse islice. It doesn't make a copy of the list and essentially embeds your second (elegant but verbose) solution in a C module.\nimport itertools\n\nhead = data[0]\nresult = head in itertools.islice(data, 1, None)\n\nfor a demo:\n>>> a = [1, 2, 3, 1]\n>>> head = a[0]\n>>> tail = itertool...
[ 8, 5 ]
[]
[]
[ "python" ]
stackoverflow_0003903467_python.txt
Q: Activate Python program every 5 minutes? Is there an easy way to get a python code segment to run every 5 minutes? I know I could do it using time.sleep() but was there any other way? For example I want to run this every 5 minutes: x = 0 def run_5(): print "5 minutes later" global x += 5 print x, "minu...
Activate Python program every 5 minutes?
Is there an easy way to get a python code segment to run every 5 minutes? I know I could do it using time.sleep() but was there any other way? For example I want to run this every 5 minutes: x = 0 def run_5(): print "5 minutes later" global x += 5 print x, "minutes since start" That's only a fake example b...
[ "you can do it with the threading module\n>>> import threading\n>>> END = False\n>>> def run(x=0):\n... x += 5\n... print x\n... if not END:\n... threading.Timer(1.0, run, [x]).start()\n... \n>>> threading.Timer(1.0, run, [x]).start()\n>>> 5\n10\n15\n20\n25\n30\n35\n40\n\nThen when you want it t...
[ 2, 2, 0 ]
[]
[]
[ "python", "time" ]
stackoverflow_0003904033_python_time.txt
Q: How to catch python syntax errors? try: pattern=r'<tr><td><a href='(?P<link>[\s\S]*?)'[\s\S]*?><img src='(?P<img>[\s\S]*?)' width='130' height='130'[\s\S]*?/></a></td>' except: try: pattern=r"<tr><td><a href='(?P<link>[\s\S]*?)'[\s\S]*?><img src='(?P<img>[\s\S]*?)' width='130' height='130'[\s\S...
How to catch python syntax errors?
try: pattern=r'<tr><td><a href='(?P<link>[\s\S]*?)'[\s\S]*?><img src='(?P<img>[\s\S]*?)' width='130' height='130'[\s\S]*?/></a></td>' except: try: pattern=r"<tr><td><a href='(?P<link>[\s\S]*?)'[\s\S]*?><img src='(?P<img>[\s\S]*?)' width='130' height='130'[\s\S]*?/></a></td>" except: patt...
[ "You need to escape your quotes inside the RE. In your first line, all the single quotes need to be escaped as \\'.\nDon't use a try block to fix your faulty RE. Just do it right the first time.\n", "The try/except statement in Python is used for errors that happen while your program is running. On the other hand...
[ 0, 0 ]
[]
[]
[ "error_handling", "python", "regex", "try_except" ]
stackoverflow_0003904054_error_handling_python_regex_try_except.txt
Q: Restore Python class to original state I have a class where I add some attributes dynamically and at some point I want to restore the class to it's pristine condition without the added attributes. The situation: class Foo(object): pass Foo.x = 1 # <insert python magic here> o = Foo() # o should not have any of ...
Restore Python class to original state
I have a class where I add some attributes dynamically and at some point I want to restore the class to it's pristine condition without the added attributes. The situation: class Foo(object): pass Foo.x = 1 # <insert python magic here> o = Foo() # o should not have any of the previously added attributes print o.x # ...
[ "I agree with Glenn that this is a horribly broken idea. Anyways, here how you'd do it with a decorator. Thanks to Glenn's post as well for reminding me that you can delete items from a class's dictionary, just not directly. Here's the code.\ndef resetable(cls):\n cls._resetable_cache_ = cls.__dict__.copy()\n ...
[ 5, 3, 3, 1, 0, 0, 0, 0, 0 ]
[ "To create a deep copy of a class you can use the new.classobj function\nclass Foo:\n pass\n\nimport new, copy\nFooSaved = new.classobj(Foo.__name__, Foo.__bases__, copy.deepcopy(Foo.__dict__))\n\n# ...play with original class Foo...\n\n# revert changes\nFoo = FooSaved\n\nUPD: module new is deprecated. Instead y...
[ -1 ]
[ "python" ]
stackoverflow_0003899454_python.txt
Q: Python trouble with repeater Im trying to write a program so that I get a result of... 5 : Rowan 6 : Rowan 7 : Rowan 8 : Rowan 9 : Rowan 10 : Rowan 11 : Rowan 12 : Rowan I want to be able to set it so that I can change the starting number, the amount of times it repeats and the word that it repeats. this is what...
Python trouble with repeater
Im trying to write a program so that I get a result of... 5 : Rowan 6 : Rowan 7 : Rowan 8 : Rowan 9 : Rowan 10 : Rowan 11 : Rowan 12 : Rowan I want to be able to set it so that I can change the starting number, the amount of times it repeats and the word that it repeats. this is what i have so far... def hii(howMany,...
[ "The range iterator takes a start value:\ndef hii(howMany, start, Word):\n for i in range(start, start+howMany):\n print i, \":\", Word\n\nNote that it's not a good idea to use the same name for a local variable as for a parameter (howMany). I have used i instead.\n", "From Python 2.6 upwards enumerate ...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003903263_python.txt
Q: how to get all the users from the list in twitter? I want to get all the user from a list using twitter api. But i have some query regarding this. Does this needs oauth authentication? I am using python. A: Returning the members of a specified list does require authentication.
how to get all the users from the list in twitter?
I want to get all the user from a list using twitter api. But i have some query regarding this. Does this needs oauth authentication? I am using python.
[ "Returning the members of a specified list does require authentication.\n" ]
[ 1 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0003904262_python_twitter.txt
Q: Immutable types allowing subclassing in Python I want to have immutable types that can, ideally, sort out their own hashing and equality, but can be easily subclassed. I started off using namedtuple: class Command(namedtuple('Command', 'cmd_string')): def valid_msg(msg): return True def make_command(msg)...
Immutable types allowing subclassing in Python
I want to have immutable types that can, ideally, sort out their own hashing and equality, but can be easily subclassed. I started off using namedtuple: class Command(namedtuple('Command', 'cmd_string')): def valid_msg(msg): return True def make_command(msg): if self.valid_msg(msg): return '%s:%s' %...
[ "Here's a metaclass to do what you want (I think). It works by storing the methods to be inherited in a dictionary and manually inserting them into the new classes dictionary. It also stores the attribute string that gets passed to the namedtuple constructor and merges that with the attribute string from the subcla...
[ 1 ]
[]
[]
[ "immutability", "python" ]
stackoverflow_0003904441_immutability_python.txt
Q: Converting while to generator 3.4 times slow down What is happening? Can somebody explain me what happens here, I changed in tight loop: ## j=i ## while j < ls - 1 and len(wordlist[j]) > lc: j+=1 j = next(j for j in range(i,ls) if len(wordlist[j]) <= lc) The commented while vers...
Converting while to generator 3.4 times slow down
What is happening? Can somebody explain me what happens here, I changed in tight loop: ## j=i ## while j < ls - 1 and len(wordlist[j]) > lc: j+=1 j = next(j for j in range(i,ls) if len(wordlist[j]) <= lc) The commented while version ran the whole program: 625 ms, the next generator v...
[ "I've found that using generators can often be slower than generating the whole list, which is a little counter-intuitive. I've managed to fix performance bottlenecks just by adding a [] pair.\nFor example compare these:\n$ python -m timeit -n 1000 \"' '.join(c for c in 'hello world')\"\n1000 loops, best of 3: 6.11...
[ 4, 0 ]
[]
[]
[ "generator", "optimization", "performance", "python", "while_loop" ]
stackoverflow_0003902522_generator_optimization_performance_python_while_loop.txt
Q: facebook self.graph.put_object I using the Python SDK (http://github.com/facebook/python-sdk/) with Google app engine. I can post message on user wall with the self.graph.put_object function while the user is online. How do post a message to user wall directly from the server even the user is offline? A: I am as...
facebook self.graph.put_object
I using the Python SDK (http://github.com/facebook/python-sdk/) with Google app engine. I can post message on user wall with the self.graph.put_object function while the user is online. How do post a message to user wall directly from the server even the user is offline?
[ "I am assuming you know how to kick the work off and just need the calls to authenticate for the user.\nYour facebook app must request extended permissions from the user.\nhttp://developers.facebook.com/docs/authentication/permissions\noffline_access\n\nEnables your application to perform\n authorized requests on ...
[ 1 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0003903761_facebook_python.txt
Q: return html for a web server and not plain text in python here is my code : import socket import sys import re import base64 import binascii import time class Serverhttp: def __init__(self): self.GET = re.compile("GET.*?HTTP") self.POST = re.compile("GET.*?HTTP") try : sock ...
return html for a web server and not plain text in python
here is my code : import socket import sys import re import base64 import binascii import time class Serverhttp: def __init__(self): self.GET = re.compile("GET.*?HTTP") self.POST = re.compile("GET.*?HTTP") try : sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
[ "Replace your return statement with the following \nreturn \"HTTP/1.0 200 OK\\r\\nContent-type:text/html;charset=utf8\\r\\n\\r\\n<html><body>test</body></html>\"\n\nNote: You should understand how to respond and handle HTTP requests properly. If you are serious in building your own web server, you should first read...
[ 4, 1 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003904584_html_python.txt
Q: How to support recursive include when parsing xml I'm defining an xml schema of my own which supports the additional tag "insert_tag", which when reached should insert the text file at that point in the stream and then continue the parsing: Here is an example: my.xml: <xml> Something <insert_file name="foo.html...
How to support recursive include when parsing xml
I'm defining an xml schema of my own which supports the additional tag "insert_tag", which when reached should insert the text file at that point in the stream and then continue the parsing: Here is an example: my.xml: <xml> Something <insert_file name="foo.html"/> or another </xml> I'm using xmlreader as follows:...
[ "Have you considered using xinclude? The lxml library has builtin support for it.\n" ]
[ 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0003901419_python_xml.txt
Q: Multiproccessing with DB connection I have some processes with python gui application and i want to connect with them to sql server. i use the following modules form multiproccessing import pool import pymssql conn = pymssql.connect(host=host,user=user,password=password,database=database) for data in my_list :...
Multiproccessing with DB connection
I have some processes with python gui application and i want to connect with them to sql server. i use the following modules form multiproccessing import pool import pymssql conn = pymssql.connect(host=host,user=user,password=password,database=database) for data in my_list : self.pool.apply_async(fun,data,conn)...
[ "A new one for every process, because per definition processes can not share in memory ressources.\n" ]
[ 4 ]
[]
[]
[ "multiprocessing", "python", "sql_server" ]
stackoverflow_0003905141_multiprocessing_python_sql_server.txt
Q: Not able to install a python module "Pycrypto-2.3" I tried installing a python module "Pycrypto-2.3".But its giving the following long list of errors: running install running build running build_py running build_ext building 'Crypto.PublicKey._fastmath' extension /usr/lib/python2.6/pycc -std=c99 -O3 -fomit-frame-p...
Not able to install a python module "Pycrypto-2.3"
I tried installing a python module "Pycrypto-2.3".But its giving the following long list of errors: running install running build running build_py running build_ext building 'Crypto.PublicKey._fastmath' extension /usr/lib/python2.6/pycc -std=c99 -O3 -fomit-frame-pointer -Isrc/ -I/usr/include/python2.6 -c src/_fastmath...
[ "The following error:\nsrc/_fastmath.c:34:17: gmp.h: No such file or directory\n\nis probably the cause of your problems. It's part of the \"gnu multiprecision library\", and you need the \"dev\" part of it. On Debian. the package is libgmp2-dev, for Redhat it's gmp-devel. For other platforms you'll have to search ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003903863_python.txt
Q: Adding database module I am new to django I would like to start a project but when i run it i get this error Error loading MySQLdb module How do i add the MYSQL module or any other module for that matter A: Install it on your system, using either a native installer or package, via pip or easy_install, or by run...
Adding database module
I am new to django I would like to start a project but when i run it i get this error Error loading MySQLdb module How do i add the MYSQL module or any other module for that matter
[ "Install it on your system, using either a native installer or package, via pip or easy_install, or by running setup.py in the tarball.\n", "you should install a mysql client and a mysql python client for that client. So you should execute following commands(For Debian systems)\napt-get install mysql-client\napt-...
[ 2, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0003905548_django_mysql_python.txt
Q: How to remove repeating non-adjacent string Given lines that look like the following: Blah \cite[9.1173]{Joyce:1986aa}\autocite[42]{Kenner:1970ab}\autocite[108]{Hall:1960aa} bbb.\n I’d like to remove the second (and any subsequent) occurrence of \autocite, resulting in the following: Blah \autocite[9.1173]{Joyce:1...
How to remove repeating non-adjacent string
Given lines that look like the following: Blah \cite[9.1173]{Joyce:1986aa}\autocite[42]{Kenner:1970ab}\autocite[108]{Hall:1960aa} bbb.\n I’d like to remove the second (and any subsequent) occurrence of \autocite, resulting in the following: Blah \autocite[9.1173]{Joyce:1986aa}[42]{Kenner:1970ab}[108]{Hall:1960aa} bbb.\...
[ "Regular expressions are not a panacea.\nl = s.split('\\\\autocite')\nprint '%s\\\\autocite%s' % (l[0], ''.join(l[1:]))\n\n", "If you absolutly want regexes you can use (?<=\\\\autocite)(.*?)\\\\autocite(.*) and replace with \\1\\2.\nBut @Ignacio Vazquez-Abrams answer is way better an efficient.\n" ]
[ 3, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003905509_python_regex.txt
Q: Change dtype of a single column in a 2d numpy array I am creating a 2d array full of zeros with the following line of code: MyNewArray=zeros([4,12],float) However, the first column will need to be populated with string-type textual data, while all the other columns will need to be populated with numerical data th...
Change dtype of a single column in a 2d numpy array
I am creating a 2d array full of zeros with the following line of code: MyNewArray=zeros([4,12],float) However, the first column will need to be populated with string-type textual data, while all the other columns will need to be populated with numerical data that can be manipulated mathematically. How can I edit the ...
[ "You might want to use structured arrays\nMyNewArray = zeros(12, dtype='S10,f4,f4,f4')\n\nThere are several ways of defining the structure, here I have defined 4 fields: one text with 10 characters, and three floats (you could write float instead of f4).\nIt is important to note that the number of characters of the...
[ 5 ]
[]
[]
[ "2d", "arrays", "numpy", "python", "types" ]
stackoverflow_0003904289_2d_arrays_numpy_python_types.txt
Q: EOF while scanning triple-quoted string literal i've looked on the web and here but i didn't find an answer : here is my code zlib.decompress(""" xワᆳヤ=ラᄇHナs~Ʀᄑç\ムîà Z@ÑÁÔQÇlxÇÆïPP~ýVãì゙M6ÛÐ|ê֭ᄁᄂヤ=)}éÓUe﬿ö3ᄎᄌú"}ʿïÿ÷1þ8ñ́U÷ᄏñíLÒVi:`ᄈᄎL!Ê҆p6-%Fë^ヘ÷à,Q.K!ユô`ÄA!ÑêweÌ ÊÚAロYøøÂjôóᅠÂcñ䊧fᆴùテúN :nüzAÝ7%ᄌcdUタᄌ3ôPۂタlンyHᆲᄑ$/y...
EOF while scanning triple-quoted string literal
i've looked on the web and here but i didn't find an answer : here is my code zlib.decompress(""" xワᆳヤ=ラᄇHナs~Ʀᄑç\ムîà Z@ÑÁÔQÇlxÇÆïPP~ýVãì゙M6ÛÐ|ê֭ᄁᄂヤ=)}éÓUe﬿ö3ᄎᄌú"}ʿïÿ÷1þ8ñ́U÷ᄏñíLÒVi:`ᄈᄎL!Ê҆p6-%Fë^ヘ÷à,Q.K!ユô`ÄA!ÑêweÌ ÊÚAロYøøÂjôóᅠÂcñ䊧fᆴùテúN :nüzAÝ7%ᄌcdUタᄌ3ôPۂタlンyHᆲᄑ$/yzᄒíàヌ'ÕÓ&`|S!<'ᄂ÷Zļᄐ2ホモ;ニ(ÅÛfb!úü$ナテᄒ,9ßhàPᄎᄄێフÑbØὛホQ...
[ "The zlib.decompress should work if you pass it the output of zlib.compress.\nSince the compressed string is really not text it is a binary string. It will not play friendly with displaying to the terminal as you have found.\nYou can use base64 encoding to give you something safe to drop into unittests, paste into...
[ 2, 0 ]
[]
[]
[ "eof", "python", "string" ]
stackoverflow_0003905025_eof_python_string.txt
Q: Python : Closing a socket already opened by a precedent python program or dirty trick to close a socket here is my dirty little web server : class Serverhttp: def __init__(self): self.GET = re.compile("GET.*?HTTP") self.POST = re.compile("POST.*?HTTP") try : sock = socket.socket(socket.AF_INET,...
Python : Closing a socket already opened by a precedent python program or dirty trick to close a socket
here is my dirty little web server : class Serverhttp: def __init__(self): self.GET = re.compile("GET.*?HTTP") self.POST = re.compile("POST.*?HTTP") try : sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 36000) print >>sys.stderr, 'starting up o...
[ "sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nShould do the trick.\n" ]
[ 4 ]
[]
[]
[ "kill", "python", "shutdown", "sockets" ]
stackoverflow_0003905832_kill_python_shutdown_sockets.txt
Q: Chromosome representation for real numbers? I am trying to solve a problem using genetic algorithms. The problem is to find the set of integral and real values that optimizes a function. I need to represent the problem using a binary string (simply because I understand the concept of crossover/mutation etc much b...
Chromosome representation for real numbers?
I am trying to solve a problem using genetic algorithms. The problem is to find the set of integral and real values that optimizes a function. I need to represent the problem using a binary string (simply because I understand the concept of crossover/mutation etc much better when applied to binary string chromosomes)....
[ "No, I think that binary representation is wrong for your problem. Your basic data is not binary, so, why use binary? Do mutation and crossover on real and integer numbers, not on their binary representation.\nSimplest crossover: first parent: ABCDE where A, B, ... are floating points numbers, second parents MNOPQ....
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "genetic_algorithm", "python" ]
stackoverflow_0003885626_genetic_algorithm_python.txt
Q: Capturing output from buffered StdOut program I'm trying to capture the output of a windows program using Qt and Python. I'm starting the process with QProcess, but the problem is the output is being buffered. Unfortunately I don't have access to the source, and therefore can't flush the output. From my searching...
Capturing output from buffered StdOut program
I'm trying to capture the output of a windows program using Qt and Python. I'm starting the process with QProcess, but the problem is the output is being buffered. Unfortunately I don't have access to the source, and therefore can't flush the output. From my searching around, I found the program "Expect", but I don't...
[ "Please take a look at QShared Memory http://doc.trolltech.com/main-snapshot/ipc-sharedmemory.html ... What you want to achieve is inter process communication, QShared memory works fine on Linux and Windows alike. \n" ]
[ 0 ]
[]
[]
[ "pyqt", "python", "stdout" ]
stackoverflow_0003902997_pyqt_python_stdout.txt
Q: Why thread is interrupted before the changes are complete I'm attempting to create python module for getting MAC adresses by IP addresses. def getMACs(addressesList): def _processArp(pkt): spa = _inet_ntoa(pkt.spa) if pkt.op == dpkt.arp.ARP_OP_REPLY and spa in _cache.macTable: lock...
Why thread is interrupted before the changes are complete
I'm attempting to create python module for getting MAC adresses by IP addresses. def getMACs(addressesList): def _processArp(pkt): spa = _inet_ntoa(pkt.spa) if pkt.op == dpkt.arp.ARP_OP_REPLY and spa in _cache.macTable: lock.acquire() try: _cache.macTable[spa...
[ "Stupid error. As always when working with threads - because of thread synchronization.\nOne of my conditions for interrupting thread is \"_cache.notFilledMacs == 0\". In the main thread _cache.notFilledMacs did not have time to get the value of 2 when in the CaptureThread value is decreased.\n" ]
[ 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003901766_multithreading_python.txt
Q: calculating means of many matrices in numpy I have many csv files which each contain roughly identical matrices. Each matrix is 11 columns by either 5 or 6 rows. The columns are variables and the rows are test conditions. Some of the matrices do not contain data for the last test condition, which is why there a...
calculating means of many matrices in numpy
I have many csv files which each contain roughly identical matrices. Each matrix is 11 columns by either 5 or 6 rows. The columns are variables and the rows are test conditions. Some of the matrices do not contain data for the last test condition, which is why there are 5 rows in some matrices and six rows in other ...
[ "You could use masked arrays. Say N is the number of csv files. You can store all your data in a masked array A, of shape (N,11,6).\nfrom numpy import *\nA = ma.zeros((N,11,6))\nA.mask = zeros_like(A) # fills the mask with zeros: nothing is masked\nA.mask = (A.data == 0) # another way of masking: mask all data equa...
[ 2 ]
[]
[]
[ "arrays", "mean", "numpy", "python" ]
stackoverflow_0003904983_arrays_mean_numpy_python.txt
Q: Twisted factory protocol instance based callback Hey, I got a ReconnectingClientFactory and I wonder if I can somehow define protocol-instance-based connectionMade/connectionLost callbacks so that i can use the factory to connect to different hosts ans distinguish between each connection. Thanks in advance. A: N...
Twisted factory protocol instance based callback
Hey, I got a ReconnectingClientFactory and I wonder if I can somehow define protocol-instance-based connectionMade/connectionLost callbacks so that i can use the factory to connect to different hosts ans distinguish between each connection. Thanks in advance.
[ "No. Write a class that does the interaction with one user. In connectionMade you check if a instance of this class already exists, if not you make a new one and store it on the factory, ie in a { addr : handler } dict. If the connection exists alreay you get the old handler from the factory.\n" ]
[ 1 ]
[]
[]
[ "factory", "python", "twisted" ]
stackoverflow_0003905791_factory_python_twisted.txt