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: Summing non-integers in Python Is it possible to take the sum of non-integers in Python? I tried the command sum([[1], [2]]) to get [1, 2], but it gives the error Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> sum([[1], [2]]) TypeError: unsupported operand type(s) for +: 'int' a...
Summing non-integers in Python
Is it possible to take the sum of non-integers in Python? I tried the command sum([[1], [2]]) to get [1, 2], but it gives the error Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> sum([[1], [2]]) TypeError: unsupported operand type(s) for +: 'int' and 'list' I suspect sum tries to ad...
[ "It looks like you want this:\n>>> sum([[1],[2]], [])\n[1, 2]\n\nYou're right that it's trying to add 0 to [1] and getting an error. The solution is to give sum an extra parameter giving the start value, which for you would be the empty list.\nEdit: As gnibbler says, though, sum is not a good way to concatenate thi...
[ 10, 9, 6, 3, 1, 0, 0 ]
[]
[]
[ "python", "sum" ]
stackoverflow_0003315365_python_sum.txt
Q: call program with arguments i would like to start a python file (.py) with arguments and receive the output of it after it is finished. i have already heard about "popen" and "subprocess.call" but i could not find any tutorials how to use them does anyone know a good tutorial? A: You don't need them ; just launc...
call program with arguments
i would like to start a python file (.py) with arguments and receive the output of it after it is finished. i have already heard about "popen" and "subprocess.call" but i could not find any tutorials how to use them does anyone know a good tutorial?
[ "You don't need them ; just launch your file as a program giving argument like\n./main.py arg1 arg2 arg3 >some_file\n\n(for that your file must begin with something like #!/usr/bin/env python)\nUsing sys module you can access them :\narg1 = sys.argv[1]\narg2 = sys.argv[2]\narg3 = sys.argv[3]\n\n", "\ni would like...
[ 6, 5, 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0003316961_python_python_3.x.txt
Q: script for mounting an iso on another server i need to mount a iso on another linux system is there any way to send mount command to the linux system? Thanks A: SSH seems to be your best bet. Although I have never used it, http://commandline.org.uk/python/sftp-python-really-simple-ssh/ seems to be a good option....
script for mounting an iso on another server
i need to mount a iso on another linux system is there any way to send mount command to the linux system? Thanks
[ "SSH seems to be your best bet. Although I have never used it, http://commandline.org.uk/python/sftp-python-really-simple-ssh/ seems to be a good option.\nimport ssh\ns = ssh.Connection('[Target Machine]')\ns.execute('mount -o loop [ISO File] [Mount Point]')\ns.close()\n\n", "import subprocess\nsubprocess.call(['...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003317481_python.txt
Q: Using serial over lan with python I'd like to write a python script to gather data from serial over lan but I can't seem to find a place to start with IPMI. I've looked at OpenIPMI's python bindings but there doesn't seem to be any documentation. Perhaps I can use the subprocess module and ipmitool? I'm not sur...
Using serial over lan with python
I'd like to write a python script to gather data from serial over lan but I can't seem to find a place to start with IPMI. I've looked at OpenIPMI's python bindings but there doesn't seem to be any documentation. Perhaps I can use the subprocess module and ipmitool? I'm not sure that would be simple though. Does an...
[ "Have you seen this thread that has a sample OpenIPMI python program?\nAnd the OpenIPMI documentation (pdf)?\n" ]
[ 2 ]
[]
[]
[ "api", "networking", "python", "serial_port" ]
stackoverflow_0003311516_api_networking_python_serial_port.txt
Q: Nested loop comparison in Python,Java and C The following code in python takes very long to run. (I couldn't wait until the program ended, though my friend told me for him it took 20 minutes.) But the equivalent code in Java runs in approximately 8 seconds and in C it takes 45 seconds. I expected Python to be slo...
Nested loop comparison in Python,Java and C
The following code in python takes very long to run. (I couldn't wait until the program ended, though my friend told me for him it took 20 minutes.) But the equivalent code in Java runs in approximately 8 seconds and in C it takes 45 seconds. I expected Python to be slow but not this much, and in case of C which I exp...
[ "Your test is not measuring anything meaningful.\nA language's performance in the real world has little to do with how quickly it executes a tight loop. \nFrankly, I'm intrigued that C and Java took as long as they did; I would have expected both of their compilers to realize that there was nothing happening inside...
[ 12, 9, 5, 3, 2, 1 ]
[]
[]
[ "c", "java", "performance", "python" ]
stackoverflow_0003318012_c_java_performance_python.txt
Q: How to find out if I have installed a Python module in Linux? I tried to install a Python module by typing: sudo python setup.py install After I typed this command I got a lot of output to the screen. The lest few lines are bellow: writing manifest file 'scikits.audiolab.egg-info/SOURCES.txt' removing '/usr/lib/py...
How to find out if I have installed a Python module in Linux?
I tried to install a Python module by typing: sudo python setup.py install After I typed this command I got a lot of output to the screen. The lest few lines are bellow: writing manifest file 'scikits.audiolab.egg-info/SOURCES.txt' removing '/usr/lib/python2.5/site-packages/scikits.audiolab-0.10.2-py2.5.egg-info' (and ...
[ "Have you tried import scikits.audiolab or import audiolab?\n", "From the OP's comment to an answer, it's clear that scikits.audiolab is indeed where this module's been installed, but it also needs you to install numpy. Assuming the module's configuration files are correct, by using easy_install instead of the u...
[ 5, 1, 1, 1, 0 ]
[]
[]
[ "import", "installation", "module", "python" ]
stackoverflow_0002058172_import_installation_module_python.txt
Q: Python twisted: how to schedule? Having 1-day experience in Twisted I try to schedule message sending in reply to tcp client: import os, sys, time from twisted.internet import protocol, reactor self.scenario = [(1, "Message after 1 sec!"), (4, "This after 4 secs"), (2, "End final after 2 secs")] for timeout, data...
Python twisted: how to schedule?
Having 1-day experience in Twisted I try to schedule message sending in reply to tcp client: import os, sys, time from twisted.internet import protocol, reactor self.scenario = [(1, "Message after 1 sec!"), (4, "This after 4 secs"), (2, "End final after 2 secs")] for timeout, data in self.scenario: reactor.cal...
[ "The important thing to realize when working with Twisted is that nothing waits for anything. When you call reactor.callLater(), you're asking the reactor to call something later, not now. The call finishes right away (after the call has been scheduled, before it has been executed.) Consequently, your print stateme...
[ 8, 4 ]
[]
[]
[ "networking", "python", "twisted" ]
stackoverflow_0003302185_networking_python_twisted.txt
Q: Python distutils.Extension : setting a concurrency level I'm wondering how to reproduce the equivalent of a make -j<n> on a setup.py using distutils.Extension, in order to build a C extension to Python 2.6 . My desired outcome: having setup.py build using a few instances of my C-compiler in the same time, instead ...
Python distutils.Extension : setting a concurrency level
I'm wondering how to reproduce the equivalent of a make -j<n> on a setup.py using distutils.Extension, in order to build a C extension to Python 2.6 . My desired outcome: having setup.py build using a few instances of my C-compiler in the same time, instead of only one. There are probably an environnement var or two th...
[ "And the answer from distutils-sig's mailing list is : a patch for distutils2 is still to be written.\n" ]
[ 0 ]
[]
[]
[ "concurrency", "distutils", "python" ]
stackoverflow_0003272022_concurrency_distutils_python.txt
Q: wxPython: wx.PyControl layout problem when it is a child of a wx.Panel This is a continuation from this question: wxPython: Can a wx.PyControl contain a wx.Sizer? The main topic here is using a wx.Sizer inside a wx.PyControl. I had problems Fit()ting my CustomWidget around its child widgets. That problem was solve...
wxPython: wx.PyControl layout problem when it is a child of a wx.Panel
This is a continuation from this question: wxPython: Can a wx.PyControl contain a wx.Sizer? The main topic here is using a wx.Sizer inside a wx.PyControl. I had problems Fit()ting my CustomWidget around its child widgets. That problem was solved by calling Layout() after Fit(). However, as far as I have experienced, th...
[ ".SetSizerAndFit(sizer) does the job. I'm not sure why a .SetSizer(sizer) then a .Fit() won't work. Any ideas?\nimport wx\n\nclass Frame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, parent=None)\n panel = Panel(parent=self)\n custom = CustomWidget(parent=panel)\n self.Show()\n\nclass Pane...
[ 1 ]
[]
[]
[ "custom_controls", "python", "sizer", "widget", "wxpython" ]
stackoverflow_0003308485_custom_controls_python_sizer_widget_wxpython.txt
Q: Python: Thread safe dictionary with short lived keys, is this correct? import threading import weakref _mainlock = threading.RLock() _job_locks = weakref.WeakValueDictionary() def do_thing(job_id): _mainlock.acquire() #Dictionary modification lock acquire _job_locks.setdefault(job_id, threading.RLock()) #P...
Python: Thread safe dictionary with short lived keys, is this correct?
import threading import weakref _mainlock = threading.RLock() _job_locks = weakref.WeakValueDictionary() def do_thing(job_id): _mainlock.acquire() #Dictionary modification lock acquire _job_locks.setdefault(job_id, threading.RLock()) #Possibly modifies the dictionary _mainlock.release() _job_locks[job_i...
[ "Seems very safe. Why do you even need the _job_locks if one_time_init checks again if it was run? You could add the lock there. Why RLock instead of Lock (the function seems to never re-enter)?\nAnyways, the with statement looks way nicer:\nimport threading\nimport weakref\n_mainlock = threading.RLock()\n_job_lock...
[ 4 ]
[]
[]
[ "dictionary", "multithreading", "python", "thread_safety", "weak_references" ]
stackoverflow_0003319392_dictionary_multithreading_python_thread_safety_weak_references.txt
Q: Problem encoding accented characters with python I'm having trouble encoding accented characters in a URL using the python command line. Reducing my problem to the essential, this code: >>> import urllib >>> print urllib.urlencode({'foo' : raw_input('> ')}) > áéíóúñ prints this in a mac command line: foo=%C3%A1%C...
Problem encoding accented characters with python
I'm having trouble encoding accented characters in a URL using the python command line. Reducing my problem to the essential, this code: >>> import urllib >>> print urllib.urlencode({'foo' : raw_input('> ')}) > áéíóúñ prints this in a mac command line: foo=%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1 but the same code prints...
[ "You can use explicit encoding to get consistent result.\n>>> str = u\"áéíóúñ\"\n>>> import urllib\n>>> urllib.urlencode({'foo':str.encode('utf-8')})\n'foo=%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1'\n\nHowever you need to ensure your string is in unicode first, so it may require decoding if its not, like raw_input().dec...
[ 3, 2 ]
[]
[]
[ "encoding", "macos", "python", "utf_8", "windows" ]
stackoverflow_0003315095_encoding_macos_python_utf_8_windows.txt
Q: can i store result directly as .txt file without getting displayed on GUI in python? my programme gives me very large results containg huge number of symbols,numbers.so that GUI often becomes 'non responding'.also takes so much time to display result.is there any way to store result as .txt file without getting di...
can i store result directly as .txt file without getting displayed on GUI in python?
my programme gives me very large results containg huge number of symbols,numbers.so that GUI often becomes 'non responding'.also takes so much time to display result.is there any way to store result as .txt file without getting displayed on GUI?
[ "Sorry for being a little unspecific, but that's what I get out of your question.\n # results will contain your large dataset ...\n handle = open(\"filename.txt\", \"w\")\n handle.write(results)\n handle.close()\n\nOr:\n with open(\"filename.txt\", \"w\") as f:\n f.write(results)\n\nIn case your results happen ...
[ 3, 1 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0003319669_python_user_interface.txt
Q: Class not refreshing on 2nd url call I have a web page with a link to a url eg./customer/showitem?id=7, which displays details of a specific customer in a child-window using method showitem() in class customer. The method may set the value of a customer class attribute that controls an alert which is displayed wh...
Class not refreshing on 2nd url call
I have a web page with a link to a url eg./customer/showitem?id=7, which displays details of a specific customer in a child-window using method showitem() in class customer. The method may set the value of a customer class attribute that controls an alert which is displayed when the page is loaded (eg. self.onloadaler...
[ "If you want data to persist for just one request, stick it on the cherrypy.request object:\ncherrypy.request.onloadalert=\"Warning!\"\n\nThe cherrypy.request object is completely destroyed and recreeated for each request, even though it's safely importable. Figuring out how is left as an exercise for the reader. ;...
[ 1 ]
[]
[]
[ "cherrypy", "persistence", "python", "url" ]
stackoverflow_0003314833_cherrypy_persistence_python_url.txt
Q: join tables with django queryObj = Rating.objects.select_related( 'Candidate','State','RatingCandidate','Sig','Office','OfficeCandidate').get( rating_id = ratingId, ratingcandidate__rating = ratingId, ratingcandidate__rating_candidate_id = \ officecandidate__office_candida...
join tables with django
queryObj = Rating.objects.select_related( 'Candidate','State','RatingCandidate','Sig','Office','OfficeCandidate').get( rating_id = ratingId, ratingcandidate__rating = ratingId, ratingcandidate__rating_candidate_id = \ officecandidate__office_candidate_id) This line gives me an...
[ "\nI'm trying to get many different tables that are linked by primary keys and regular ids.\n\nDon't try to \"join\" tables. This isn't SQL.\nYou have to do multiple gets to get data from many different tables.\nDon't worry about select_related until you can prove that you have a bottle-neck.\nJust do the various ...
[ 13, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003319632_django_python.txt
Q: How complicate can a Django application go? I'm tasked to create a simple CRUD MVC application, and I thought it's a good opportunity to learn python. Because of its great documentation, I'm thinking now that I'll go with Django. Now, this simple CRUD MVC application could become quite complicated in the future....
How complicate can a Django application go?
I'm tasked to create a simple CRUD MVC application, and I thought it's a good opportunity to learn python. Because of its great documentation, I'm thinking now that I'll go with Django. Now, this simple CRUD MVC application could become quite complicated in the future. I might have receive and issue JMS messages, dis...
[ "\nsimple CRUD MVC application\n\nDjango does this \"out of the box\" The admin interface is a simple, CRUD, MVC application. You don't do much programming to make this happen. You create the model. That's it. Use the Django admin for your CRUD application. Done.\n\nI might have receive and issue JMS messages...
[ 2, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003319890_django_python.txt
Q: How to correctly extract data with Regular Expressions i'm facing regulars expressions for the first time and i need to extract some data from this report (a txt file with formatting info): \n10: Vikelis M, Rapoport AM. Role of antiepileptic drugs as preventive agents for \nmigraine. CNS Drugs. 2010 Jan 1;2...
How to correctly extract data with Regular Expressions
i'm facing regulars expressions for the first time and i need to extract some data from this report (a txt file with formatting info): \n10: Vikelis M, Rapoport AM. Role of antiepileptic drugs as preventive agents for \nmigraine. CNS Drugs. 2010 Jan 1;24(1):21-33. doi:\n10.2165/11310970-000000000-00000. Revi...
[ "Use .+? for non-greedy matching instead of .+ which gives you greedy matching. You also want a re.DOTALL to make sure your . matches the line-end characters it needs to match, and re.MULTILINE to make sure the ^ and $ match starts and ends of line, not just of the whole string. The options in question need to be...
[ 2, 1 ]
[]
[]
[ "python", "regex", "text_files" ]
stackoverflow_0003320214_python_regex_text_files.txt
Q: Dealing with dates and timezones in a python project In a side project I have to manage, compare and display dates from different formats. What's the best design strategy to follow? I planned: All dates are parsed according their format and stored in the db in 9-tuple python format using UTC When I have to do cal...
Dealing with dates and timezones in a python project
In a side project I have to manage, compare and display dates from different formats. What's the best design strategy to follow? I planned: All dates are parsed according their format and stored in the db in 9-tuple python format using UTC When I have to do calculations and compares I transform 9-tuple in date...
[ "I'd use the DB's native datetime format rather than this \"9-tuple\" format. It'll make queries easier, and it's probably more space-efficient too.\nShouldn't be too hard to convert from that back into a Python datetime object. You can use the dateutil module if you're having trouble.\nI think you're right about k...
[ 2 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0003320374_datetime_python.txt
Q: Does Python Django support custom SQL and denormalized databases with no Foreign Key relationships? I've just started learning Python Django and have a lot of experience building high traffic websites using PHP and MySQL. What worries me so far is Python's overly optimistic approach that you will never need to wri...
Does Python Django support custom SQL and denormalized databases with no Foreign Key relationships?
I've just started learning Python Django and have a lot of experience building high traffic websites using PHP and MySQL. What worries me so far is Python's overly optimistic approach that you will never need to write custom SQL and that it automatically creates all these Foreign Key relationships in your database. The...
[ "If you don't want foreign keys, then avoid using\n\nmodels.ForeignKey(), \nmodels.ManyToManyField(), and \nmodels.OneToOneField().\n\nDjango will automatically create an auto-increment int field named id that you can use to refer to individual records, or you can override that by marking a field as primary_key=Tru...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0003066255_django_mysql_python.txt
Q: Python import inconsistent behavior I have a py file like this, which errors out. from world import acme def make_stuff_happen(): acme.account.foo() # Works acme.subscription.bar() # FAIL: "module 'object' has no attribute 'subscription'" make_stuff_happen() But this works! from world import acme...
Python import inconsistent behavior
I have a py file like this, which errors out. from world import acme def make_stuff_happen(): acme.account.foo() # Works acme.subscription.bar() # FAIL: "module 'object' has no attribute 'subscription'" make_stuff_happen() But this works! from world import acme from world.acme import subscription de...
[ "Submodules are referenced in the __init__.py file in the module folder. It appears that subscription is not referenced in acme's __init__.py.\nHowever, when you do import world.acme.subscription, it knows to go digging in that folder without talking to __init__.py.\nAccording to your description of __init__.py as ...
[ 6 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0003320467_import_module_python.txt
Q: Mutex locks vs Threading locks. Which to use? My main question is does the Threading lock object create atomic locks? It doesn't say that the lock is atomic in the module documentation. in pythons mutex documentation it does say the mutex lock is atomic but it seems that I read somewhere that in fact it isn't. I a...
Mutex locks vs Threading locks. Which to use?
My main question is does the Threading lock object create atomic locks? It doesn't say that the lock is atomic in the module documentation. in pythons mutex documentation it does say the mutex lock is atomic but it seems that I read somewhere that in fact it isn't. I am wondering if someone could could give me a bit of...
[ "Locks of any nature would be rather useless if they weren't atomic - the whole point of the lock is to allow for higher-level atomic operations.\nAll of threading's synchronization objects (locks, rlocks, semaphores, boundedsemaphores) utilize atomic instructions, as do mutexes.\nYou should use threading, since mu...
[ 13 ]
[]
[]
[ "locking", "multithreading", "mutex", "python" ]
stackoverflow_0003320514_locking_multithreading_mutex_python.txt
Q: Efficiently filter large number of datastore entities with a large number of property values In my App Engine datastore I've got an entity type which may hold a large number of entities, each of which will have the property 'customer_id'. For example, lets say a given customer_id has 10,000 entities, and there are...
Efficiently filter large number of datastore entities with a large number of property values
In my App Engine datastore I've got an entity type which may hold a large number of entities, each of which will have the property 'customer_id'. For example, lets say a given customer_id has 10,000 entities, and there are 50,000 customer_ids. I'm trying to filter this effectively, so that a user could get information ...
[ "Thanks for getting back to me. It looks like I had an issue with the account used when I posted so I need to respond in the comments here.\nHaving thought about it and from what you've said, fetching that many results is not going to work.\nHere's what I'm trying to do:\nI'm trying to make a report that shows for ...
[ 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003316301_google_app_engine_google_cloud_datastore_python.txt
Q: Dynamically loading two libpython versions I have a program which embeds both python2 and python3 interpreters. The libpython shared libraries are dlopen()ed by the respective commands which provide access to the interpreters and each interpreter maintains its own state. This all works just fine if the user only ...
Dynamically loading two libpython versions
I have a program which embeds both python2 and python3 interpreters. The libpython shared libraries are dlopen()ed by the respective commands which provide access to the interpreters and each interpreter maintains its own state. This all works just fine if the user only uses pure python modules or builtins. Trying to...
[ "Sorry, but this won't work the way you want it to. The solution ordinarily would involve linking each extension to versioned libpython symbols; or one could have a namespace-capable linker, such that one could map each library to a different namespace, rather than a global one. Unfortunately neither of these optio...
[ 1 ]
[]
[]
[ "c", "dynamic", "python" ]
stackoverflow_0003320742_c_dynamic_python.txt
Q: Troubles in installing python-sybase module I am trying to install this module simply following the installation guide: http:// python-sybase.sourceforge.net/sybase/node5.html I get an error that I don't understand, I am wondering if it's not a firewall problem but I don't know how to handle that: C:\Documents ...
Troubles in installing python-sybase module
I am trying to install this module simply following the installation guide: http:// python-sybase.sourceforge.net/sybase/node5.html I get an error that I don't understand, I am wondering if it's not a firewall problem but I don't know how to handle that: C:\Documents and Settings\lippela\Desktop\python-sybase-0.39>p...
[ "The setup script failed to download the .egg it tries to download. It also tells you what to do when that happens: download the file yourself and place it in the same directory as the script.\n" ]
[ 1 ]
[]
[]
[ "python", "sybase" ]
stackoverflow_0003320659_python_sybase.txt
Q: Generating all unique combinations for "drive ya nuts" puzzle A while back I wrote a simple python program to brute-force the single solution for the drive ya nuts puzzle. (source: tabbykat.com) The puzzle consists of 7 hexagons with the numbers 1-6 on them, and all pieces must be aligned so that each number is ...
Generating all unique combinations for "drive ya nuts" puzzle
A while back I wrote a simple python program to brute-force the single solution for the drive ya nuts puzzle. (source: tabbykat.com) The puzzle consists of 7 hexagons with the numbers 1-6 on them, and all pieces must be aligned so that each number is adjacent to the same number on the next piece. The puzzle has ~1.4G...
[ "To get only unique valid solutions, you can fix the orientation of the piece in the center. For example, you can assume that that the \"1\" on the piece in the center is always pointing \"up\".\nIf you're not already doing so, you can make your program much more efficient by checking for a valid solution after pl...
[ 5, 3, 1 ]
[]
[]
[ "combinatorics", "language_agnostic", "probability", "python" ]
stackoverflow_0002600924_combinatorics_language_agnostic_probability_python.txt
Q: Python: File not formatting like it should The could below doesnt write to the text file as it should: import re download_results = open('download_result.txt', 'w') s = 'AAAAAAABBBBCDEEEEEFFFFFFFFFFFFFGGGGGGGGGGGG##GGGGGGHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJKKKKKKKKKKKKLLLLLLLLLLLLLLLLMMMMMMM&&MMMMMMMMNNN...
Python: File not formatting like it should
The could below doesnt write to the text file as it should: import re download_results = open('download_result.txt', 'w') s = 'AAAAAAABBBBCDEEEEEFFFFFFFFFFFFFGGGGGGGGGGGG##GGGGGGHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJKKKKKKKKKKKKLLLLLLLLLLLLLLLLMMMMMMM&&MMMMMMMMNNNNNNNNNNNNOOOOOOOOOOOO' s = re.sub(r'[^\w]','',s)...
[ "Change this:\ndownload_results.write('%s' % (s[i:i+60]))\n\nto this:\ndownload_results.write('%s\\n' % (s[i:i+60]))\n\n", "Then append a newline in your write call within the loop - write() doesn't automatically add a newline, unlike print.\nfor i in range(0, len(s), 60):\n download_results.write('%s\\n' % (s...
[ 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003321348_python.txt
Q: I need help making a list I am trying to make a disorganized text file into a list suitable for use with another python program. The text file is a list of data seperated by a few spaces but not in standard columns or anything organized. The goal of this program is to read through the file using python and after e...
I need help making a list
I am trying to make a disorganized text file into a list suitable for use with another python program. The text file is a list of data seperated by a few spaces but not in standard columns or anything organized. The goal of this program is to read through the file using python and after each piece of data that I want t...
[ "lines = [item for item in open('C:\\textfile.txt', 'r').read().split(' ') if item.startswith(\"JJ\")]\n" ]
[ -1 ]
[]
[]
[ "python" ]
stackoverflow_0003321651_python.txt
Q: Python list remove method: how's the implementation? In java, I have my client class that have the "code" attr, and the equals method. Method equals receives another client and compares with itself's code attr. In python, I just read that we have the __cmp__ method, to do the same as java method equals. Ok, I did ...
Python list remove method: how's the implementation?
In java, I have my client class that have the "code" attr, and the equals method. Method equals receives another client and compares with itself's code attr. In python, I just read that we have the __cmp__ method, to do the same as java method equals. Ok, I did that. I created my class client, with "code" attr and the ...
[ "http://docs.python.org/reference/datamodel.html#object.__cmp__\n\n__cmp__(self, other)\nCalled by comparison operations if\n rich comparison (see above) is not\n defined. Should return a negative\n integer if self < other, zero if self\n == other, a positive integer if self > other.\n\nBasically, you should ch...
[ 5, 4 ]
[]
[]
[ "compare", "list", "python" ]
stackoverflow_0003321676_compare_list_python.txt
Q: Search a file and save the lines the search term is in to a new file I have two files. One is a csv and contains the search strings (one per line) and the other is a huge file which contains the search term at the start of each line but has extra information after which I would like to extract. The search terms f...
Search a file and save the lines the search term is in to a new file
I have two files. One is a csv and contains the search strings (one per line) and the other is a huge file which contains the search term at the start of each line but has extra information after which I would like to extract. The search terms file is called 'search.csv' and looks like this: 3ksr 3ky8 2g5w 2gou Th...
[ "Depending on how many search terms you have, and assuming they're all 4 characters:\nterms = open('search.csv').split(',')\n\nwith open('CSV.dat', 'r') as f:\n for line in f:\n if line[:4] in terms:\n #do something with line\n print line\n\nif they're not 4 chars you can do line[:line.f...
[ 1, 0 ]
[]
[]
[ "python", "search" ]
stackoverflow_0003321962_python_search.txt
Q: Making directories recursively in python I need to create a file with python, in the directory: foo/bar/baz/filename.fil The only problem, is that I don't know if baz, bar, or even foo have been created (they may have been, but the script doesn't guarantee it). So, obiously I can't do simply: file = open('foo/ba...
Making directories recursively in python
I need to create a file with python, in the directory: foo/bar/baz/filename.fil The only problem, is that I don't know if baz, bar, or even foo have been created (they may have been, but the script doesn't guarantee it). So, obiously I can't do simply: file = open('foo/bar/baz/filename.fil', 'wb') # Stuff # file.clos...
[ "Use os.makedirs\n" ]
[ 4 ]
[]
[]
[ "file", "python" ]
stackoverflow_0003322126_file_python.txt
Q: Ensuring code coverage in unit testing? I have noticed that even though I have a lot of doctests in our Python code, when I trace the testing using the methods described here: traceit I find that there are certain lines of code that are never executed. I currently sift through the traceit logs to identify blocks ...
Ensuring code coverage in unit testing?
I have noticed that even though I have a lot of doctests in our Python code, when I trace the testing using the methods described here: traceit I find that there are certain lines of code that are never executed. I currently sift through the traceit logs to identify blocks of code that are never run, and then try to c...
[ "coverage.py is a very handy tool. Among other things, it provides branch coverage.\n", "Do you have a mandate from management to be dogmatic about obtaining 100% code coverage with your test cases? If not, do you believe touching every line of code is the most effective way to find bugs in your code? Assuming yo...
[ 30, 19 ]
[]
[]
[ "code_coverage", "python", "testing", "unit_testing" ]
stackoverflow_0003322123_code_coverage_python_testing_unit_testing.txt
Q: Simple Python variable scope It seems to me that functions can reference variables outside of their scope but cannot set them. Is this correct? Am I understanding this right? I also included the globals usage. I know they are bad ju-ju and will avoid them; I know how to get around this, but just wanted to be clear...
Simple Python variable scope
It seems to me that functions can reference variables outside of their scope but cannot set them. Is this correct? Am I understanding this right? I also included the globals usage. I know they are bad ju-ju and will avoid them; I know how to get around this, but just wanted to be clear. My example program: import foo ...
[ "Correct. Well mostly. When you flag_to_do_something = 0 you are not modifying the variable, you are creating a new variable. The flag_to_do_something that is created in the function will be a separate link to (in this case) the same object. However, if you had used a function or operator that modified the variable...
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003322430_python.txt
Q: App Engine SDK: How do I view keys in a specific namespace using the Memcache Viewer? I'm trying to use the Memcache Viewer in the App Engine Dev Console to view keys in a specific namespace. The obvious syntax of namespace.key is not working; I haven't been able to find documentation describing specific usage. Is...
App Engine SDK: How do I view keys in a specific namespace using the Memcache Viewer?
I'm trying to use the Memcache Viewer in the App Engine Dev Console to view keys in a specific namespace. The obvious syntax of namespace.key is not working; I haven't been able to find documentation describing specific usage. Is this possible?
[ "Not possible. In dev, check namespace'd memcache items programmatically, e.g. using a handler.\nCredit: moraes on #appengine / freenode (validated by looking at source)\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "memcached", "python" ]
stackoverflow_0003175462_google_app_engine_memcached_python.txt
Q: Help on Regular Expression problem i wonder if it's possible to make a RegEx for the following data pattern: '152: Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.' string = '152: Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.' I am using this Regular Expression (Using Python's re module) to extract t...
Help on Regular Expression problem
i wonder if it's possible to make a RegEx for the following data pattern: '152: Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.' string = '152: Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.' I am using this Regular Expression (Using Python's re module) to extract these names: re.findall(r'(\d+): (.+), (....
[ "A regular expression probably isn't the best way to solve this. You could use split():\n>>> s = '152: Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.'\n>>> s.split(\": \")\n['152', 'Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.']\n>>> s.split(\": \")[1].split(\", \")\n['Ashkenazi A', 'Benlifer A', 'K...
[ 6, 1, 0, 0 ]
[]
[]
[ "python", "regex", "string", "unicode" ]
stackoverflow_0003322735_python_regex_string_unicode.txt
Q: Can I use python to create flash like browser games? is it possible to use python to create flash like browser games? (Actually I want to use it for an economic simulation, but it amounts to the same as a browser game) Davoud A: The answer would be yes, assuming you consider this a good example of what you want ...
Can I use python to create flash like browser games?
is it possible to use python to create flash like browser games? (Actually I want to use it for an economic simulation, but it amounts to the same as a browser game) Davoud
[ "The answer would be yes, assuming you consider this a good example of what you want to do:\nhttp://pyjs.org/examples/Space.html\nThis browser-based version of Asteroids was created using Pyjamas, which enables you to write the code in python in one place, and have it run either on the browser, or on the desktop:\n...
[ 13, 4, 2, 1, 1 ]
[]
[]
[ "browser", "python", "python_webbrowser" ]
stackoverflow_0002899907_browser_python_python_webbrowser.txt
Q: Suppose I had a list in Python. What's the most pythonic and efficient way to randomize it by sections? I have a list of X items. I want the first 10 to be randomized. Then, the 2nd 10 items to be randomized. Then the 3rd. What's the most efficient way to do this? A: It's good to break apart problems into small...
Suppose I had a list in Python. What's the most pythonic and efficient way to randomize it by sections?
I have a list of X items. I want the first 10 to be randomized. Then, the 2nd 10 items to be randomized. Then the 3rd. What's the most efficient way to do this?
[ "It's good to break apart problems into smaller problems which can be solved with reusable parts. The grouper idiom provides one such reusable part: it takes an iterable and groups its elements into groups of size n: \nimport random\nimport itertools\n\ndef grouper(n, iterable, fillvalue=None):\n # Source: http:...
[ 2, 2, 0 ]
[]
[]
[ "algorithm", "list", "python", "random", "sorting" ]
stackoverflow_0003321961_algorithm_list_python_random_sorting.txt
Q: Cross-Platform Bonjour Is it possible to write a program using Bonjour or a Bonjour-compatible library in a cross-platform language such as Java or Python? If so, where can I find the files needed for this? A: For Java have a look at the jmdns library which does it all in pure Java. http://jmdns.sourceforge.net...
Cross-Platform Bonjour
Is it possible to write a program using Bonjour or a Bonjour-compatible library in a cross-platform language such as Java or Python? If so, where can I find the files needed for this?
[ "For Java have a look at the jmdns library which does it all in pure Java. http://jmdns.sourceforge.net/\nI do not believe it can delegate to the native implementation if running on OS X, but it has been a while, so it might these days.\n" ]
[ 1 ]
[]
[]
[ "bonjour", "cross_platform", "java", "python" ]
stackoverflow_0003322689_bonjour_cross_platform_java_python.txt
Q: Am I supposed to directly modify User models in auth modules in frameworks? I am new to using Frameworks for web development and I have noticed that frameworks like django, turbogears etc come with auth packages which contains user models. Am I supposed to directly modify these and use them as my User models or am...
Am I supposed to directly modify User models in auth modules in frameworks?
I am new to using Frameworks for web development and I have noticed that frameworks like django, turbogears etc come with auth packages which contains user models. Am I supposed to directly modify these and use them as my User models or am I supposed to associate my own user models to these and use them just for authen...
[ "The latter: build a model with a one to one relationship to the User. Don't modify the django one directly or you'll likely run into trouble sooner or later. The django team won't be taking your changes into account after all and you could be adversely impacted if any internal changes are made. (Though you need...
[ 1 ]
[]
[]
[ "django", "frameworks", "python", "turbogears" ]
stackoverflow_0003323139_django_frameworks_python_turbogears.txt
Q: How to use same cookies in multiple request in python? I am using this code: def req(url, postfields): proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"}) opener = urllib2.build_opener(proxy_support) opener.addheaders = [('User-agent', 'Mozilla/5.0')] return opener.open(url).read() ...
How to use same cookies in multiple request in python?
I am using this code: def req(url, postfields): proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"}) opener = urllib2.build_opener(proxy_support) opener.addheaders = [('User-agent', 'Mozilla/5.0')] return opener.open(url).read() To make a simple http get request (using tor as proxy). Now ...
[ "The cookielib module is what you need to do this. There's a nice tutorial with some code samples.\n" ]
[ 2 ]
[]
[]
[ "cookies", "http", "httprequest", "python" ]
stackoverflow_0003323355_cookies_http_httprequest_python.txt
Q: Python Regex Question I have an end tag followed by a carriage return line feed (x0Dx0A) followd by one or more tabs (x09) followed by a new start tag . Something like this: </tag1>x0Dx0Ax09x09x09<tag2> or </tag1>x0Dx0Ax09x09x09x09x09<tag2> What Python regex should I use to replace it with something like this...
Python Regex Question
I have an end tag followed by a carriage return line feed (x0Dx0A) followd by one or more tabs (x09) followed by a new start tag . Something like this: </tag1>x0Dx0Ax09x09x09<tag2> or </tag1>x0Dx0Ax09x09x09x09x09<tag2> What Python regex should I use to replace it with something like this: </tag1><tag3>content</tag...
[ "Here is code for something like what you say that you need:\n>>> import re\n>>> sample = '</tag1>\\r\\n\\t\\t\\t\\t<tag2>'\n>>> sample\n'</tag1>\\r\\n\\t\\t\\t\\t<tag2>'\n>>> pattern = '(</tag1>)\\r\\n\\t+(<tag2>)'\n>>> replacement = r'\\1<tag3>content</tag3>\\2'\n>>> re.sub(pattern, replacement, sample)\n'</tag1>...
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003322383_python_regex.txt
Q: Character detection in a text file in Python using the Universal Encoding Detector (chardet) I am trying to use the Universal Encoding Detector (chardet) in Python to detect the most probable character encoding in a text file ('infile') and use that in further processing. While chardet is designed primarily for de...
Character detection in a text file in Python using the Universal Encoding Detector (chardet)
I am trying to use the Universal Encoding Detector (chardet) in Python to detect the most probable character encoding in a text file ('infile') and use that in further processing. While chardet is designed primarily for detecting the character encoding of webpages, I have found an example of it being used on individual...
[ "chardet.detect() returns a dictionary which provides the encoding as the value associated with the key 'encoding'. So you can do this:\nimport chardet \nrawdata = open(infile, 'rb').read()\nresult = chardet.detect(rawdata)\ncharenc = result['encoding']\n\nThe chardet documentation is not explicitly clear about ...
[ 66 ]
[]
[]
[ "character_encoding", "python" ]
stackoverflow_0003323770_character_encoding_python.txt
Q: celery-django can't find settings I have a Django project that uses Celery for running asynchronous tasks. I'm doing my development on a Windows XP machine. Starting my Django server (python manage.py runserver 80) works fine, but attempting to start the Celery Daemon (python manage.py celeryd start) fails with t...
celery-django can't find settings
I have a Django project that uses Celery for running asynchronous tasks. I'm doing my development on a Windows XP machine. Starting my Django server (python manage.py runserver 80) works fine, but attempting to start the Celery Daemon (python manage.py celeryd start) fails with the following error: ImportError: Could ...
[ "Apparently this is a problem with running Celery on Windows. Using the --settings argument ala python manage.py celeryd start --settings=settings did the trick.\n", "sys.path must include 'C:\\development\\SpaceCorps' not 'C:\\development\\SpaceCorps\\src', \nbecause he is looking for src.settings, not just set...
[ 19, 0 ]
[]
[]
[ "celery", "django", "python", "python_import", "settings" ]
stackoverflow_0003323125_celery_django_python_python_import_settings.txt
Q: Python: An empty element remains after the list comprehension keywords_list = """ cow dog cat """ keywords_list = [i.strip() for i in keywords_list.split("\n") if i] I'm still getting an empty element(last element) and I'm wondering why. Also suggestions to improve my code would be appreciated. Th...
Python: An empty element remains after the list comprehension
keywords_list = """ cow dog cat """ keywords_list = [i.strip() for i in keywords_list.split("\n") if i] I'm still getting an empty element(last element) and I'm wondering why. Also suggestions to improve my code would be appreciated. Thanks in advance! edit: solved it myself by stripping the string fir...
[ "You're checking if i, and that succeeds for any non-empty string i -- including one that's all whitespace and so will produce an empty string after stripping. To fix, use\nif i and not i.isspace()\n\nas your listcomp's condition (so this only succeeds for non-empty, non-all-whitespace strings).\n", "\nsolved it...
[ 2, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003323805_list_python.txt
Q: Recursion Recursion Recursion --- How can i Improve Performance? (Python Archive Recursive Extraction) I am trying to develop a Recursive Extractor. The problem is , it is Recursing Too Much (Evertime it found an archive type) and taking a performance hit. So how can i improve below code? My Idea 1: Get the 'Dict'...
Recursion Recursion Recursion --- How can i Improve Performance? (Python Archive Recursive Extraction)
I am trying to develop a Recursive Extractor. The problem is , it is Recursing Too Much (Evertime it found an archive type) and taking a performance hit. So how can i improve below code? My Idea 1: Get the 'Dict' of direcories first , together with file types.Filetypes as Keys. Extract the file types. When an Archive i...
[ "You can simplify your extractRecursive method to use os.walk as it should be used. os.walk already reads all subdirectories so your recursion is unneeded.\nSimply remove the recursive call and it should work :)\ndef extractRecursive(path, archives, extracted_archives=None):\n i = 0\n if not extracted_archive...
[ 1, 1 ]
[]
[]
[ "archive", "extract", "generator", "python", "recursion" ]
stackoverflow_0003323829_archive_extract_generator_python_recursion.txt
Q: python mysqldb cursor messages list shows errors twice For some reason whenever i run a query on the db cursor, it generates two errors in its .messages list, is this a feature? here is the code that runs the query, all the application does is open a connection to the db, run this once with a forced error, read th...
python mysqldb cursor messages list shows errors twice
For some reason whenever i run a query on the db cursor, it generates two errors in its .messages list, is this a feature? here is the code that runs the query, all the application does is open a connection to the db, run this once with a forced error, read the .messages, then exit import MySQLdb class dbobject: d...
[ "Perhaps you can post the message(s) you receive. \n\nmysql_insert_etc.py:22: Warning: Data\n truncated for column 'val' at row 1\n self.cursor.execute(query, args)\n (,\n ('Warning', 1265L, \"Data truncated for\n column 'val' at row 1\"))\n\nFrom the above (manufactured error) it appears that MySQLdb returns...
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003323918_mysql_python.txt
Q: Is Python's ctypes.c_long 64 bit on 64 bit systems? In C, long is 64 bit on a 64 bit system. Is this reflected in Python's ctypes module? A: The size of long depends on the memory model. On Windows (LLP64) it is 32-bit, on UNIX (LP64) it is 64-bit. If you need a 64-bit integer, use c_int64. If you need a pointe...
Is Python's ctypes.c_long 64 bit on 64 bit systems?
In C, long is 64 bit on a 64 bit system. Is this reflected in Python's ctypes module?
[ "The size of long depends on the memory model. On Windows (LLP64) it is 32-bit, on UNIX (LP64) it is 64-bit.\nIf you need a 64-bit integer, use c_int64. \nIf you need a pointer-sized integer, use c_void_p (“The value is represented as integer”).\n", "Actually no.\nOn a Windows 64-bit system, long is 32 bits.\nPyt...
[ 10, 4, 2, 1 ]
[]
[]
[ "64_bit", "ctypes", "python" ]
stackoverflow_0003323778_64_bit_ctypes_python.txt
Q: python : tracking change in class to save it at the end class A(object): def __init__(self): self.db = create_db_object() def change_Db_a(self): self.db.change_something() self.db.save() def change_db_b(self): self.db.change_anotherthing() self.db.save() I...
python : tracking change in class to save it at the end
class A(object): def __init__(self): self.db = create_db_object() def change_Db_a(self): self.db.change_something() self.db.save() def change_db_b(self): self.db.change_anotherthing() self.db.save() I am getting object from database, I changing it in multiple f...
[ "Don't rely on the __del__ method for saving your object. For details, see this blog post.\nYou can use use the context management protocol by defining __enter__ and __exit__ methods:\nclass A(object):\n def __enter__(self):\n print 'enter'\n # create database object here (or in __init__)\n ...
[ 3, 1 ]
[]
[]
[ "class", "object", "python" ]
stackoverflow_0003324317_class_object_python.txt
Q: Perforce P4Python API Bug I am compiling on Ubuntu 10.04 LTS. The Perforce Python API uses their C++ API for some of it. So, I point the setup.py at the C++'s API directory using the --apidir= they say to use. When it starts to compile the C++, I get a whole load of errors (temporary error list link is now gone). ...
Perforce P4Python API Bug
I am compiling on Ubuntu 10.04 LTS. The Perforce Python API uses their C++ API for some of it. So, I point the setup.py at the C++'s API directory using the --apidir= they say to use. When it starts to compile the C++, I get a whole load of errors (temporary error list link is now gone). No one else has had these error...
[ "Woops! Forgot I still needed to install python-dev... \n" ]
[ 0 ]
[]
[]
[ "c++", "perforce", "python" ]
stackoverflow_0003324490_c++_perforce_python.txt
Q: Delaying execution of code? I'm sorry if my title is a little unclear. Basically I want to print a '.' every second for five seconds then execute a chunk of code. Here is what I tried: for iteration in range(5) : timer = threading.Timer(1.0, print_dot) timer.start() #Code chunk It seems as though that Tim...
Delaying execution of code?
I'm sorry if my title is a little unclear. Basically I want to print a '.' every second for five seconds then execute a chunk of code. Here is what I tried: for iteration in range(5) : timer = threading.Timer(1.0, print_dot) timer.start() #Code chunk It seems as though that Timer starts its own thread for ever...
[ "Use time.sleep().\nhttp://docs.python.org/library/time.html#time.sleep\n", "Your example queues up 5 timers and starts them all (relatively) at once.\nInstead, chain the timers. Pseudo-code (since I hardly know python):\niterationCount = 0\nfunction execute_chained_print_dot:\n if iterationCount < 5\n itera...
[ 3, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003324604_multithreading_python.txt
Q: How to unique a dict by value? I want to unique duplicate values in a dict. It looks like this: d = { "a":1, "b":2, "c":2, "d":3, "e":4, "f":5, "g":1, "h":2, "i":2, "j":1, "k":1} Here is what I did: # sort and unique the dict values obj = d.values() K = [] K = sorted(list(zip(*[(x,K.append(x)) for x in obj if not...
How to unique a dict by value?
I want to unique duplicate values in a dict. It looks like this: d = { "a":1, "b":2, "c":2, "d":3, "e":4, "f":5, "g":1, "h":2, "i":2, "j":1, "k":1} Here is what I did: # sort and unique the dict values obj = d.values() K = [] K = sorted(list(zip(*[(x,K.append(x)) for x in obj if not x in K])[0] V=[] for v1 in L: ...
[ "\nA dict is not a sequence. There is no ordering.\nYou need a simpler overall approach.\nA dict does not give a \"key conflict error\". It assumes that you want to overwrite the old value with the new value.\nI don't understand what you're asking here.\n\nThe solution below is a more straightforward way of removin...
[ 3, 2, 1 ]
[]
[]
[ "dictionary", "duplicates", "python", "unique" ]
stackoverflow_0003253716_dictionary_duplicates_python_unique.txt
Q: in django how do I create a queryset to find double barrel names? In django, I have a table of people, each of which has a namefirst and namelast. I want to do the sql: select * from names where left(namefirst,1)=left(namelast,1). Right now my best effort is qs=People.objects.extra(select={'db':'select left(na...
in django how do I create a queryset to find double barrel names?
In django, I have a table of people, each of which has a namefirst and namelast. I want to do the sql: select * from names where left(namefirst,1)=left(namelast,1). Right now my best effort is qs=People.objects.extra(select={'db':'select left(namefirst,1)=left(namelast,1)'}) but then if i stick a .filter(db=1) on ...
[ "Your extra parameter doesn't look right. You should be using the where parameter (not select):\nPeople.objects.extra(where=['left(namefirst,1)=left(namelast,1)'])\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_queryset", "python" ]
stackoverflow_0003324733_django_django_models_django_queryset_python.txt
Q: XML reading using ElementTree I have one xml file. <Item>Item value</Item> <Itemdate>24/07/2010</Itemdate> <Total>1</Total> <Itemcategory>Income</Itemcategory> <GroupName>Salary</GroupName> <EditId>undefined</EditId> <Item>Item value</Item> <Itemdate>24/07/2010</Itemdate> <Total>1</Total> <Itemcategory>Income</I...
XML reading using ElementTree
I have one xml file. <Item>Item value</Item> <Itemdate>24/07/2010</Itemdate> <Total>1</Total> <Itemcategory>Income</Itemcategory> <GroupName>Salary</GroupName> <EditId>undefined</EditId> <Item>Item value</Item> <Itemdate>24/07/2010</Itemdate> <Total>1</Total> <Itemcategory>Income</Itemcategory> <GroupName>Salary</...
[ "As sje397 wrote in the comment, you should restructure it if you have an option. Either put it all into item tags:\n<item>\n <value>...</value>\n <date>...</date>\n ...\n</item>\n\nOr using attributes:\n<item value=\"...\" date=\"...\" ... />\n\nThose are largely equivalent (attributes an appear in any or...
[ 5 ]
[]
[]
[ "elementtree", "python" ]
stackoverflow_0003324665_elementtree_python.txt
Q: XML GUI in Python I'm working on a project where someone wrote a PyGTK GUI that uses docks from GDL. He has the GUI saved as an XML file: <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <object class="GtkUIManager" id="uimanager"/> <object class="GtkWindow" id="mainWindow"> <prope...
XML GUI in Python
I'm working on a project where someone wrote a PyGTK GUI that uses docks from GDL. He has the GUI saved as an XML file: <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <object class="GtkUIManager" id="uimanager"/> <object class="GtkWindow" id="mainWindow"> <property name="title" transl...
[ "This seems to be a GtkBuilder file. You can use it, e.g.\nbuilder = gtk.Builder()\nbuilder.add_from_file(\"gui_layout.xml\")\n\nwindow = builder.get_object(\"mainWindow\")\n\n" ]
[ 0 ]
[]
[]
[ "dock", "gtk", "python" ]
stackoverflow_0003302676_dock_gtk_python.txt
Q: Django manytomany, imageField and upload_to I have the two models shown below: class EntryImage(models.Model): image = models.ImageField(upload_to="entries") class Entry(models.Model): code = models.CharField(max_length=70, unique=True) images = models.ManyToManyField(EntryImage, null=True, blan...
Django manytomany, imageField and upload_to
I have the two models shown below: class EntryImage(models.Model): image = models.ImageField(upload_to="entries") class Entry(models.Model): code = models.CharField(max_length=70, unique=True) images = models.ManyToManyField(EntryImage, null=True, blank=True) As you can see, Entry can have 0 or more...
[ "Well without going too far off, you could make an intermediary M2M table EntryImageDir with the directory name in it. You would link your EntryImages there with a foreign key and you could create the EntryImageDir either with a signal on Entry create or when uploading something.\nThe documentation for M2M with cus...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002647065_django_python.txt
Q: Which technology should I use to develop a high performance web application I have couple of ideas in my brain which I would like to bring out before it's too late. Basically I want to develop a web application which I could sell it to clients. So which technology shall I use to accomplish this? I have been a C an...
Which technology should I use to develop a high performance web application
I have couple of ideas in my brain which I would like to bring out before it's too late. Basically I want to develop a web application which I could sell it to clients. So which technology shall I use to accomplish this? I have been a C and C++ software developer but it's been a very long time since I have developed on...
[ "Usually the programming language doesn't really matter. All have their own strengths and weaknesses. All come up with their own best-practices and frameworks.\nIt's really up to you what's your preference. If you are coming from Microsoft C/C++ I'd use .NET, if you are from Linux world I'd use Java.\nBack in the ...
[ 6, 3, 3, 1, 0 ]
[]
[]
[ "c#", "java", "python" ]
stackoverflow_0003324683_c#_java_python.txt
Q: Declaring members only in constructor I'm coming from a C++ background to python I have been declaring member variables and setting them in a C++esqe way like so: class MyClass: my_member = [] def __init__(self,arg_my_member): self.my_member = arg_my_member Then I noticed in some open source code...
Declaring members only in constructor
I'm coming from a C++ background to python I have been declaring member variables and setting them in a C++esqe way like so: class MyClass: my_member = [] def __init__(self,arg_my_member): self.my_member = arg_my_member Then I noticed in some open source code, that the initial declaration my_member = ...
[ "The way you are doing it means that you'll now have a \"static\" member and a \"non-static\" member of the same name.\nclass MyClass:\n my_member = []\n\n def __init__(self, arg_my_member):\n self.my_member = arg_my_member\n\n\n>>> a = MyClass(42)\n>>> print a.my_member\n42\n>>> print MyClass.my_membe...
[ 9, 4, 1, 0 ]
[]
[]
[ "constructor", "member", "python" ]
stackoverflow_0003324697_constructor_member_python.txt
Q: python file copying Is there any difference in speed of copying files from one location to another betwen python or delphi or c++ ? I guess that all 3 laguages uses same or similar win api calls and that there is not much performance difference. A: Pythons shutil module does not use the Windows API, but instead...
python file copying
Is there any difference in speed of copying files from one location to another betwen python or delphi or c++ ? I guess that all 3 laguages uses same or similar win api calls and that there is not much performance difference.
[ "Pythons shutil module does not use the Windows API, but instead uses an open/read/write loop. This may or may not be slower than using CopyFile(Ex). Please measure it, everything else is just guessing.\n" ]
[ 1 ]
[]
[]
[ "comparison", "performance", "python", "windows" ]
stackoverflow_0003324870_comparison_performance_python_windows.txt
Q: PHP devs that moved to Python, is the experience better? I'm planning on moving to Python and I have a couple of additional questions along with the title: did you have more fun with python? are you as productive as when you're using PHP? what made you change to python? Would you do a project again in PHP? If so,...
PHP devs that moved to Python, is the experience better?
I'm planning on moving to Python and I have a couple of additional questions along with the title: did you have more fun with python? are you as productive as when you're using PHP? what made you change to python? Would you do a project again in PHP? If so, why? Your answers would really be useful for us PHP devs wan...
[ "I was a PHP dev for about 5 years before switching to Python almost exclusively a year ago. The experience has been a mostly positive one; I'll answer your questions but also list a few gotchas I ran into.\n\nDefinitely. I continually find surprisingly powerful features/expressions in Python that do a great deal i...
[ 19, 4, 3, 3, 2, 1, 1, 1 ]
[]
[]
[ "php", "python" ]
stackoverflow_0003319261_php_python.txt
Q: Bug in third-party dependency creates python packaging dilemma I'm a developer on a software project for Linux that uses Python and PyGTK. The program we are writing depends on a number of third-party packages that are available through all mayor distro repositories. One of these is a python binding (written in C)...
Bug in third-party dependency creates python packaging dilemma
I'm a developer on a software project for Linux that uses Python and PyGTK. The program we are writing depends on a number of third-party packages that are available through all mayor distro repositories. One of these is a python binding (written in C) that allows our program to chat with a common C library. Unfortunat...
[ "As long as the ugly hack works, use it. It will have drawbacks local to your package. Additionally, you can phase it out (significantly) later by requiring a bug-free version of your dependency, when it is released and is available for some time so that distros have a chance to start shipping it.\n" ]
[ 3 ]
[]
[]
[ "linux", "packaging", "python", "repository" ]
stackoverflow_0003325161_linux_packaging_python_repository.txt
Q: What are some good free parsing programs? Are there any good free parsing programs out there in Python or Java? I have been using a lot of textfiles recently and they are all different. I have been spending a lot of time writing code to parse these textfiles. I was wondering if there is some program that could get...
What are some good free parsing programs?
Are there any good free parsing programs out there in Python or Java? I have been using a lot of textfiles recently and they are all different. I have been spending a lot of time writing code to parse these textfiles. I was wondering if there is some program that could get all the names of a person out of a textfile or...
[ "Pyparsing is a good Python add-on module for plain text. Easy to get something going quickly, but has enough supporting components to do some pretty elaborate parsing work. See http://pyparsing.wikispaces.com, and check out the Examples page. (Plus it is very liberally licensed, so there are no restrictions or ...
[ 4, 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "java", "parsing", "python" ]
stackoverflow_0003320161_java_parsing_python.txt
Q: Stoping generator in first answer, use return instead I am using too much to my taste the pattern (after every possible solution branch of the search). This is the code to find boggle words in given square. It had a bug if the words are not preselected to include only those whose letter pairs are neighbours, which...
Stoping generator in first answer, use return instead
I am using too much to my taste the pattern (after every possible solution branch of the search). This is the code to find boggle words in given square. It had a bug if the words are not preselected to include only those whose letter pairs are neighbours, which I fixed now by changing comparrision not pos to pos is Non...
[ "Why do you make it a generator in the first place when you only want one answer? Just search for answers and return the first one instead of yielding it.\n", "return iter([anwser])\n\n" ]
[ 3, 1 ]
[]
[]
[ "prolog", "prolog_cut", "python", "yield" ]
stackoverflow_0003325045_prolog_prolog_cut_python_yield.txt
Q: How to re-read in the last point ! python how to read txt file and stop then continue at last read line example: Joe LOley Hana fat oh beef come one example = the txt file and that last line i had read it is Hana fat so how i can continue ? like that: #!/usr/bin/python #this script name is x.py don't forget that ...
How to re-read in the last point ! python
how to read txt file and stop then continue at last read line example: Joe LOley Hana fat oh beef come one example = the txt file and that last line i had read it is Hana fat so how i can continue ? like that: #!/usr/bin/python #this script name is x.py don't forget that import os f= open("Str1k3r.txt", "r") for pwd ...
[ "you might want to try using seek(), tell() etc... See the documents for more.\n", "f= open(\"Str1k3r.txt\", \"r\")\nfor line in f:\n print line\n break\n\nfor line in f:\n print line # Continues with line 2 as f knows where it stopped\n break # It's actually using file.next()\n\n", "Every time...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003325308_python.txt
Q: Emailing admin when a 500 error occurs How can I send an email to admin when a 500 error occurs, in python. The web framework I'm using is 'bottle'. A: Just use the @error(code) decorator to define an error handling page, like so: from bottle import run, error, route @error(500) def handle_500_error(code): # ...
Emailing admin when a 500 error occurs
How can I send an email to admin when a 500 error occurs, in python. The web framework I'm using is 'bottle'.
[ "Just use the @error(code) decorator to define an error handling page, like so:\nfrom bottle import run, error, route\n\n@error(500)\ndef handle_500_error(code):\n # add mail send code here\n return \"Error message here\"\n\n@route(\"/test_500\")\ndef cause_error():\n raise Exception\n\nrun()\n\nJust navigate to...
[ 8, 1 ]
[]
[]
[ "bottle", "python" ]
stackoverflow_0003324743_bottle_python.txt
Q: What is the relation between PATH_MAX and NAME_MAX, and how do I obtain? In limits.h, and in various places in the POSIX manpages, there are references to PATH_MAX and NAME_MAX. How do these relate to one another? Where is the official documentation for them? How can I obtain them at run time, and (where relevant)...
What is the relation between PATH_MAX and NAME_MAX, and how do I obtain?
In limits.h, and in various places in the POSIX manpages, there are references to PATH_MAX and NAME_MAX. How do these relate to one another? Where is the official documentation for them? How can I obtain them at run time, and (where relevant) compile time for the C, Python, and GNU (shell) environments?
[ "PATH_MAX is the maximum length of a filesystem path. NAME_MAX is the maximum length of a filename (in a particular spot). So, /foo/bar is restricted by PATH_MAX, and only the bar portion has its length limited by NAME_MAX.\nYou can get these at run time via pathconf, as _PC_PATH_MAX and _PC_NAME_MAX, although st...
[ 6 ]
[]
[]
[ "c", "gnu", "limits", "posix", "python" ]
stackoverflow_0003325602_c_gnu_limits_posix_python.txt
Q: How to cache username and passwd in pysvn here is my code #!/usr/bin/python # -*- coding:utf-8 -*- import sys import pysvn def main(): client = pysvn.Client() client.callback_get_login = lambda realm, username, may_save:(True, "myusername", "mypasswd", True) print client.cat('http://svn.mydomain.com/fi...
How to cache username and passwd in pysvn
here is my code #!/usr/bin/python # -*- coding:utf-8 -*- import sys import pysvn def main(): client = pysvn.Client() client.callback_get_login = lambda realm, username, may_save:(True, "myusername", "mypasswd", True) print client.cat('http://svn.mydomain.com/file1.py') print client.cat('http://svn.mydom...
[ "Looks like (bug hypothesis number one) the configuration directory might be not writable -- try passing an explicit path to a known-to-be-writable config dir when you call Client.\nIf that doesn't help (bug hypothesis number two) it may be that the serving is sending different realms for the two files (the fact th...
[ 1 ]
[]
[]
[ "pysvn", "python" ]
stackoverflow_0003325489_pysvn_python.txt
Q: Noob Question: Python + Twitter + App Engine - Oauth I'm sorry but I'm having some trouble implementing Oauth within my app engine python project. I've been working from http://github.com/tav/tweetapp, but I don't think I have a strong enough grasp on this platform to understand how to implement this class within ...
Noob Question: Python + Twitter + App Engine - Oauth
I'm sorry but I'm having some trouble implementing Oauth within my app engine python project. I've been working from http://github.com/tav/tweetapp, but I don't think I have a strong enough grasp on this platform to understand how to implement this class within my main.py I'm building the rest of my app in. This maybe ...
[ "Let me recommend taking a look at the tweepy library and some example tweepy apps. Specifically here: http://github.com/wasauce/tweepy-examples\nThis shows how to use oauth to authenticate a user: http://github.com/wasauce/tweepy-examples/tree/master/appengine/oauth_example/\n", "As Hagge said, it sounds like yo...
[ 1, 1, 1, 0 ]
[]
[]
[ "google_app_engine", "pydev", "python", "twitter" ]
stackoverflow_0003305701_google_app_engine_pydev_python_twitter.txt
Q: Python: Accessing Values For Dict Key Made Using Variables Hi I've been coding a console version of Minesweeper just to learn some of the basics of Python. It uses a coordinate system that is recorded in a dictionary. Now, I have been able to implement it successfully but accessing or assigning a value to a specif...
Python: Accessing Values For Dict Key Made Using Variables
Hi I've been coding a console version of Minesweeper just to learn some of the basics of Python. It uses a coordinate system that is recorded in a dictionary. Now, I have been able to implement it successfully but accessing or assigning a value to a specific coordinate key using variables for the "x,y" of the coordinat...
[ "Why not simply use a tuple as the key?\nfor i in range(1, ROWS+1):\n for j in range(1, COLS+1):\n mine_field[(i, j)] = 0 # you don't even need the parentheses!\n\nUsing this method, you can use comma-separated indices like so:\nd = {(1,2):3}\nprint d[1, 2] # will print 3\n\nAnd BTW why are you using one-...
[ 5, 1 ]
[]
[]
[ "dictionary", "key", "python", "variables" ]
stackoverflow_0003325719_dictionary_key_python_variables.txt
Q: Use of properties in python like in example C# I currently work with Python for a while and I came to the point where I questioned myself whether I should use "Properties" in Python as often as in C#. In C# I've mostly created properties for the majority of my classes. It seems that properties are not that popular...
Use of properties in python like in example C#
I currently work with Python for a while and I came to the point where I questioned myself whether I should use "Properties" in Python as often as in C#. In C# I've mostly created properties for the majority of my classes. It seems that properties are not that popular in python, am I wrong? How to use properties in Pyt...
[ "Properties are often no required if all you do is set and query member variables. Because Python has no concept of encapsulation, all member variables are public and often there is no need to encapsulate accesses. However, properties are possible, perfectly legitimate and popular:\nclass C(object):\n def __init...
[ 15, 7, 2 ]
[]
[]
[ "c#", "properties", "python" ]
stackoverflow_0003324920_c#_properties_python.txt
Q: Python list, lookup object name, efficiency advice Suppose I have the following object: class Foo(object): def __init__(self, name=None): self.name = name def __repr__(self): return self.name And a list containing multiple instances, such as: list = [Foo(name='alice'), Foo(name='bob'), Foo(name='char...
Python list, lookup object name, efficiency advice
Suppose I have the following object: class Foo(object): def __init__(self, name=None): self.name = name def __repr__(self): return self.name And a list containing multiple instances, such as: list = [Foo(name='alice'), Foo(name='bob'), Foo(name='charlie')] If I want to find an object with a given name, I...
[ "Try this for size:\nclass Foo(object):\n _all_names = {}\n def __init__(self, name=None):\n self.name = name\n @property\n def name(self):\n return self._name\n @name.setter\n def name(self, name):\n self._name = name\n self._all_names[name] = self\n @classmethod\n ...
[ 8, 1 ]
[]
[]
[ "algorithm", "list", "list_comprehension", "performance", "python" ]
stackoverflow_0003325711_algorithm_list_list_comprehension_performance_python.txt
Q: python matplotlib will only plot integers I'm very new to python. two days. trying to get a plot working with matplotlib. I'm getting this error: cannot perform reduce with flexible type the line with the error is: ax.scatter(x,y,z,marker='o') Variables: ax is defined as: ax = Axes3D(fig) fig is defined as: fig...
python matplotlib will only plot integers
I'm very new to python. two days. trying to get a plot working with matplotlib. I'm getting this error: cannot perform reduce with flexible type the line with the error is: ax.scatter(x,y,z,marker='o') Variables: ax is defined as: ax = Axes3D(fig) fig is defined as: fig = plt.figure() x, y, z are lists Any python ...
[ "Compare your code with this basic scatter plot code. Notice that there xs,ys,zs are ndarrays of floats. Does that code work for you? Maybe you can incrementally morph that code into your own to get code that works (or learn where yours breaks).\nIf that doesn't help, perhaps post enough code to allow us to reprodu...
[ 3, 1 ]
[]
[]
[ "integer", "matplotlib", "plot", "python" ]
stackoverflow_0003323185_integer_matplotlib_plot_python.txt
Q: Common convention for invoking unit tests across a python project? Is there a standard convention, or even a growing one, around where and how to invoke the tests associated with a project? In many projects, I'm seeing it bundled into a Make, a separate test.py script at the top level of the project, etc to do the...
Common convention for invoking unit tests across a python project?
Is there a standard convention, or even a growing one, around where and how to invoke the tests associated with a project? In many projects, I'm seeing it bundled into a Make, a separate test.py script at the top level of the project, etc to do the work.  I looked around for some common thing with setup.py, but didn't ...
[ "The short answer is yes, there's a simple convention built-in to the unittest module. See this previous question.\n" ]
[ 1 ]
[]
[]
[ "python", "testing", "unit_testing" ]
stackoverflow_0003326116_python_testing_unit_testing.txt
Q: GAE - Sharing Authentication Across Apps Let's say I had a root app and multiple sub-apps. Would it be possible to share authenticated sessions across them? I'm using Google App Engine (Python). A: If you use tipfy, the wonderful lightweight almost-not-a-framework that @moraes developed specifically for App Engi...
GAE - Sharing Authentication Across Apps
Let's say I had a root app and multiple sub-apps. Would it be possible to share authenticated sessions across them? I'm using Google App Engine (Python).
[ "If you use tipfy, the wonderful lightweight almost-not-a-framework that @moraes developed specifically for App Engine use, you get many excellent choices for authentication approaches (see here) several of which will let you achieve what you're after.\n", "Not using the built in authentication support - users ha...
[ 4, 1 ]
[]
[]
[ "authentication", "google_app_engine", "openid", "python" ]
stackoverflow_0003325906_authentication_google_app_engine_openid_python.txt
Q: How to use twisted for downloading a remote file? I'm relatively new to twisted and I'm planning on using it to create a file downloader. It would accept a file url and a number of parts to download the file. What I have in mind is to split the file into how many parts the user specified and download each parts th...
How to use twisted for downloading a remote file?
I'm relatively new to twisted and I'm planning on using it to create a file downloader. It would accept a file url and a number of parts to download the file. What I have in mind is to split the file into how many parts the user specified and download each parts through deferred and when it is done, all parts gets asse...
[ "If your mention of a URL implies that the protocol in use is HTTP (and I hope HTTP 1.1;-), then you could use twisted's relatively new HTTP 1.1 client (discussed at length here, and from the fact that the issue was marked as fixed 9 months ago I assume the client is finally in -- I have not checked that), using HT...
[ 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003325871_python_twisted.txt
Q: doing textwrap and dedent in Windows Powershell (or dotNet aka .net) Background Python has "textwrap" and "dedent" functions. They do pretty much what you expect to any string you supply. textwrap.wrap(text[, width[, ...]]) Wraps the single paragraph in text (a string) so every line is at most width characters lo...
doing textwrap and dedent in Windows Powershell (or dotNet aka .net)
Background Python has "textwrap" and "dedent" functions. They do pretty much what you expect to any string you supply. textwrap.wrap(text[, width[, ...]]) Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines. textwrap.deden...
[ "This is a negligent code...\n#requires -version 2.0\n function wrap( [string]$text, [int]$width ) {\n $i=0;\n $text.ToCharArray() | group { [Math]::Floor($i/$width); (gv i).Value++ } | % { -join $_.Group }\n}\n\nfunction dedent( [string[]]$text ) {\n $i = $text | % { $_ -match \"^(\\s*)\" | Out-Null ; ...
[ 3, 1, 1 ]
[]
[]
[ ".net", "powershell", "python", "string", "text" ]
stackoverflow_0001417663_.net_powershell_python_string_text.txt
Q: Python: Detecting the actual text paragraphs in a string The big mission: I am trying to get a few lines of summary of a webpage. i.e. I want to have a function that takes a URL and returns the most informative paragraph from that page. (Which would usually be the first paragraph of actual content text, in contras...
Python: Detecting the actual text paragraphs in a string
The big mission: I am trying to get a few lines of summary of a webpage. i.e. I want to have a function that takes a URL and returns the most informative paragraph from that page. (Which would usually be the first paragraph of actual content text, in contrast to "junk text", like the navigation bar.) So I managed to re...
[ "A general solution to this problem is a non-trivial problem to solve.\nTo put this in context, a large part of Google's success with search has come from their ability to automatically discern some semantic meaning from arbitrary Web pages, namely figuring out where the \"content\" is.\nOne idea that springs to mi...
[ 2, 2, 1, 0 ]
[]
[]
[ "html", "python", "screen_scraping", "text" ]
stackoverflow_0003325817_html_python_screen_scraping_text.txt
Q: GAE + Python vs Webfaction + Python + django - for a relative new dev Basically I have a webfaction space (assume for the purposes of this question that its free). I am trying to learn python by created some simple web applications on Google App Engine using Eclipse + Pydev for development. So far I have some basi...
GAE + Python vs Webfaction + Python + django - for a relative new dev
Basically I have a webfaction space (assume for the purposes of this question that its free). I am trying to learn python by created some simple web applications on Google App Engine using Eclipse + Pydev for development. So far I have some basic functionality working in App Engine, though I have had some frustration w...
[ "\nI am trying to learn python by created\n some simple web applications on Google\n App Engine using Eclipse + Pydev for\n development.\n\nThis seems reasonable. Nothing wrong with using GAE, Eclipse, and Pydev to learn to do Python web dev.\n\nSo far I have some basic functionality\n working in App Engine, t...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003326308_google_app_engine_python.txt
Q: How to properly columnize tables in a Django template I am currently trying to break a list of people (aprox 20 to 30 items) into a table with 4 columns. Here is my current code. <table> {% for person in people %} {% cycle "<tr><td>" "<td>" "<td>" "<td>" %} {{ person }} {% cycle "</td>" "</td>" "</...
How to properly columnize tables in a Django template
I am currently trying to break a list of people (aprox 20 to 30 items) into a table with 4 columns. Here is my current code. <table> {% for person in people %} {% cycle "<tr><td>" "<td>" "<td>" "<td>" %} {{ person }} {% cycle "</td>" "</td>" "</td>" "</td></tr>" %} {% endfor %} </table> Obviously, this...
[ "Use the divisibleby filter.\n<tr>\n{% for person in people %}\n <td>{{ person }}</td>\n {% if forloop.counter|divisibleby:4 and not forloop.last %}</tr><tr>{% endif %}\n{% endfor %}\n</tr>\n\n" ]
[ 11 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003326514_django_django_templates_python.txt
Q: Python: Error in MySQL import MySQLdb import random db = MySQLdb.connect (host = "localhost", user = "python-test", passwd = "python", db = "python-test") cursor = db.cursor() var = .3 sql = "INSERT INTO RandomInt (RAND) VALUES (var)" # RandomInt is the name of the table and Ran...
Python: Error in MySQL
import MySQLdb import random db = MySQLdb.connect (host = "localhost", user = "python-test", passwd = "python", db = "python-test") cursor = db.cursor() var = .3 sql = "INSERT INTO RandomInt (RAND) VALUES (var)" # RandomInt is the name of the table and Rand is the Column Name cursor...
[ "As written, var is being sent to MySQL as a string.\nGive this a shot instead:\nsql = \"INSERT INTO RandomInt (RAND) VALUES (%s)\"\ncursor.execute(sql, (var,))\n\nEdit:\n>>> import MySQLdb\n>>> MySQLdb.paramstyle\n'format'\n\nMySQLdb's paramstyle is format; which, according to the DB-API is %s:\n\n 'for...
[ 5, 1, 1, 0 ]
[]
[]
[ "mysql", "mysql_error_1054", "python" ]
stackoverflow_0003327188_mysql_mysql_error_1054_python.txt
Q: How can I enumerate filesystems from Python? I'm using os.statvfs to find out the free space available on a volume -- in addition to querying free space for a particular path, I'd like to be able to iterate over all volumes. I'm working on Linux at the moment, but ideally would like something which returns ["/", ...
How can I enumerate filesystems from Python?
I'm using os.statvfs to find out the free space available on a volume -- in addition to querying free space for a particular path, I'd like to be able to iterate over all volumes. I'm working on Linux at the moment, but ideally would like something which returns ["/", "/boot", "home"] on Linux and ["C:\", "D:\"] on Wi...
[ "For Linux how about parsing /etc/mtab or /proc/mounts? Or:\nimport commands\n\nmount = commands.getoutput('mount -v')\nlines = mount.split('\\n')\npoints = map(lambda line: line.split()[2], lines)\n\nprint points\n\nFor Windows I found something like this:\nimport string\nfrom ctypes import windll\n\ndef get_drive...
[ 3 ]
[]
[]
[ "filesystems", "linux", "python", "windows" ]
stackoverflow_0003327528_filesystems_linux_python_windows.txt
Q: Monitor Yahoo! Instant Messages in Python? I am trying to add some security to my computer at home and would like to have a copy of all Yahoo! IMs sent to me. I am using Python 2.6 on Windows. I would also like to have every URL in Internet Explorer sent to me. A: Wireshark has custom filters for chat protocols ...
Monitor Yahoo! Instant Messages in Python?
I am trying to add some security to my computer at home and would like to have a copy of all Yahoo! IMs sent to me. I am using Python 2.6 on Windows. I would also like to have every URL in Internet Explorer sent to me.
[ "Wireshark has custom filters for chat protocols like yahoo or to filter for all HTTP traffic. I don't know why you would want to filter only IE, its not the most common browser but you could probably filter by user agent. Wireshark can be invoked on the commandline and you can tap into these pre-built filters. ...
[ 0 ]
[]
[]
[ "internet_explorer_8", "python", "security", "windows", "yahoo_messenger" ]
stackoverflow_0002893395_internet_explorer_8_python_security_windows_yahoo_messenger.txt
Q: Control access to parts of a system, but also to certain pieces of information This is a tricky question, we've been talking about this for a while (days) and haven't found a convincingly good solution. This is the situation: We have users and groups. A user can belong to many groups (many to many relation) There...
Control access to parts of a system, but also to certain pieces of information
This is a tricky question, we've been talking about this for a while (days) and haven't found a convincingly good solution. This is the situation: We have users and groups. A user can belong to many groups (many to many relation) There are certain parts of the site that need access control, but: There are certain ROWS...
[ "This problem is not really new; it's basically the general problem of authorization and access rights/control.\nIn order to avoid having to model and maintain a complete graph of exactly what objects each user can access in each possible way, you have to make decisions (based on what your application does) about h...
[ 2, 1, 0, 0 ]
[]
[]
[ "access_control", "python" ]
stackoverflow_0003327279_access_control_python.txt
Q: Crossplatform method for inserting text into raw_input (to avoid readine) in Python I have an application (CLI) which includes the feature of editing account information. It does this by asking a question and putting in the old value in the answer so that it is editable. Currently I'm using the readline module to ...
Crossplatform method for inserting text into raw_input (to avoid readine) in Python
I have an application (CLI) which includes the feature of editing account information. It does this by asking a question and putting in the old value in the answer so that it is editable. Currently I'm using the readline module to do this. I'd like another way of doing the same thing that avoids this module (I want to ...
[ "Line editing functionality is far from trivial to duplicate. For example, just a functionality such as \"read the next keystroke without echoing\" (even before you start intepreting the meaning of that keystroke in order to reposition the cursor and alter the on-screen appearance as well as the remembered content...
[ 1, 0 ]
[]
[]
[ "python", "readline" ]
stackoverflow_0003327524_python_readline.txt
Q: Django standalone run in cron I want to run automatic newsletter function in my crontab, but no matter what I try - I cannot make it work. What is the proper method for doing this ? This is my crontab entry : 0 */2 * * * PYTHONPATH=/home/muntu/rails python2.6 /home/muntu/rails/project/newsletter.py And the newsle...
Django standalone run in cron
I want to run automatic newsletter function in my crontab, but no matter what I try - I cannot make it work. What is the proper method for doing this ? This is my crontab entry : 0 */2 * * * PYTHONPATH=/home/muntu/rails python2.6 /home/muntu/rails/project/newsletter.py And the newsletter.py file, which is located in t...
[ "Try changing your cron entry to:\n0 */2 * * * cd /home/muntu/rails && python2.6 /home/muntu/rails/project/newsletter.py\n\nThis will ensure that the \"rails\" directory is in python's path. If you want to set the PYTHONPATH, then create a shell script:\n#!/bin/sh\nexport PYTHONPATH=/home/muntu/rails\npython2.6 /h...
[ 1 ]
[]
[]
[ "cron", "django", "django_settings", "python" ]
stackoverflow_0003327695_cron_django_django_settings_python.txt
Q: Python script to do a GET request on 2 urls in a cron job I need a python script to perform a GET request on 2 urls. I will use these scripts in a cron job on my ubuntu server. The catch is, the 2 calls have to happen sequentially because the first GET request to Url#1 might take up to 1 minute or so to complete. ...
Python script to do a GET request on 2 urls in a cron job
I need a python script to perform a GET request on 2 urls. I will use these scripts in a cron job on my ubuntu server. The catch is, the 2 calls have to happen sequentially because the first GET request to Url#1 might take up to 1 minute or so to complete. For the cron job, I want it to run every 30 minutes.
[ "I'm not sure if I'm missing something in your question. But it should be fairly simple with urllib2:\nimport urllib2\n\nrequest = urllib2.Request('http://example.com/path')\nresponse = urllib2.urlopen(request)\ncontent = response.read()\n\n# now make the second request, just as above\n\nSee the page, urllib2 The ...
[ 3, 0 ]
[]
[]
[ "cron", "python" ]
stackoverflow_0003327252_cron_python.txt
Q: Can the execution of statements in Python be delayed? I want it to run the first line print 1 then wait 1 second to run the second command print 2, etc. Pseudo-code: print 1 wait(1 seconds) print 2 wait(0.45 seconds) print 3 wait(3 seconds) print 4 A: time.sleep(seconds) import time print 1 time.sleep(1) print ...
Can the execution of statements in Python be delayed?
I want it to run the first line print 1 then wait 1 second to run the second command print 2, etc. Pseudo-code: print 1 wait(1 seconds) print 2 wait(0.45 seconds) print 3 wait(3 seconds) print 4
[ "time.sleep(seconds)\nimport time\n\nprint 1\ntime.sleep(1)\nprint 2\ntime.sleep(0.45)\nprint 3\ntime.sleep(3)\nprint 4\n\n", "All the answers have assumed that you want or can manually insert time.sleep after each line, but may be you want a automated way to do that for a large number of lines of code e.g. consi...
[ 47, 16, 5 ]
[]
[]
[ "delay", "python", "sleep", "timing" ]
stackoverflow_0003327775_delay_python_sleep_timing.txt
Q: Best Twitter Framework for Python on App Engine? I'm looking to incorporate twitter API features into an app engine project that I'm working on. I'm relatively new to both app engine and python, so I'm wondering what modules/frameworks I should use to most easily incorporate twitter, and to facilitate twitter oaut...
Best Twitter Framework for Python on App Engine?
I'm looking to incorporate twitter API features into an app engine project that I'm working on. I'm relatively new to both app engine and python, so I'm wondering what modules/frameworks I should use to most easily incorporate twitter, and to facilitate twitter oauth? I've seen: python-twitter tipfy gaema
[ "I heartily recomment tipfy, but, as its author @moraes just said, it is its own, little, lightweight framework -- integration with others is possible (through WSGI middleware concepts), but your life is much simpler if you stick with a single framework, and django is much richer (and, of course, much bigger and le...
[ 4, 3, 3, 1 ]
[]
[]
[ "google_app_engine", "python", "twitter" ]
stackoverflow_0003325935_google_app_engine_python_twitter.txt
Q: Using Ruby, Perl, or Python, how to "Move the window 'Firefox' to coordinate (0,0) on screen and resize it 1024 x 768"? Can it be moved by Window Title as well as exe name? Other info on moving it in another language could be helpful. Update: some Perl sample can be found in Win32::GuiTest but there seems to be no...
Using Ruby, Perl, or Python, how to "Move the window 'Firefox' to coordinate (0,0) on screen and resize it 1024 x 768"?
Can it be moved by Window Title as well as exe name? Other info on moving it in another language could be helpful. Update: some Perl sample can be found in Win32::GuiTest but there seems to be no resize or move functions.
[ "Win32::API and MoveWindow. See also How do you programmatically resize and move windows with the Windows API?.\n", "Here's a way to do it in Ruby using win32-api:\n# example.rb\nrequire 'win32/api'\ninclude Win32\n\nFindWindow = API.new('FindWindow', 'PP', 'L', 'user32')\nhWnd = FindWindow.call(nil, \"firefox\")...
[ 3, 2 ]
[]
[]
[ "perl", "python", "ruby", "winapi" ]
stackoverflow_0003323672_perl_python_ruby_winapi.txt
Q: Django forms, saving non-user submitted data class SomeModel(models.Model): text = models.TextField() ip = models.IPAddressField() created_on = models.DateTimeField() updated_on = models.DateTimeField() Say I have that as a model, what if I wanted to only display 'text' field widget for the us...
Django forms, saving non-user submitted data
class SomeModel(models.Model): text = models.TextField() ip = models.IPAddressField() created_on = models.DateTimeField() updated_on = models.DateTimeField() Say I have that as a model, what if I wanted to only display 'text' field widget for the user to submit data, but I obviously wouldn't want t...
[ "Two things:\nFirst ModelForms: \nClass SomeModelForm(ModelForm):\n class Meta:\n exclude = ['ip','created_on', 'updated_on']\n\nTwo Model Fields API:\nclass SomeModel(models.Model):\n text = models.TextField()\n ip = models.IPAddressField()\n created_on = models.DateTimeField(auto_now_add=True)\n ...
[ 2 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0003328212_django_forms_python.txt
Q: Python operator precedence The Python docs say that * and / have the same precedence. I know that expressions in python are evaluated from left to right. Can i rely on that and assume that j*j/m is always equal to (j*j)/m avoiding the parentheses? If this is the case can i assume that this holds for operators with...
Python operator precedence
The Python docs say that * and / have the same precedence. I know that expressions in python are evaluated from left to right. Can i rely on that and assume that j*j/m is always equal to (j*j)/m avoiding the parentheses? If this is the case can i assume that this holds for operators with the same precedence in general?...
[ "Yes - different operators with the same precedence are left-associative; that is, the two leftmost items will be operated on, then the result and the 3rd item, and so on.\nAn exception is the ** operator:\n>>> 2 ** 2 ** 3\n256\n\nAlso, comparison operators (==, >, et cetera) don't behave in an associative manner, ...
[ 14, 14, 3 ]
[]
[]
[ "expression", "operator_precedence", "python" ]
stackoverflow_0003328355_expression_operator_precedence_python.txt
Q: Yielding until all needed values are yielded, is there way to make slice to become lazy Is there way to stop yielding when generator did not finish values and all needed results have been read? I mean that generator is giving values without ever doing StopIteration. For example, this never stops: (REVISED) from ra...
Yielding until all needed values are yielded, is there way to make slice to become lazy
Is there way to stop yielding when generator did not finish values and all needed results have been read? I mean that generator is giving values without ever doing StopIteration. For example, this never stops: (REVISED) from random import randint def devtrue(): while True: yield True answers=[False for _ i...
[ "You can call close() on the generator object. This way, a GeneratorExit exception is raised within the generator and further calls to its next() method will raise StopIteration:\n>>> def test():\n... while True:\n... yield True\n... \n>>> gen = test()\n>>> gen\n<generator object test at ...>\n>>> gen.n...
[ 8, 0, 0, 0 ]
[]
[]
[ "generator", "lazy_sequences", "python", "slice", "variable_assignment" ]
stackoverflow_0003324947_generator_lazy_sequences_python_slice_variable_assignment.txt
Q: Quick & dirt CRUD interface to SQLAlchemy? I'm researching software components to use in a future development of a business logic web application. It's gonna be written in Python and we are targeting SQLAlchemy as ORM. The app will be used by other software apps via a REST-like interface over http, possibly using ...
Quick & dirt CRUD interface to SQLAlchemy?
I'm researching software components to use in a future development of a business logic web application. It's gonna be written in Python and we are targeting SQLAlchemy as ORM. The app will be used by other software apps via a REST-like interface over http, possibly using web.py for that part. For debugging, maintenance...
[ "although the Camelot examples are based on Elixir, Camelot is not tied to Elixir, so you could as well use declarative to define your model. In fact Camelot can be used to display plain old python objects as well.\n" ]
[ 1 ]
[]
[]
[ "crud", "python", "sqlalchemy" ]
stackoverflow_0003150739_crud_python_sqlalchemy.txt
Q: Puzzle that defies the brute force approach? I bought a blank DVD to record my favorite TV show. It came with 20 digit stickers. 2 of each of '0'-'9'. I thought it would be a good idea to numerically label my new DVD collection. I taped the '1' sticker on my first recorded DVD and put the 19 leftover stickers in a...
Puzzle that defies the brute force approach?
I bought a blank DVD to record my favorite TV show. It came with 20 digit stickers. 2 of each of '0'-'9'. I thought it would be a good idea to numerically label my new DVD collection. I taped the '1' sticker on my first recorded DVD and put the 19 leftover stickers in a drawer. The next day I bought another blank DVD (...
[ "This is old solution, completely new 6 bajillion times faster solution is on the bottom.\nSolution:\ntime { python solution.py; } \n0: 0\n1: 199990\n2: 1999919999999980\n3: 19999199999999919999999970\n4: 199991999999999199999999919999999960\n5: 1999919999999991999999999199999999919999999950\n6: 1999919999999991999...
[ 7, 6, 2, 2, 1, 1 ]
[]
[]
[ "math", "puzzle", "python" ]
stackoverflow_0003324306_math_puzzle_python.txt
Q: Cannot access members of UserProperty in code I'm new to Google Apps and I've been messing around with the hello world app that is listed on the google app site. Once I finished the app, I decided to try to expand on it. The first thing I added was a feature to allow the filtering of the guestbook posts by the us...
Cannot access members of UserProperty in code
I'm new to Google Apps and I've been messing around with the hello world app that is listed on the google app site. Once I finished the app, I decided to try to expand on it. The first thing I added was a feature to allow the filtering of the guestbook posts by the user that submitted them. All I have changed/added ...
[ "When querying the Greeting model, you cannot filter on fields within Greeting.author (e.g., greeting.author.nickname). In SQL, this would be done by doing a join on the Greeting and User tables. However, in GAE you can only query properties directly included on the model you are querying.\nSince author is a db.U...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003327958_google_app_engine_python.txt
Q: Python Sorting Question i need to sort the following list of Tuples in Python: ListOfTuples = [('10', '2010 Jan 1;', 'Rapoport AM', 'Role of antiepileptic drugs as preventive agents for migraine', '20030417'), ('21', '2009 Nov;', 'Johannessen SI', 'Antiepilepticdrugs in epilepsy and other disorders--a population-b...
Python Sorting Question
i need to sort the following list of Tuples in Python: ListOfTuples = [('10', '2010 Jan 1;', 'Rapoport AM', 'Role of antiepileptic drugs as preventive agents for migraine', '20030417'), ('21', '2009 Nov;', 'Johannessen SI', 'Antiepilepticdrugs in epilepsy and other disorders--a population-based study of prescriptions',...
[ "def descyear_ascauth(atup):\n datestr = atup[1]\n authstr = atup[2]\n year = int(datestr.split(None, 1)[0])\n return -year, authstr\n\n... sorted(result, key=descyear_ascauth) ...\n\nNotes: you need to extract the year as an integer (not as a string), so that you can change its sign -- the latter being the key...
[ 4, 2, 0, 0, 0 ]
[]
[]
[ "list", "python", "sorting", "stability" ]
stackoverflow_0003325574_list_python_sorting_stability.txt
Q: How to create partial download in twisted? How do you create multiple HTTPDownloader instance with partial download asynchronously? and does it assemble the file automatically after all download is done? A: You must use Range HTTP header: Range. Request only part of an entity. Bytes are numbered from 0. Ra...
How to create partial download in twisted?
How do you create multiple HTTPDownloader instance with partial download asynchronously? and does it assemble the file automatically after all download is done?
[ "You must use Range HTTP header:\n\nRange. Request only part of an entity.\n Bytes are numbered from 0. Range:\n bytes=500-999\n\nIe. If you want download 1000 file in 4 parts, you will starts 4 downloads:\n\n0-2499\n2500-4999\n5000-7499\n7500-9999\n\nAnd then simply join data from responses.\nTo check file si...
[ 3 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003328059_python_twisted.txt
Q: Extracting semantic/stylistic features from text I would like to know of open source tools (for java/python) which could help me extract semantic & stylistic features from text. Examples of semantic features would be adjective-noun ratio, a particular sequence of part-of-speech tags (adjective followed by a noun: ...
Extracting semantic/stylistic features from text
I would like to know of open source tools (for java/python) which could help me extract semantic & stylistic features from text. Examples of semantic features would be adjective-noun ratio, a particular sequence of part-of-speech tags (adjective followed by a noun: adj|nn) etc. Examples of stylistic features would be n...
[ "I think that the Stanford Parser is one of the best and comprehensive NLP tools available for free: not only will it allow you to parse the structural dependencies (to count nouns/adjectives) but it will also give you the grammatical dependencies in the sentence (so you can extract the subject, object, etc). The ...
[ 3, 2, 1, 1, 1, 0 ]
[]
[]
[ "java", "machine_learning", "python" ]
stackoverflow_0003109773_java_machine_learning_python.txt
Q: position contents of array.array into heap I have a simple byte array I've filled with a x86 -program. Which I need to execute at runtime. """ Produces a simple callable procedure which returns a constant. """ from array import array simple = array('B') # mov rax, 0x10 simple.extend((0x81, 0xc0, 0x10, 0x0, 0...
position contents of array.array into heap
I have a simple byte array I've filled with a x86 -program. Which I need to execute at runtime. """ Produces a simple callable procedure which returns a constant. """ from array import array simple = array('B') # mov rax, 0x10 simple.extend((0x81, 0xc0, 0x10, 0x0, 0x0, 0x0)) # ret simple.append(0xc3) Now, to get...
[ "I solved this on my own. Maybe there's not much to say into it anyway.\nI did a library for this. It's a small wrapping around linux mmap -command.\nmmap module provided by python weren't sufficient. I couldn't get the address out of an object. Instead I had to provide my own module for just doing that.\n# -*- cod...
[ 1 ]
[]
[]
[ "ctypes", "memory", "python" ]
stackoverflow_0003294333_ctypes_memory_python.txt
Q: Need some ideas on how to code my log parser I have a VPS that's hosting multiple virtual hosts. Each host has it's own access.log and error.log. Currently, there's no log rotation setup, though, this may change. Basically, I want to parse these logs to monitor bandwidth and collect stats. My idea was to write a p...
Need some ideas on how to code my log parser
I have a VPS that's hosting multiple virtual hosts. Each host has it's own access.log and error.log. Currently, there's no log rotation setup, though, this may change. Basically, I want to parse these logs to monitor bandwidth and collect stats. My idea was to write a parser and save the information to a small sqlite d...
[ "Unless you create different log files for each day, you have no way other than to parse on request the whole log.\nI would still use a database to hold the log data, but with your desired time-unit resolution (eg. hold the bandwidth at a day / hour interval). Another advantage in using a database is that you can m...
[ 2, 1, 0 ]
[]
[]
[ "logging", "parsing", "python" ]
stackoverflow_0003328688_logging_parsing_python.txt
Q: Two arguments in one def? First, here's my code: import poplib def con(pwd): M = poplib.POP3_SSL('pop3.live.com', 995) try: M.user(pwd) M.pass_('!@#$%^') except: print "[-]Not Found!:",pwd else: print '[+]Found password' exit() f = open("Str1k3r.txt", "r") ...
Two arguments in one def?
First, here's my code: import poplib def con(pwd): M = poplib.POP3_SSL('pop3.live.com', 995) try: M.user(pwd) M.pass_('!@#$%^') except: print "[-]Not Found!:",pwd else: print '[+]Found password' exit() f = open("Str1k3r.txt", "r") for pwd in f.readlines(): c...
[ "Assuming, the file \"Str1k3r.txt\" contains username and password in the first two lines, what you want to do is the following:\nimport poplib\ndef con(pwd, cod):\n M = poplib.POP3_SSL('pop3.live.com', 995) \n try:\n M.user(pwd)\n M.pass_(cod)\n except:\n print \"[-]Not Found!:\",pwd\...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003328749_python.txt
Q: django and netbeans? I use netbeans for all of my Linux development (C/C++, Php, Python, Symfony). I am now learning django, and wondered if I could use netbeans as the IDE. I cant seem to find a Django plugin for netbeans. Is there one?. If no when is one planned? Worst case scenario, I'll have to use another IDE...
django and netbeans?
I use netbeans for all of my Linux development (C/C++, Php, Python, Symfony). I am now learning django, and wondered if I could use netbeans as the IDE. I cant seem to find a Django plugin for netbeans. Is there one?. If no when is one planned? Worst case scenario, I'll have to use another IDE (I really dont want to le...
[ "There is Python and Django support from the built-in Python plug-in (in short simply get any NetBeans 6.9 or more recent, go to menu Update... > Search \"Python\" > Install).\nThere is also a NetBeans-Django additional project going on but pretty dead for a while.\n", "Currently, NetBeans support for Django is ...
[ 9, 3, 0 ]
[]
[]
[ "django", "ide", "netbeans", "python" ]
stackoverflow_0002971309_django_ide_netbeans_python.txt
Q: IRC bot functionalities I'm learning Python and would like to start a small project. It seems that making IRC bots is a popular project amongst beginners so I thought I would implement one. Obviously, there are core functionalities like being able to connect to a server and join a channel but what are some good fu...
IRC bot functionalities
I'm learning Python and would like to start a small project. It seems that making IRC bots is a popular project amongst beginners so I thought I would implement one. Obviously, there are core functionalities like being able to connect to a server and join a channel but what are some good functionalities that are usuall...
[ "Unless it's solely for the educational experience, you should really just use a framework for the core functionality.\nThat said, here's some of the things the bot in my home IRC channel does:\n\nChoose one item from a list of options\nDisplay a random entry from the Linux fortunes file\nDisplay a random set of wo...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "irc", "python" ]
stackoverflow_0003328315_irc_python.txt