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: Command+W Support in wxPython It's my understanding that in wxPython in OSX, ⌘+w support for closing wx.Window objects. In order to add it, I've had to bind to wx.EVT_KEY_DOWN, checking for event.MetaDown() and event.KeyCode == 'W' explicitly. In my app, I need to have all windows and dialogs support this. I'm sti...
Command+W Support in wxPython
It's my understanding that in wxPython in OSX, ⌘+w support for closing wx.Window objects. In order to add it, I've had to bind to wx.EVT_KEY_DOWN, checking for event.MetaDown() and event.KeyCode == 'W' explicitly. In my app, I need to have all windows and dialogs support this. I'm still in the process of layout out my ...
[ "\nI was thinking maybe a class\n decorator, but this is functionality\n that will be added at runtime, due to\n the dynamic nature of python.\n\nI don't understand why this makes you \"a little stumped\". The class decorator executes just after the end of the class statement -- yes, that's \"at runtime\", but, ...
[ 0 ]
[]
[]
[ "macos", "python", "user_interface", "wxpython" ]
stackoverflow_0003765496_macos_python_user_interface_wxpython.txt
Q: using extended ascii characters for wikimedia api I am writing a simple search algorithm for wikipedia. I am having trouble when I send a query with characters that have accents and other characters that are not seen in regular english. Queries that return in error are: http://en.wikipedia.org/w/api.php?action=que...
using extended ascii characters for wikimedia api
I am writing a simple search algorithm for wikipedia. I am having trouble when I send a query with characters that have accents and other characters that are not seen in regular english. Queries that return in error are: http://en.wikipedia.org/w/api.php?action=query&titles=Albrecht%20Dürer&prop=links&pllimit=33&format...
[ "I don't see any trace in your Python source of how you're encoding any non-ascii characters you're sending in the query. For URLs (including query strings in them) using anything beyond ascii, you need to (make them unicode if they already aren't, then) encode them in utf-8 and percent-escape the result (for the ...
[ 1 ]
[]
[]
[ "api", "mediawiki", "python" ]
stackoverflow_0003765855_api_mediawiki_python.txt
Q: Signal handler, python I have a multithreaded program and use the signal.signal(SIGINT,func) to kill all threads when ctrl c is pressed. The question I have is this: I have to call signal.signal(...) from main in python. Do I have to call that on a loop or can I just set it once and whenever the user presses ctrl ...
Signal handler, python
I have a multithreaded program and use the signal.signal(SIGINT,func) to kill all threads when ctrl c is pressed. The question I have is this: I have to call signal.signal(...) from main in python. Do I have to call that on a loop or can I just set it once and whenever the user presses ctrl c, the signal will be caught...
[ "Only the main tread can handle signals. Just make all your threads \"daemonic\" ones (set the thread object's .daemon property to True before you start the thread) to ensure the threads terminate when the main thread does.\n" ]
[ 2 ]
[]
[]
[ "multithreading", "python", "sigint" ]
stackoverflow_0003765897_multithreading_python_sigint.txt
Q: Launching multiple processes of shell I'm trying to use python to launch a command in multiple seperate instances of terminal simultaneously. What is the best way to do this? Right now I am trying to use the subprocess module with popen which works for one command but not multiple. Thanks in advance. Edit: Here is...
Launching multiple processes of shell
I'm trying to use python to launch a command in multiple seperate instances of terminal simultaneously. What is the best way to do this? Right now I am trying to use the subprocess module with popen which works for one command but not multiple. Thanks in advance. Edit: Here is what I am doing: from subprocess import* ...
[ "This should stay open as long as the process is running. If you want to launch multiple simultanously, just wrap it in a thread\nuntested code, but you should get the general idea:\n\nclass PopenThread(threading.Thread):\n\n def __init__(self, port):\n threading.Thread.__init__(self)\n self.port=p...
[ 1, 1, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0003764499_linux_python.txt
Q: Run Python CGI Script on Windows XP This exact question has been asked before but I am at my wits end! I've spend 4 hours trying to get a SIMPLE Python CGI script to work on Windows XP but I get errors. Please save my sanity! Python Script register.py #!c:/Python30/python.exe -u print "Content-type: text/html" ...
Run Python CGI Script on Windows XP
This exact question has been asked before but I am at my wits end! I've spend 4 hours trying to get a SIMPLE Python CGI script to work on Windows XP but I get errors. Please save my sanity! Python Script register.py #!c:/Python30/python.exe -u print "Content-type: text/html" print "<P>Hello, World!</p>" Script is l...
[ "Your error is:\n\nPremature end of script headers\n\nNote that the HTTP protocol specifies that the body of a HTTP response is separated from it's headers by a blank line (i.e. two times a carriage return and line feed). I'd go for something like:\nimport sys\nsys.stdout.write(\"Content-type: text/html\\r\\n\\r\\n...
[ 4, 1, 0 ]
[]
[]
[ "cgi", "python", "windows_xp" ]
stackoverflow_0003765440_cgi_python_windows_xp.txt
Q: Have python run script at X:00 am Following up on, With python: intervals at x:00 repeat Using threading, How can I get a script to run starting at 8:00 am stop running at 5:00 pm The solution should be coded within python, and be portable tiA A: The time module has a function called asctime, which might be usef...
Have python run script at X:00 am
Following up on, With python: intervals at x:00 repeat Using threading, How can I get a script to run starting at 8:00 am stop running at 5:00 pm The solution should be coded within python, and be portable tiA
[ "The time module has a function called asctime, which might be useful for you:\n>>> from time import asctime\n>>> asctime()\n'Tue Sep 21 17:49:42 2010'\n\nSo, you could incorporate something like the following into your code:\nsysTime = asctime()\ntimestamp = systime.split()[3]\nseparator = timestamp[2]\nhour = tim...
[ 3, 0 ]
[]
[]
[ "multithreading", "python", "solaris", "time", "windows" ]
stackoverflow_0003763787_multithreading_python_solaris_time_windows.txt
Q: Python: PIL replace a single RGBA color I have already taken a look at this question: SO question and seem to have implemented a very similar technique for replacing a single color including the alpha values: c = Image.open(f) c = c.convert("RGBA") w, h = c.size cnt = 0 for px in c.getdata(): c.putpixel((int(c...
Python: PIL replace a single RGBA color
I have already taken a look at this question: SO question and seem to have implemented a very similar technique for replacing a single color including the alpha values: c = Image.open(f) c = c.convert("RGBA") w, h = c.size cnt = 0 for px in c.getdata(): c.putpixel((int(cnt % w), int(cnt / w)), (255, 0, 0, px[3])) ...
[ "If you have numpy, it provides a much, much faster way to operate on PIL images.\nE.g.:\nimport Image\nimport numpy as np\n\nim = Image.open('test.png')\nim = im.convert('RGBA')\n\ndata = np.array(im) # \"data\" is a height x width x 4 numpy array\nred, green, blue, alpha = data.T # Temporarily unpack the bands ...
[ 82, 11, 4 ]
[]
[]
[ "colors", "python", "python_imaging_library" ]
stackoverflow_0003752476_colors_python_python_imaging_library.txt
Q: Customizing Django Admin Interface functionality I am new to django and have gotten a bit stuck on trying to make the admin site work as I'd like it to. I am wondering if for making the admin functionality I want it is better to make a custom admin app with a template inheriting from admin/base_site.html, using t...
Customizing Django Admin Interface functionality
I am new to django and have gotten a bit stuck on trying to make the admin site work as I'd like it to. I am wondering if for making the admin functionality I want it is better to make a custom admin app with a template inheriting from admin/base_site.html, using the frontend login with a redirect when is_staff is tru...
[ "Slow down. Relax. Follow the Django philosophy.\n\nYou have an \"app\". It presents data. Focus on presentation.\nYou have a default, built-in admin for your \"app\". It updates data and it's already there.\nIf the admin app doesn't meet your needs update Forms and update Models to get close. But don't strai...
[ 9, 0 ]
[]
[]
[ "admin", "customization", "django", "python" ]
stackoverflow_0003758509_admin_customization_django_python.txt
Q: Multithreaded repeater in Python I have small repeater Below that keeps ending, How can fix so more stable from crashes, and not stop running.... I would I add a heartbeat to the gui to see that its still running. In Wxpthon, my menu bar goes blank or white. def TimerSetup(): import threading, time ...
Multithreaded repeater in Python
I have small repeater Below that keeps ending, How can fix so more stable from crashes, and not stop running.... I would I add a heartbeat to the gui to see that its still running. In Wxpthon, my menu bar goes blank or white. def TimerSetup(): import threading, time invl = 300 def dothis(): ...
[ "This runs for 7000 iterations. So if your runtime is at about 7000*300 s, it \"works exactly as coded\" :-) However, possibly the number of threads or the things you do in FetchUpdates could be a problem. Is there any traceback when it stops? Are reaching a user limit? \n", "seems you need join() to wait the sta...
[ 0, 0 ]
[]
[]
[ "heartbeat", "multithreading", "python" ]
stackoverflow_0003754745_heartbeat_multithreading_python.txt
Q: How to make a file which is on local server download-able over HTTP in python? Framework: Django Language: Python OS: Ubuntu For example, let us assume that I have a file "xyz.pdf" at "/home/username/project/". I have a webpage with download button. So if people click on that download button, the file xyz.pdf shou...
How to make a file which is on local server download-able over HTTP in python?
Framework: Django Language: Python OS: Ubuntu For example, let us assume that I have a file "xyz.pdf" at "/home/username/project/". I have a webpage with download button. So if people click on that download button, the file xyz.pdf should be downloaded. What I have done, Created a webpage with download button with hre...
[ "Generally, you'd want to just host the file in apache etc., and provide a link to the location. If the file is generated dynamically, or you want to \"embargo\" it, here's how you might do it with cherrypy:\n@cherrypy.expose\ndef download(self, filename):\n \"\"\"\n Download the specified XML file\n \"\"\...
[ 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003748205_django_python.txt
Q: Using Mercurial to separate three versions: official/development/testing/ I'm working on deploying a Python module composed of several dozen files and folders; I use Mercurial for managing the software changes. I want to keep the same module in three branches: the official one (which the team uses), the developmen...
Using Mercurial to separate three versions: official/development/testing/
I'm working on deploying a Python module composed of several dozen files and folders; I use Mercurial for managing the software changes. I want to keep the same module in three branches: the official one (which the team uses), the development one (this may be more than one development branch), and the testing branch (n...
[ "The \"official\" way would be cloning your repo in as many branch as you need.\nBut named branches within a repo is also acceptable, especially if you don't need to work simultaneously on different development efforts (each associated to their respective branch)\nI find the \"Guide to Branching Model in Mercurial\...
[ 3 ]
[]
[]
[ "mercurial", "python", "version_control" ]
stackoverflow_0003766657_mercurial_python_version_control.txt
Q: Python threading passing statuses Basically what I'm trying to do is fetch a couple of websites using proxies and process the data. The problem is that the requests rarely fail in a convincing way, setting socket timeouts wasnt very helpful either because they often didn't work. So what I did is: q = Queue() s = [...
Python threading passing statuses
Basically what I'm trying to do is fetch a couple of websites using proxies and process the data. The problem is that the requests rarely fail in a convincing way, setting socket timeouts wasnt very helpful either because they often didn't work. So what I did is: q = Queue() s = ['google.com','ebay.com',] # And so on f...
[ "edit: breaking news; see below · · · ······\nI decided recently that I wanted to do something pretty similar, and what came out of it was the pqueue_fetcher module. It ended up being mainly a learning endeavour: I learned, among other things, that it's almost certainly better to use something like twisted than to...
[ 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003746288_multithreading_python.txt
Q: Python: binary tree traversal iterators without using conditionals I am trying to create a module in python for iterating over a binary tree using the 4 standard tree traversals (inorder, preorder, postorder and levelorder) without using conditionals and only using polymorphic method dispatch or iterators. The fo...
Python: binary tree traversal iterators without using conditionals
I am trying to create a module in python for iterating over a binary tree using the 4 standard tree traversals (inorder, preorder, postorder and levelorder) without using conditionals and only using polymorphic method dispatch or iterators. The following examples should work. for e in t.preorder(): print(e) for e in...
[ "You said you wanted to use polymorphism, but you don't actually seem to have done so. Replace all occurrences of 'None' in your code with a special object that supports your methods but returns an empty sequence and it will all work.\nAlso you should take more care of the indentation when posting Python questions....
[ 1 ]
[]
[]
[ "binary_tree", "iterator", "python", "python_3.x" ]
stackoverflow_0003767014_binary_tree_iterator_python_python_3.x.txt
Q: Python - Speed up generation of permutations of a list (and process of checking if permuations in Dict) I need a faster way to generate all permutations of a list, then check if each one is in a dictionary. for x in range (max_combo_len, 0, -1): possible_combos = [] permutations = l...
Python - Speed up generation of permutations of a list (and process of checking if permuations in Dict)
I need a faster way to generate all permutations of a list, then check if each one is in a dictionary. for x in range (max_combo_len, 0, -1): possible_combos = [] permutations = list(itertools.permutations(bag,x)) for item in permutations: possible_combos.appe...
[ "A very basic optimization:\npermutations = list(itertools.permutations(bag,x))\nfor item in permutations:\n\ncan become...\nfor item in itertools.permutations(bag,x):\n\n", "I can't test it very well without better input cases, but here are a few improvements:\nfor x in xrange(max_combo_len, 0, -1):\n possibl...
[ 5, 1, 1, 1, 0 ]
[]
[]
[ "dictionary", "list", "permutation", "python", "python_itertools" ]
stackoverflow_0003766661_dictionary_list_permutation_python_python_itertools.txt
Q: Python: How to catch this kind of exception? I'm making a program for AIX 5.3 in Python 2.6.1 that interfaces with an IMAP server. I'm getting an exception which I don't know how to catch - it doesn't seem to have a name that I can use with "except". The error seems to be some kind of timeout in the connection to ...
Python: How to catch this kind of exception?
I'm making a program for AIX 5.3 in Python 2.6.1 that interfaces with an IMAP server. I'm getting an exception which I don't know how to catch - it doesn't seem to have a name that I can use with "except". The error seems to be some kind of timeout in the connection to the server. The last part of the stack trace looks...
[ "The exception is imaplib.IMAP4.abort (Python doc) so catching that should work\n", "you can try to catch it and find out the type:\nimport sys,traceback,pprint\ntry:\n do what you want to do\nexcept:\n type, value, tb = sys.exc_info()\n pprint.pprint(type)\n print(\"\\n\" + ''.join(traceback.format_e...
[ 10, 3 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0003767432_exception_python.txt
Q: Python or C++? Programming for mobile devices I am interested in programming for Mobile Devices. Now I have a phone which runs Symbian S60 3rd, which is one of my motivations for programming for mobile devices. Now, my question is, which one is better to go for? Python or C++? I have a good background in C++ (ANSI...
Python or C++? Programming for mobile devices
I am interested in programming for Mobile Devices. Now I have a phone which runs Symbian S60 3rd, which is one of my motivations for programming for mobile devices. Now, my question is, which one is better to go for? Python or C++? I have a good background in C++ (ANSI), Java and C#. Thanks.
[ "There's a large learning curve associated with Symbian C++, if you want to do a quick prototype probably do it in Python.\nIt depends on what you want your application to do. I believe the Symbian Python implementation was done in some Symbian developers spare time so it may not give you access to everything on th...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "c++", "python", "symbian" ]
stackoverflow_0003763766_c++_python_symbian.txt
Q: Namespaces in C# vs imports in Java and Python In the Java and Python world, you look at a source file and know where all the imports come from (i.e. you know in which file the imported classes are defined). For example: In Java: import javafoo.Bar; public class MyClass { private Bar myBar = new Bar(); } You...
Namespaces in C# vs imports in Java and Python
In the Java and Python world, you look at a source file and know where all the imports come from (i.e. you know in which file the imported classes are defined). For example: In Java: import javafoo.Bar; public class MyClass { private Bar myBar = new Bar(); } You immediately see that the Bar-class is imported from...
[ "1) Well, you can do the same thing in Java too:\nimport java.util.*;\nimport java.io.*;\n\n...\n\nInputStream x = ...;\n\nDoes InputStream come from java.util or java.io? Of course, you can choose not to use that feature.\nNow, in theory I realise this means when you're looking with a text editor, you can't tell w...
[ 7, 3, 3, 2, 2, 1 ]
[]
[]
[ "c#", "java", "namespaces", "package", "python" ]
stackoverflow_0003767910_c#_java_namespaces_package_python.txt
Q: How can I make this Python2.6 function work with Unicode? I've got this function, which I modified from material in chapter 1 of the online NLTK book. It's been very useful to me but, despite reading the chapter on Unicode, I feel just as lost as before. def openbookreturnvocab(book): fileopen = open(book) ...
How can I make this Python2.6 function work with Unicode?
I've got this function, which I modified from material in chapter 1 of the online NLTK book. It's been very useful to me but, despite reading the chapter on Unicode, I feel just as lost as before. def openbookreturnvocab(book): fileopen = open(book) rawness = fileopen.read() tokens = nltk.wordpunct_tokenize...
[ "For each string that you read from your file, you can convert them to unicode by calling rawness.decode('utf-8'), if you have the text in UTF-8. You will end up with unicode objects. Also, I don't know what \"jotted\" is, but you may want to make sure it's a unicode object and use u'\\n'.join(jotted) instead.\nU...
[ 4 ]
[]
[]
[ "nlp", "nltk", "python", "python_2.6", "unicode" ]
stackoverflow_0003768373_nlp_nltk_python_python_2.6_unicode.txt
Q: Keep SSL keyfile open in Python I'm using Python's ssl library with an encrypted keyfile. However every time I wrap a socket, I'm prompted for the passphrase. Enter PEM pass phrase: How can I give the passphrase just once, and have Python hold the decrypted key open for the lifetime of the process? I'm very inter...
Keep SSL keyfile open in Python
I'm using Python's ssl library with an encrypted keyfile. However every time I wrap a socket, I'm prompted for the passphrase. Enter PEM pass phrase: How can I give the passphrase just once, and have Python hold the decrypted key open for the lifetime of the process? I'm very interested in the canonical openssl comman...
[ "This issue is fixed in Python 2.7, and Python 3.2.\n" ]
[ 1 ]
[]
[]
[ "passphrase", "pem", "python", "security", "ssl" ]
stackoverflow_0003140011_passphrase_pem_python_security_ssl.txt
Q: Python compare dictonaries for different values I have 2 lists of dictonaries and want to return items which have the same id but different title. i.e. list1 = [{'id': 1, 'title': 'title1'}, {'id': 2, 'title': 'title2'}, {'id': 3, 'title': 'title3'}] list2 = [{'id': 1, 'title': 'title1'}, {'id': 2, 'title': 'titl...
Python compare dictonaries for different values
I have 2 lists of dictonaries and want to return items which have the same id but different title. i.e. list1 = [{'id': 1, 'title': 'title1'}, {'id': 2, 'title': 'title2'}, {'id': 3, 'title': 'title3'}] list2 = [{'id': 1, 'title': 'title1'}, {'id': 2, 'title': 'title3'}, {'id': 3, 'title': 'title4'}] Would return [{'...
[ "I propose that you refactor your design to not be a list of dictionaries, but 2 dictionaries of id: title pairs. The algorithm is trivial at that point and the performance is better.\nCode example (edited to reflect SilentGhost's correct assertion):\ntitles1 = {1: \"title1\", 2: \"title2\", 3: \"title3\"}\ntitles2...
[ 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003768543_python.txt
Q: Python lists and list item matches - can my code/reasoning be improved? query level: beginner As part of a learning exercise I have written code that must check if a string (as it is build up through raw_input) matches the beginning of any list item and if it equals any list item. wordlist = ['hello', 'bye'] ha...
Python lists and list item matches - can my code/reasoning be improved?
query level: beginner As part of a learning exercise I have written code that must check if a string (as it is build up through raw_input) matches the beginning of any list item and if it equals any list item. wordlist = ['hello', 'bye'] handlist = [] letter = raw_input('enter letter: ') handlist.append(letter) h...
[ "Firstly, you don't need the handlist variable; you can just concatenate the value of raw_input with hand.\nYou can save the first raw_input by starting the while loop with hand as an empty string since every string has startswith(\"\") as True.\nFinally, we need work out best way to see if any of the items in word...
[ 7 ]
[]
[]
[ "list", "python", "while_loop" ]
stackoverflow_0003768702_list_python_while_loop.txt
Q: Django getting executable raw sql for a QuerySet I know that you can get the SQL of a given QuerySet using print query.query but as we know from a previous question ( Potential Django Bug In QuerySet.query? ) the returned SQL is not properly quoted. See http://code.djangoproject.com/browser/django/trunk/django/db...
Django getting executable raw sql for a QuerySet
I know that you can get the SQL of a given QuerySet using print query.query but as we know from a previous question ( Potential Django Bug In QuerySet.query? ) the returned SQL is not properly quoted. See http://code.djangoproject.com/browser/django/trunk/django/db/models/sql/query.py Is there any way that is it possi...
[ "Django never creates the raw sql, so no. To prevent SQL injection, django passes the parameters separately to the database drivers at the last step. The best way to get the actual SQL is to look at your query log, which you cannot do before you execute the query.\n" ]
[ 9 ]
[]
[]
[ "django", "orm", "python", "sql" ]
stackoverflow_0003769093_django_orm_python_sql.txt
Q: Are there tools that can spot errors like this one? I found the following mistake in my code this week: import datetime d = datetime.date(2010,9,24) if d.isoweekday == 5: pass Yes, it should be d.isoweekday() instead. I know, if I had had a test-case for this I would have been saved. Comparing a function wit...
Are there tools that can spot errors like this one?
I found the following mistake in my code this week: import datetime d = datetime.date(2010,9,24) if d.isoweekday == 5: pass Yes, it should be d.isoweekday() instead. I know, if I had had a test-case for this I would have been saved. Comparing a function with 5 is not very useful. Oh, I'm not blaming Python for th...
[ "As an alternative, most Python projects are unit tested and system tested. If you have both (or even just unit tests) you'll find your problem along with pretty much any other issue.\nAs dekomote said, this is syntaxically valid. Python is not statically typed so this cannot be caught as an error. At most it could...
[ 7, 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003769196_python.txt
Q: Setting basedirlist in setup.cfg and PREFIX in make to point to virtualenv In SO question 3692928, I showed how I compiled and installed matplotlib in a virtualenv. One thing I did was suboptimal though—I manually set the basedirlist in setup.cfg and PREFIX in make.osx. setup.cfg [directories] basedirlist = /Users...
Setting basedirlist in setup.cfg and PREFIX in make to point to virtualenv
In SO question 3692928, I showed how I compiled and installed matplotlib in a virtualenv. One thing I did was suboptimal though—I manually set the basedirlist in setup.cfg and PREFIX in make.osx. setup.cfg [directories] basedirlist = /Users/matthew/.virtualenvs/matplotlib-test make.osx PREFIX=/Users/matthew/.virtualen...
[ "Use the VIRTUAL_ENV environment variable:\nsetup.cfg\n[directories]\nbasedirlist = ${VIRTUAL_ENV}\n\nmake.osx\nPREFIX=${VIRTUAL_ENV}\n\n" ]
[ 1 ]
[]
[]
[ "makefile", "python", "setuptools", "virtualenv" ]
stackoverflow_0003709898_makefile_python_setuptools_virtualenv.txt
Q: How to use importlib for rewriting bytecode? I'm looking for a way to use importlib in Python 2.x to rewrite bytecode of imported modules on-the-fly. In other words, I need to hook my own function between the compilation and execution step during import. Besides that I want the import function to work just as the...
How to use importlib for rewriting bytecode?
I'm looking for a way to use importlib in Python 2.x to rewrite bytecode of imported modules on-the-fly. In other words, I need to hook my own function between the compilation and execution step during import. Besides that I want the import function to work just as the built-in one. I've already did that with imputil,...
[ "Having had a look through the importlib source code, I believe you could subclass PyLoader in the _bootstrap module and override get_code:\nclass PyLoader:\n ...\n\n def get_code(self, fullname):\n \"\"\"Get a code object from source.\"\"\"\n source_path = self.source_path(fullname)\n if source_path...
[ 2 ]
[]
[]
[ "bytecode_manipulation", "import", "python" ]
stackoverflow_0003769336_bytecode_manipulation_import_python.txt
Q: Organizing and building a numpy array for a dynamic equation input I'm not sure if my post question makes lots of sense; however, I'm building an input array for a class/function that takes in a lot of user inputed data and outputs a numpy array. # I'm trying to build an input array that should include following i...
Organizing and building a numpy array for a dynamic equation input
I'm not sure if my post question makes lots of sense; however, I'm building an input array for a class/function that takes in a lot of user inputed data and outputs a numpy array. # I'm trying to build an input array that should include following information: ''' * zone_id - id from db - int * model size - int * ty...
[ "Numpy arrays are the wrong datatype here: they are designed for numeric manipulations of large amounts of similar data (e.g. large matrices). It looks like you could just use a dict:\noptions = {\n \"zone_id\": 10001,\n \"model_size\": 1,\n \"analysis_type\": 2,\n \"model_purposes\": [ \"ONE\", ... ]\n...
[ 3 ]
[]
[]
[ "arrays", "numpy", "python", "scipy" ]
stackoverflow_0003769386_arrays_numpy_python_scipy.txt
Q: Problematic Class Im trying to create a class called Record, though when I try to use it, something goes wrong. Im sure im overlooking something simple. Does anyone mind taking a look? class Record: def __init__(self, model): self.model= model self.doc_date = [] ...
Problematic Class
Im trying to create a class called Record, though when I try to use it, something goes wrong. Im sure im overlooking something simple. Does anyone mind taking a look? class Record: def __init__(self, model): self.model= model self.doc_date = [] self.doc_pn = []...
[ "res = res + \"Standard Part Numbers:\" + str(self.std_pn) + \"\\n\"\n\nI don't see self.std_pn defined anywhere.\n", "class Record:\n def __init__(self, model):\n self.model= model\n self.doc_date = []\n self.doc_pn = []\n self.std_pn = []\n print(\"Record %s has been ...
[ 6, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0003769284_class_python.txt
Q: Using PSI Filter objects from Python I'm working with SharePoint and ProjectServer 2007 via PSI with Python. I can't find any documentation on how Filter Class (Microsoft.Office.Project.Server.Library) objects work internally to emulate its behaviour in Python. Any ideas? A: Take a look at Colby Africa's blog po...
Using PSI Filter objects from Python
I'm working with SharePoint and ProjectServer 2007 via PSI with Python. I can't find any documentation on how Filter Class (Microsoft.Office.Project.Server.Library) objects work internally to emulate its behaviour in Python. Any ideas?
[ "Take a look at Colby Africa's blog post. Also, msdn docs are here.\nEdit\nThe generated filter is just XML. Here is a filter that returns the data from the \"LookupTables\" table (list of all the lookup tables):\n<?xml version=\"1.0\" encoding=\"utf-16\"?>\n<Filter xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-inst...
[ 0 ]
[]
[]
[ "project_server", "psi", "python" ]
stackoverflow_0003769320_project_server_psi_python.txt
Q: Why do exceptions/errors evaluate to True in python? In several places I have to retrieve some value from a dict, but need to check if the key for that value exists, and if it doesn't I use some default value : if self.data and self.data.has_key('key'): value = self.data['key'] else: value ...
Why do exceptions/errors evaluate to True in python?
In several places I have to retrieve some value from a dict, but need to check if the key for that value exists, and if it doesn't I use some default value : if self.data and self.data.has_key('key'): value = self.data['key'] else: value = self.default .... One thing I like about python, is...
[ "You are misunderstanding the use of exceptions. An exception is something gone wrong. It's not just a return value, and it shouldn't be treated as such.\n\nExplicit is better than implicit.\n\nBecause an exception is raised when something goes wrong, you must explicitly write code to catch them. That's deliberate ...
[ 9, 5, 3, 2, 0 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0003768438_exception_handling_python.txt
Q: Using Drupal 7 or developing a new system: What's better for a website relaunch with a community of 15.000 users? I have to make a decision for our (eXma german) community webpage. We will relauching it with a new system. There are two sites: The first is to develop a whole new system on e.g. Django and Python. ...
Using Drupal 7 or developing a new system: What's better for a website relaunch with a community of 15.000 users?
I have to make a decision for our (eXma german) community webpage. We will relauching it with a new system. There are two sites: The first is to develop a whole new system on e.g. Django and Python. The second is to use the new Drupal 7. Personally I have a lot more experiences with Drupal 6 and now since I'm testi...
[ "Drupal can be used as a very solid base upon which to build your site. It's well tested, has a variety of ready to use modules, and it is successfully used for busy sites. \nIt does have a relatively steep learning curve, but the documentation and community are excellent. However you mention you do have experience...
[ 3, 1 ]
[]
[]
[ "django", "drupal", "php", "python", "webpage" ]
stackoverflow_0003770067_django_drupal_php_python_webpage.txt
Q: Python function to solve Ax = b by back substitution Okay, for my numerical methods class I have the following question: Write a Python function to solve Ax = b by back substitution, where A is an upper triangular nonsingular matrix. MATLAB code for this is on page 190 which you can use as a pseudocode guide if yo...
Python function to solve Ax = b by back substitution
Okay, for my numerical methods class I have the following question: Write a Python function to solve Ax = b by back substitution, where A is an upper triangular nonsingular matrix. MATLAB code for this is on page 190 which you can use as a pseudocode guide if you wish. The function should take as input A and b and retu...
[ "j=i+1\nwhile j<n-1:\n x[i]=x[i]-U[i][j]*x[j];\n\nis infinite ... and never gets executed\nyour indexing is fubared:\nfor i in range(n-2,-1,-1):\n....\n for j in range(i+1,n):\n\nnotice, range is half open unlike matlab\n", "One problem I see is that your input consists of integers, which means that Python ...
[ 2, 2, 1 ]
[]
[]
[ "matlab", "matrix", "python" ]
stackoverflow_0003766700_matlab_matrix_python.txt
Q: signal.alarm function with resolution greater than 1 second? I'm trying to build a python timeout exception that runs in milliseconds. The python signal.alarm function has a 1 second resolution. How would one get an equivalent function that requests a SIGALRM signal to a given process in, say milliseconds, as oppo...
signal.alarm function with resolution greater than 1 second?
I'm trying to build a python timeout exception that runs in milliseconds. The python signal.alarm function has a 1 second resolution. How would one get an equivalent function that requests a SIGALRM signal to a given process in, say milliseconds, as opposed to seconds? I've found no simple solutions as of yet. Thanks i...
[ "Use signal.setitimer() instead.\n" ]
[ 16 ]
[]
[]
[ "alarm", "python", "signals" ]
stackoverflow_0003770711_alarm_python_signals.txt
Q: Django subquery using QuerySet Is it possible to perform a subquery on a QuerySet using another QuerySet? For example: q = Something.objects.filter(x=y).extra(where=query_set2) A: Short answer: No. The extra method doesn't expect querysets to be passed in. If you think about it a bit, it makes sense. Querysets ...
Django subquery using QuerySet
Is it possible to perform a subquery on a QuerySet using another QuerySet? For example: q = Something.objects.filter(x=y).extra(where=query_set2)
[ "Short answer: No. The extra method doesn't expect querysets to be passed in. \nIf you think about it a bit, it makes sense. Querysets are an abstraction used to represent the results of a fetch operation on the database and extra is a convenient way of attaching custom fields from the database to a queryset. Unles...
[ 6, 2 ]
[]
[]
[ "database", "django", "orm", "python" ]
stackoverflow_0003769367_database_django_orm_python.txt
Q: How to serve data from UDP stream over HTTP in Python? I am currently working on exposing data from legacy system over the web. I have a (legacy) server application that sends and receives data over UDP. The software uses UDP to send sequential updates to a given set of variables in (near) real-time (updates every...
How to serve data from UDP stream over HTTP in Python?
I am currently working on exposing data from legacy system over the web. I have a (legacy) server application that sends and receives data over UDP. The software uses UDP to send sequential updates to a given set of variables in (near) real-time (updates every 5-10 ms). thus, I do not need to capture all UDP data -- it...
[ "Twisted would be very suitable here. It supports many protocols (UDP, HTTP) and its asynchronous nature makes it possible to directly stream UDP data to HTTP without shooting yourself in the foot with (blocking) threading code. It also support wsgi.\n", "Here's a quick \"proof of concept\" app using the twisted ...
[ 6, 6, 4 ]
[]
[]
[ "python", "wsgi" ]
stackoverflow_0003768019_python_wsgi.txt
Q: Python os.walk + follow symlinks How do I get this piece to follow symlinks in python 2.6? def load_recursive(self, path): for subdir, dirs, files in os.walk(path): for file in files: if file.endswith('.xml'): file_path = os.path.join(subdir, file) try: ...
Python os.walk + follow symlinks
How do I get this piece to follow symlinks in python 2.6? def load_recursive(self, path): for subdir, dirs, files in os.walk(path): for file in files: if file.endswith('.xml'): file_path = os.path.join(subdir, file) try: do_stuff(file_path) ...
[ "Set followlinks to True. This is the fourth argument to the os.walk method, reproduced below:\nos.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])\n\nThis option was added in Python 2.6.\nEDIT 1\nBe careful when using followlinks=True. According to the documentation:\n\nNote: Be aware that setting fo...
[ 64 ]
[]
[]
[ "directory_traversal", "python", "symlink", "symlink_traversal", "traversal" ]
stackoverflow_0003771696_directory_traversal_python_symlink_symlink_traversal_traversal.txt
Q: PyQT QtGui.QTableWidgetItem I have a QtGui.QTableWidgetItem that I added to a table by the createRow function below: def createRow(self, listA): rowNum = self.table.rowCount() self.table.insertRow(rowNum) i = 0 for val in listA: self.table.setItem(rowNum, i, QtGui.QTableWidgetItem(val)) ...
PyQT QtGui.QTableWidgetItem
I have a QtGui.QTableWidgetItem that I added to a table by the createRow function below: def createRow(self, listA): rowNum = self.table.rowCount() self.table.insertRow(rowNum) i = 0 for val in listA: self.table.setItem(rowNum, i, QtGui.QTableWidgetItem(val)) i += 1 Now I have a thread ...
[ "Use QTableWidgetItem.text(self) (i.e.: self.table.item(i,0).text()) to get the contents of a cell/QTableWidgetItem.\n" ]
[ 5 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0003771566_pyqt_python.txt
Q: Authentication on App Engine / Python / Django non-rel over JSON I'm building a site on Google App Engine, running python and Django non-rel. Everything is working great for HTML and posting/reading data. But as I'm moving forward I'd like to do many of the updates with AJAX, and eventually also over mobile device...
Authentication on App Engine / Python / Django non-rel over JSON
I'm building a site on Google App Engine, running python and Django non-rel. Everything is working great for HTML and posting/reading data. But as I'm moving forward I'd like to do many of the updates with AJAX, and eventually also over mobile devices like Android and iPhone. My pages use django non-rel and my login/lo...
[ "Python makes this pretty easy, you can just create a decorator method of checking the auth and add the decorator to any method requiring auth credentials. \ndef admin(handler_method):\n \"\"\"\n This decorator requires admin, 403 if not.\n \"\"\"\n def auth_required(self, *args, **kwargs):\n if users.is_cur...
[ 2 ]
[]
[]
[ "authentication", "django_nonrel", "google_app_engine", "json", "python" ]
stackoverflow_0003771610_authentication_django_nonrel_google_app_engine_json_python.txt
Q: python 3.1 - DictType not part of types module? This is what I found in my install of Python 3.1 on Windows. Where can I find other types, specifically DictType and StringTypes? >>> print('\n'.join(dir(types))) BuiltinFunctionType BuiltinMethodType CodeType FrameType FunctionType GeneratorType GetSetDescriptorType...
python 3.1 - DictType not part of types module?
This is what I found in my install of Python 3.1 on Windows. Where can I find other types, specifically DictType and StringTypes? >>> print('\n'.join(dir(types))) BuiltinFunctionType BuiltinMethodType CodeType FrameType FunctionType GeneratorType GetSetDescriptorType LambdaType MemberDescriptorType MethodType ModuleTyp...
[ "According to the doc of the types module (http://docs.python.org/py3k/library/types.html),\n\nThis module defines names for some object types that are used by the standard Python interpreter, but not exposed as builtins like int or str are. ...\nTypical use is for isinstance() or issubclass() checks.\n\nSince the ...
[ 7, 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0003772049_python_python_3.x.txt
Q: pythonic way to wrap xmlrpclib calls in similar multicalls I'm writing a class that interfaces to a MoinMoin wiki via xmlrpc (simplified code follows): class MoinMoin(object): token = None def __init__(self, url, username=None, password=None): self.wiki = xmlrpclib.ServerProxy(url + '/?action=xml...
pythonic way to wrap xmlrpclib calls in similar multicalls
I'm writing a class that interfaces to a MoinMoin wiki via xmlrpc (simplified code follows): class MoinMoin(object): token = None def __init__(self, url, username=None, password=None): self.wiki = xmlrpclib.ServerProxy(url + '/?action=xmlrpc2') if username and password: self.token ...
[ "Python function are objects so they can be passed quite easily to other function.\ndef HandleAuthAndReturnResult(self, method, arg):\n mc = xmlrpclib.MultiCall(self.wiki)\n if self.token:\n mc.applyAuthToken(self.token)\n method(mc, arg)\n return mc()[-1]\ndef fooMethod(self, x):\n HandleAuth...
[ 1 ]
[]
[]
[ "class", "methods", "python" ]
stackoverflow_0003771859_class_methods_python.txt
Q: pyfacebook doesn't have set_status in that object anymore? i just try this import facebook fb = facebook.Facebook('YOUR_API_KEY', 'YOUR_SECRET_KEY') fb.auth.createToken() fb.login() fb.auth.getSession() fb.set_status('Checking out StackOverFlow.com') and got this gunslinger@c0debreaker:~$ python Python 2.6.2 (r...
pyfacebook doesn't have set_status in that object anymore?
i just try this import facebook fb = facebook.Facebook('YOUR_API_KEY', 'YOUR_SECRET_KEY') fb.auth.createToken() fb.login() fb.auth.getSession() fb.set_status('Checking out StackOverFlow.com') and got this gunslinger@c0debreaker:~$ python Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Ty...
[ "From looking at the source code, it looks like you need to use fb.status.set()\n" ]
[ 1 ]
[]
[]
[ "pyfacebook", "python" ]
stackoverflow_0003769229_pyfacebook_python.txt
Q: Optimizing Python Code for Database Access I am building an application with objects which have their data stored in mysql tables (across multiple tables). When I need to work with the object (retrieve object attributes / change the attributes) I am querying the sql database using mysqldb (select / update). Howeve...
Optimizing Python Code for Database Access
I am building an application with objects which have their data stored in mysql tables (across multiple tables). When I need to work with the object (retrieve object attributes / change the attributes) I am querying the sql database using mysqldb (select / update). However, since the application is quite computation in...
[ "25Mb is tiny. Microscopic. SQL is slow. Glacial.\nDo not waste time on SQL unless you have transactions (with locking and multiple users).\nIf you're doing \"analysis\", especially computationally-intensive analysis, load all the data into memory.\nIn the unlikely event that data doesn't fit into memory, then d...
[ 5, 0 ]
[]
[]
[ "mysql", "optimization", "python" ]
stackoverflow_0003770394_mysql_optimization_python.txt
Q: Python YouTube Gdata Api: DeletePlaylist I have correctly initialized YouTubeService. I can move/delete/rename playlist entries, but when I try to delete playlist I get unhelpfull exception: _service = None def get_service(): global _service if _service is None: _service = YouTubeService() ...
Python YouTube Gdata Api: DeletePlaylist
I have correctly initialized YouTubeService. I can move/delete/rename playlist entries, but when I try to delete playlist I get unhelpfull exception: _service = None def get_service(): global _service if _service is None: _service = YouTubeService() gdata.alt.appengine.run_on_appengine(_servic...
[ "Documentation (http://code.google.com/apis/youtube/1.0/developers_guide_python.html#DeletePlaylists) is outdated or this is bug, but DeletePlaylist requires \"full\" link:\nhttp://gdata.youtube.com/feeds/api/users/username/playlists/921AC6352FE6931F\n\nsince GetYouTubePlaylistVideoFeed method requires \"short\" li...
[ 0 ]
[]
[]
[ "gdata_python_client", "google_app_engine", "python" ]
stackoverflow_0003769069_gdata_python_client_google_app_engine_python.txt
Q: Google App Engine python Filter "property of property" Having these models on google app engine: class Choice(db.Model): poll = db.ReferenceProperty(Poll, collection_name = 'choices' ) text = db.StringProperty() class Vote(db.Model): choice = db.ReferenceProperty(Choice, collection_name = 'votes' ) ...
Google App Engine python Filter "property of property"
Having these models on google app engine: class Choice(db.Model): poll = db.ReferenceProperty(Poll, collection_name = 'choices' ) text = db.StringProperty() class Vote(db.Model): choice = db.ReferenceProperty(Choice, collection_name = 'votes' ) ip = db.StringProperty() date = db.DateTimeProperty(au...
[ "The App Engine datastore isn't capable of doing a query like this, which requires a join. To perform such a query, you'll need to denormalize your data so your Vote entities include information about which Poll they apply to.\n" ]
[ 3 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0003772495_django_google_app_engine_python.txt
Q: Using data from a specific class in python storage = [] ... after running program storage = [ <main.Record instance at 0x032E8530> ] inside the instance of Record are: "Model No." "Standard: Part Number" "Standard: Issue Date" "Date of Declaration" "Declaration Document Number" Question: How do I use specific dat...
Using data from a specific class in python
storage = [] ... after running program storage = [ <main.Record instance at 0x032E8530> ] inside the instance of Record are: "Model No." "Standard: Part Number" "Standard: Issue Date" "Date of Declaration" "Declaration Document Number" Question: How do I use specific data from within the Record?
[ "What do you mean by use?\nstorage[0] will give you a reference to the record.\nFrom there you can just use whatever methods main.Record exposes to access its data.\n" ]
[ 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0003772981_class_python.txt
Q: Pythonic way to perform a large case/switch I'm pretty sure this is a really fundamental concept in Python, I'd love it if someone could help me understand how to do the following in a pythonic/clean way. I'm really new to coding so I will just show an example. I think it will be obvious what I am trying to do. ...
Pythonic way to perform a large case/switch
I'm pretty sure this is a really fundamental concept in Python, I'd love it if someone could help me understand how to do the following in a pythonic/clean way. I'm really new to coding so I will just show an example. I think it will be obvious what I am trying to do. for textLine in textLines: foo = re.match('[1-...
[ "Why not just do this\nitem = list[int(thing) - 1]\n\nIn more complex cases, you should use a dictionary mapping inputs to outputs.\n", "For the specific code you're showing, the pythonic thing would be to replace the entire if-ladder with:\nitem = list[int(thing)-1]\n\nOf course, it's possible that your real cod...
[ 11, 7 ]
[]
[]
[ "python" ]
stackoverflow_0003773079_python.txt
Q: learning python - point to keep in mind w.r.t idioms! I've been an avid learner of the Python language for quite some time. Having more than 6 years of Java[professional] experience, coupled with a bit of C++ [hobby] experience - it's fair to say my perspective is deeply entrenched in the idioms brought forth by s...
learning python - point to keep in mind w.r.t idioms!
I've been an avid learner of the Python language for quite some time. Having more than 6 years of Java[professional] experience, coupled with a bit of C++ [hobby] experience - it's fair to say my perspective is deeply entrenched in the idioms brought forth by such statically typed, strongly bound languages. In short - ...
[ "\nlist comprehension and filter(...),\n apply(...) and eval(...), etc. while\n these idioms aren't completely\n substitutable, but i find that their\n primary purposes overlap to a great\n extent\n\nThe pythonic way would be: use simple for-loops or list comprehensions. filter and map are remnants of older ve...
[ 4, 3, 2, 2, 2, 1, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0003772989_python_syntax.txt
Q: Django, where to import your modules I always thought it was OK to just import all of your modules at the top of a view file. Then if you ever change a model name you can just edit the import at the top and not go digging through every view function that you need it imported in. Well, I just ran into an instanc...
Django, where to import your modules
I always thought it was OK to just import all of your modules at the top of a view file. Then if you ever change a model name you can just edit the import at the top and not go digging through every view function that you need it imported in. Well, I just ran into an instance where I had imported a model at the top ...
[ "There is no requirement in Django that you import modules at function scope. You can, but that is true of python generally. I'd like to see your code and error message. I don't think that your problem is due to the cause you attribute it to.\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003773208_django_python.txt
Q: How can I selectively mask arbitrary data being sent over an insecure link? I'm using an offsite error logging package for my python web application. When I send an error I include the contents of (among other things) the POST variable and some template data. Some of this data must not be sent to the error logging...
How can I selectively mask arbitrary data being sent over an insecure link?
I'm using an offsite error logging package for my python web application. When I send an error I include the contents of (among other things) the POST variable and some template data. Some of this data must not be sent to the error logging service (passwords, some other template data). How can I take a payload that con...
[ "If you have the POST data as a string, you can use the standard modules \"urlparse\" and \"urllib\" to remove certain parameters:\nimport urlparse\nimport urllib\n\npostDataAsDict = urlparse.parse_qs(\"a=5&b=3&c=%26escaped\", strict_parsing = True)\nprint postDataAsDict # prints {'a': ['5'], 'b': ['3'], 'c': ['&es...
[ 1 ]
[]
[]
[ "python", "sanitization", "security", "web_services" ]
stackoverflow_0003773440_python_sanitization_security_web_services.txt
Q: Python average tabular data help Ok I have the following working program. It opens of a file of data in columns that is too large for excel and finds the average value for each column: Sample data is: Joe Sam Bob 1 2 3 2 1 3 And it returns Joe Sam Bob 1.5 1.5 3 This is good. The problem is some columns h...
Python average tabular data help
Ok I have the following working program. It opens of a file of data in columns that is too large for excel and finds the average value for each column: Sample data is: Joe Sam Bob 1 2 3 2 1 3 And it returns Joe Sam Bob 1.5 1.5 3 This is good. The problem is some columns have NA as a value. I want to skip this...
[ "Here is a functional solution:\ntext = \"\"\"Joe Sam Bob\n1 2 3\n2 1 3\nNA 2 3\n3 5 NA\"\"\"\n\ndef avg( lst ):\n \"\"\" returns the average of a list \"\"\"\n return 1. * sum(lst)/len(lst)\n\n# split that text\nparts = [line.split() for line in text.splitlines()]\n#remove the headers\nnames = parts....
[ 3, 2, -1 ]
[ "Change your inner-most loop to:\n values = line.split(\" \")\n for i in xrange(len(values)):\n if values[i] == \"NA\":\n continue\n sums[i] += int(values[i])\n numRows += 1\n\n", "Much smaller code:\nwith open('in', \"rtU\") as f:\n lines = [l for l in f if l.strip()]\n na...
[ -1, -1 ]
[ "python" ]
stackoverflow_0003771424_python.txt
Q: Piping output of subprocess.Popen to files I need to launch a number of long-running processes with subprocess.Popen, and would like to have the stdout and stderr from each automatically piped to separate log files. Each process will run simultaneously for several minutes, and I want two log files (stdout and stde...
Piping output of subprocess.Popen to files
I need to launch a number of long-running processes with subprocess.Popen, and would like to have the stdout and stderr from each automatically piped to separate log files. Each process will run simultaneously for several minutes, and I want two log files (stdout and stderr) per process to be written to as the processe...
[ "You can pass stdout and stderr as parameters to Popen()\nsubprocess.Popen(self, args, bufsize=0, executable=None, stdin=None, stdout=None,\n stderr=None, preexec_fn=None, close_fds=False, shell=False,\n cwd=None, env=None, universal_newlines=False, startupinfo=None, \n ...
[ 91, 41, 3 ]
[]
[]
[ "python", "stdout", "subprocess" ]
stackoverflow_0002331339_python_stdout_subprocess.txt
Q: PyPi issues - Upload failed (401): You must be identified to edit package information Im encountering a problem with pypi similar to this one, except that I'm running windows and the mentioned solution page is down. Does anyone know how to work around this? I'm using python 2.5. python setup.py sdist register upl...
PyPi issues - Upload failed (401): You must be identified to edit package information
Im encountering a problem with pypi similar to this one, except that I'm running windows and the mentioned solution page is down. Does anyone know how to work around this? I'm using python 2.5. python setup.py sdist register upload running register We need to know who you are, so please choose either: 1. use your ex...
[ "the answer for this seems not very non-windows-specific, give it a try:\naccepted answer It says basically, that you need a file .pypirc with the following section:\n\n[server-login]\nusername:tschellenbach\npassword:******** (the real one)\n\nalso, this is the relevant documentation (about .pypirc):\n\nOn windows...
[ 55 ]
[]
[]
[ "pypi", "python" ]
stackoverflow_0003773613_pypi_python.txt
Q: Write conditions based on a list I'm writing an if statement in Python with a lot of OR conditions. Is there an elegant way to do this with a list, within in the condition rather than looping through the list? In other words, what would be prettier than the following: if foo == 'a' or foo == 'b' or foo == 'c' or f...
Write conditions based on a list
I'm writing an if statement in Python with a lot of OR conditions. Is there an elegant way to do this with a list, within in the condition rather than looping through the list? In other words, what would be prettier than the following: if foo == 'a' or foo == 'b' or foo == 'c' or foo == 'd': I've just taken up Python,...
[ "if foo in ('a', 'b', 'c', 'd'):\n #...\n\nI will also note that your answer is wrong for several reasons:\n\nYou should remove parentheses.. python does need the outer ones and it takes room.\nYou're using an assignment operator, not an equality operator (=, not ==)\nWhat you meant to write as foo == 'a' or foo...
[ 7, 2, 2, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003773666_list_python.txt
Q: Implement a userEdited signal to QDateTimeEdit? QLineEdit has a textEdited signal which is emitted whenever the text is changed by user interaction, but not when the text is changed programatically. However, QDateTimeEdit has only a general dateTimeChanged signal that does not distinguish between these two types o...
Implement a userEdited signal to QDateTimeEdit?
QLineEdit has a textEdited signal which is emitted whenever the text is changed by user interaction, but not when the text is changed programatically. However, QDateTimeEdit has only a general dateTimeChanged signal that does not distinguish between these two types of changes. Since my app depends on knowing if the fie...
[ "The idiomatic Qt way of achieving this is indeed subclassing QDateTimeEdit and adding the functionality you require. I understand you tried it and \"failed to deal with events\", but that's a separate issue, and perhaps you should describe those problems - since they should be solvable.\n", "Since I'm not entire...
[ 0, 0 ]
[]
[]
[ "pyqt4", "python", "qt", "signals" ]
stackoverflow_0003766360_pyqt4_python_qt_signals.txt
Q: Read/Write CSV as binary with Python I just found out that I can save space\ speed up reads of CSV files. Using the answer of my previous question How do I create a CSV file from database in Python? And 'wb' for opens w = csv.writer(open(Fn,'wb'),dialect='excel') How can I open all files in a directory and s...
Read/Write CSV as binary with Python
I just found out that I can save space\ speed up reads of CSV files. Using the answer of my previous question How do I create a CSV file from database in Python? And 'wb' for opens w = csv.writer(open(Fn,'wb'),dialect='excel') How can I open all files in a directory and saves all files with the same name as start...
[ "You can't \"overwrite a file on the fly\". You have two options:\n\nif the files are small enough (smaller than the amount of available RAM by\na comfortable margin), just loop over them (os.listdir makes that loop\neasy, or os.walk if you want to catch the whole tree of subdirectories,\nnot just one directory), ...
[ 4 ]
[]
[]
[ "csv", "file_io", "python" ]
stackoverflow_0003773894_csv_file_io_python.txt
Q: Django / Python, calling a specific class / function on every user Request I was looking over the Django documentation on a way to do this but didn't see anything, though I may have missed it as I'm not sure exactly where to look... I want to be able to perform a specific action on every user request, such as inst...
Django / Python, calling a specific class / function on every user Request
I was looking over the Django documentation on a way to do this but didn't see anything, though I may have missed it as I'm not sure exactly where to look... I want to be able to perform a specific action on every user request, such as instantiating a class and calling one of its functions, however the only way I know ...
[ "You want to use Django's middleware functionality.\n" ]
[ 6 ]
[]
[]
[ "django", "python", "request" ]
stackoverflow_0003774005_django_python_request.txt
Q: Python vs Lua for embedded scripting/text processing engine For a project I'm currently working on, I'm looking to embed a scripting engine into my C++ code to allow for some extensibility down the line. The application will require a fair amount of text processing and the use of regular expressions within these ...
Python vs Lua for embedded scripting/text processing engine
For a project I'm currently working on, I'm looking to embed a scripting engine into my C++ code to allow for some extensibility down the line. The application will require a fair amount of text processing and the use of regular expressions within these scripts. I know Lua is generally the industry darling when it com...
[ "if you need specifically what is commonly known as 'regular expressions' (which aren't regular at all), then you have two choices:\n\ngo with Python. it's included regexp is similar enough to Perl's and sed/grep\nuse Lua and an external PCRE library\n\nif, on the other hand, you need any good pattern matching, yo...
[ 19, 7, 5, 4 ]
[]
[]
[ "c++", "embedded_language", "lua", "python", "scripting" ]
stackoverflow_0003774108_c++_embedded_language_lua_python_scripting.txt
Q: Making all variables in a scope global or importing a module inside another module I have a package with two modules in it. One is the __init__ file, and the other is a separate part of the package. If I try from mypackage import separatepart, the code in the __init__ module is run, which will run unneeded code, s...
Making all variables in a scope global or importing a module inside another module
I have a package with two modules in it. One is the __init__ file, and the other is a separate part of the package. If I try from mypackage import separatepart, the code in the __init__ module is run, which will run unneeded code, slowing down the importing by a lot. The code in separate part won't cause any errors, an...
[ "dthat I know of, there is not way to specify that all variables are global but you can import the module while you are in the module. just make sure that you do it in a function that isn't called at the top level, you are playing with infinite recursion here but a simple use should be safe.\n#module.py\n\nfoo = ba...
[ 1 ]
[]
[]
[ "global_variables", "import", "initialization", "module", "python" ]
stackoverflow_0003774510_global_variables_import_initialization_module_python.txt
Q: Get data from the meta tags using BeautifulSoup I am trying to read the description from the meta tag and this is what I used soup.findAll(name="description") but it does not work, however, the code below works just fine soup.findAll(align="center") How do I read the description from the meta tag in the head of ...
Get data from the meta tags using BeautifulSoup
I am trying to read the description from the meta tag and this is what I used soup.findAll(name="description") but it does not work, however, the code below works just fine soup.findAll(align="center") How do I read the description from the meta tag in the head of a document?
[ "Yep, name can't be used in keyword-argument form to designate an attribute named name because the name name is already used by BeautifulSoup itself. So use instead:\nsoup.findAll(attrs={\"name\":\"description\"})\n\nThat's what the attrs argument is for: passing as a dict those attribute constraints for which you...
[ 35 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003774571_beautifulsoup_python.txt
Q: Implementing use of 'with object() as f' in custom class in python I have to open a file-like object in python (it's a serial connection through /dev/) and then close it. This is done several times in several methods of my class. How I WAS doing it was opening the file in the constructor, and then closing it in th...
Implementing use of 'with object() as f' in custom class in python
I have to open a file-like object in python (it's a serial connection through /dev/) and then close it. This is done several times in several methods of my class. How I WAS doing it was opening the file in the constructor, and then closing it in the destructor. I'm getting weird errors though and I think it has to do w...
[ "Those methods are pretty much all you need for making the object work with with statement.\nIn __enter__ you have to return the file object after opening it and setting it up.\nIn __exit__ you have to close the file object. The code for writing to it will be in the with statement body.\nclass Meter():\n def __i...
[ 155, 62 ]
[ "The first Google hit (for me) explains it simply enough:\nhttp://effbot.org/zone/python-with-statement.htm\nand the PEP explains it more precisely (but also more verbosely):\nhttp://www.python.org/dev/peps/pep-0343/\n" ]
[ -11 ]
[ "file_io", "python", "with_statement" ]
stackoverflow_0003774328_file_io_python_with_statement.txt
Q: Can't call method in Python C extension I'm working on making my first Python C extension, which defines a few functions and custom types. The strange thing is that the custom types are working, but not the regular functions. The top-level MyModule.c file looks like this: static PyMethodDef MyModule_methods[] = ...
Can't call method in Python C extension
I'm working on making my first Python C extension, which defines a few functions and custom types. The strange thing is that the custom types are working, but not the regular functions. The top-level MyModule.c file looks like this: static PyMethodDef MyModule_methods[] = { {"doStuff", MyModule_doStuff, METH_VARA...
[ "The fact that this code works:\nfrom mymodule.MyCustomType import MyCustomType\n\nis absolutely astonishing and tells us that mymodule is actually a package, and MyCustomType a module within that package (which contains a type or class by the same name). \nTherefore, to call the function, you'll obviously have to...
[ 2, 0 ]
[]
[]
[ "c", "python", "python_extensions" ]
stackoverflow_0003774291_c_python_python_extensions.txt
Q: Cycle of multiple iterables? Given: x = ['a','b','c','d','e'] y = ['1','2','3'] I'd like iterate resulting in: a, 1 b, 2 c, 3 d, 1 e, 2 a, 3 b, 1 ... where the two iterables cycle independently until a given count. Python's cycle(iterable) can do this w/ 1 iterable. Functions such as map and itertools.izip_long...
Cycle of multiple iterables?
Given: x = ['a','b','c','d','e'] y = ['1','2','3'] I'd like iterate resulting in: a, 1 b, 2 c, 3 d, 1 e, 2 a, 3 b, 1 ... where the two iterables cycle independently until a given count. Python's cycle(iterable) can do this w/ 1 iterable. Functions such as map and itertools.izip_longest can take a function to handle ...
[ "The simplest way to do this is in cyclezip1 below. It is fast enough for most purposes. \nimport itertools\n\ndef cyclezip1(it1, it2, count):\n pairs = itertools.izip(itertools.cycle(iter1),\n itertools.cycle(iter2))\n return itertools.islice(pairs, 0, count)\n\nHere is another ...
[ 10, 7 ]
[]
[]
[ "python" ]
stackoverflow_0003775027_python.txt
Q: Python multiprocessing Pool.map is calling aquire? I have a numpy.array of 640x480 images, each of which is 630 images long. The total array is thus 630x480x640. I want to generate an average image, as well as compute the standard deviation for each pixel across all 630 images. This is easily accomplished by avg_i...
Python multiprocessing Pool.map is calling aquire?
I have a numpy.array of 640x480 images, each of which is 630 images long. The total array is thus 630x480x640. I want to generate an average image, as well as compute the standard deviation for each pixel across all 630 images. This is easily accomplished by avg_image = numpy.mean(img_array, axis=0) std_image = numpy.s...
[ "I believe the problem is that the amount of CPU time it takes to process each chunk is small relative to the amount of time it takes to copy the input and output to and from the worker processes. I modified your example code to split the output into 16 even chunks and to print out the difference in CPU time (time...
[ 7 ]
[]
[]
[ "multiprocessing", "profiling", "python" ]
stackoverflow_0003771875_multiprocessing_profiling_python.txt
Q: Using file descriptors to communicate between processes I have the following python code: import pty import subprocess os=subprocess.os from subprocess import PIPE import time import resource pipe=subprocess.Popen(["cat"], stdin=PIPE, stdout=PIPE, stderr=PIPE, \ close_fds=True) skip=[f.filen...
Using file descriptors to communicate between processes
I have the following python code: import pty import subprocess os=subprocess.os from subprocess import PIPE import time import resource pipe=subprocess.Popen(["cat"], stdin=PIPE, stdout=PIPE, stderr=PIPE, \ close_fds=True) skip=[f.fileno() for f in (pipe.stdin, pipe.stdout, pipe.stderr)] pid, chi...
[ "Ok, I think I've got a handle on your question now, and see two different approaches you could take.\nIf you absolutely want to provide the shell in the child process with an already-open file descriptor, then you can replace the Popen() of cat with a call to os.pipe(). That will give you a connected pair of real...
[ 1 ]
[]
[]
[ "file_descriptor", "ipc", "python", "zsh" ]
stackoverflow_0003769048_file_descriptor_ipc_python_zsh.txt
Q: Numeric variable scope in Python closure (Python v2.5.2) I have a nested function where I am trying to access variables assigned in the parent scope. From the first line of the next() function I can see that path, and nodes_done are assigned as expected. distance, current, and probability_left have no value and a...
Numeric variable scope in Python closure (Python v2.5.2)
I have a nested function where I am trying to access variables assigned in the parent scope. From the first line of the next() function I can see that path, and nodes_done are assigned as expected. distance, current, and probability_left have no value and are causing a NameError to be thrown. What am I doing wrong her...
[ "The way Python's nested scopes work, you can never assign to a variable in the parent scope, unless it's global (via the global keyword). This changes in Python 3 (with the addition of nonlocal), but with 2.x you're stuck.\nInstead, you have to sort of work around this by using a datatype which is stored by refere...
[ 4, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003775213_python.txt
Q: How to use Scrapy I would like to know how can I start a crawler based on Scrapy. I installed the tool via apt-get install and I tried to run an example: /usr/share/doc/scrapy/examples/googledir/googledir$ scrapy list directory.google.com /usr/share/doc/scrapy/examples/googledir/googledir$ scrapy crawl I hacked...
How to use Scrapy
I would like to know how can I start a crawler based on Scrapy. I installed the tool via apt-get install and I tried to run an example: /usr/share/doc/scrapy/examples/googledir/googledir$ scrapy list directory.google.com /usr/share/doc/scrapy/examples/googledir/googledir$ scrapy crawl I hacked the code from spiders/...
[ "EveryBlock.com released some quality scraping code using lxml, urllib2 and Django as their stack.\nScraperwiki.com is inspirational, full of examples of python scrapers.\nSimple example with cssselect:\nfrom lxml.html import fromstring\n\ndom = fromstring('<html... ...')\nnavigation_links = [a.get('href') for a in...
[ 7, 7 ]
[]
[]
[ "python", "scrapy", "web_crawler" ]
stackoverflow_0003773035_python_scrapy_web_crawler.txt
Q: Statistical accumulator in Python An statistical accumulator allows one to perform incremental calculations. For instance, for computing the arithmetic mean of a stream of numbers given at arbitrary times one could make an object which keeps track of the current number of items given, n and their sum, sum. When on...
Statistical accumulator in Python
An statistical accumulator allows one to perform incremental calculations. For instance, for computing the arithmetic mean of a stream of numbers given at arbitrary times one could make an object which keeps track of the current number of items given, n and their sum, sum. When one requests the mean, the object simply ...
[ "For a generalized, threadsafe higher-level function, you could use something like the following in combination with the Queue.Queue class and some other bits:\nfrom Queue import Empty\n\ndef Accumulator(f, q, storage):\n \"\"\"Yields successive values of `f` over the accumulation of `q`.\n\n `f` should take ...
[ 3, 1 ]
[]
[]
[ "accumulator", "oop", "python", "statistics" ]
stackoverflow_0003774315_accumulator_oop_python_statistics.txt
Q: Dealing with special floating point values in Python I am writing a simple app that takes a bunch of numerical inputs and calculates a set of results. (The app is in PyGTK but I don't think that's relevant.) My problem is that if I want to just have NaN's and Inf's propagated through, then in every calculation I n...
Dealing with special floating point values in Python
I am writing a simple app that takes a bunch of numerical inputs and calculates a set of results. (The app is in PyGTK but I don't think that's relevant.) My problem is that if I want to just have NaN's and Inf's propagated through, then in every calculation I need to do something like: # At the top of the module nan =...
[ "No, Python's built-in math raises exceptions for errors rather than returning them as NaN and INF. You'll need to use a library or your own code if you don't want this behavior.\n(Thought I'd give the simple answer, since too many questions where the answer is \"sorry, no\" simply don't get answered.)\n" ]
[ 2 ]
[]
[]
[ "floating_point", "python" ]
stackoverflow_0003775513_floating_point_python.txt
Q: Writing a parser for regular expressions Even after years of programming, I'm ashamed to say that I've never really fully grasped regular expressions. In general, when a problem calls for a regex, I can usually (after a bunch of referring to syntax) come up with an appropriate one, but it's a technique that I find...
Writing a parser for regular expressions
Even after years of programming, I'm ashamed to say that I've never really fully grasped regular expressions. In general, when a problem calls for a regex, I can usually (after a bunch of referring to syntax) come up with an appropriate one, but it's a technique that I find myself using increasingly often. So, to teac...
[ "Writing an implementation of a regular expression engine is indeed a quite complex task.\nBut if you are interested in how to do it, even if you can't understand enough of the details to actually implement it, I would recommend that you at least look at this article:\nRegular Expression Matching Can Be Simple And ...
[ 44, 22, 10, 6, 2 ]
[]
[]
[ "parsing", "python", "regex" ]
stackoverflow_0003639574_parsing_python_regex.txt
Q: Scala or Python to Build a Comet server to support a PHP application? I have a currently running PHP application that I want to add real-time feed (Google search latest result feeds), I have an implementation in PHP that does the following: An AJAX request to the server. The PHP responds. After 15000ms (15 second...
Scala or Python to Build a Comet server to support a PHP application?
I have a currently running PHP application that I want to add real-time feed (Google search latest result feeds), I have an implementation in PHP that does the following: An AJAX request to the server. The PHP responds. After 15000ms (15 seconds) using setTimeout(), we repeat the steps. I knew this have very much ove...
[ "Why not node.js? It has a proven reputation of the solution that perfectly handles COMET. Everyone knows Plurk success story - one of the most popular social networking sites in Asia that has 500+mln subscribers, with up to 200k of them working in a parallel (using COMET long-polling connections). node.js memory u...
[ 4, 2 ]
[]
[]
[ "comet", "javascript", "node.js", "python", "scala" ]
stackoverflow_0003770974_comet_javascript_node.js_python_scala.txt
Q: Fourier space filtering I have a real vector time series x of length T and a filter h of length t << T. h is a filter in fourier space, real and symmetric. It is approximately 1/f. I would like to filter x with h to get y. Suppose t == T and FFT's of length T could fit into memory (neither of which are true). To g...
Fourier space filtering
I have a real vector time series x of length T and a filter h of length t << T. h is a filter in fourier space, real and symmetric. It is approximately 1/f. I would like to filter x with h to get y. Suppose t == T and FFT's of length T could fit into memory (neither of which are true). To get my filtered x in python, I...
[ "You're on the right track. The technique is called overlap-save processing. Is t short enough that FFTs of that length fit in memory? If so, you can pick your block size B such that B > 2*min(length(x),length(h)) and makes for a fast transform. Then when you process, you drop the first half of y_b, rather than...
[ 6 ]
[]
[]
[ "fft", "numpy", "python", "scipy", "signal_processing" ]
stackoverflow_0003775912_fft_numpy_python_scipy_signal_processing.txt
Q: Python: How use constants for multiple clasess? I want use a constant in Python for 2 classes. Which is the better way? Thanks in advance! MY_COLOR = "#000001" # <-------- Are correct here? BLACK = "#000000" # <-------- Are correct here? class One: MY_FONT = "monospace" def __init__(self): if...
Python: How use constants for multiple clasess?
I want use a constant in Python for 2 classes. Which is the better way? Thanks in advance! MY_COLOR = "#000001" # <-------- Are correct here? BLACK = "#000000" # <-------- Are correct here? class One: MY_FONT = "monospace" def __init__(self): if MY_COLOR == BLACK: print("It's black") ...
[ "The location of the \"constant\" looks fine to me. As @pyfunc commented you might want to declare other color/font values as \"constant\"s as well. \nIf you are expecting a lot of custom colors and/or fonts you might want to think of a separate module or a properties/configuration file. \n[pedantic] There is no \"...
[ 1, 0 ]
[]
[]
[ "class", "constants", "python" ]
stackoverflow_0003776295_class_constants_python.txt
Q: python compare subsection of 2 strings and see if they match I have 2 strings e.g. str1 = 'section1.1: this is a heading for section 1' and str2 = 'section1.1: this is a heading for section 1.1' I want to compare the text which comes after 'section1.1:' and return whether it is the same or not. In the exampl...
python compare subsection of 2 strings and see if they match
I have 2 strings e.g. str1 = 'section1.1: this is a heading for section 1' and str2 = 'section1.1: this is a heading for section 1.1' I want to compare the text which comes after 'section1.1:' and return whether it is the same or not. In the example it would return false as the first says section 1 and the second...
[ "Use the split method of the strings to split on only the first ::\n>>> str1 = 'section1.1: this is a heading for section 1'\n>>> str2 = 'section1.1: this is a heading for section 1.1'\n>>> str1.split(':', 1)[1]\n' this is a heading for section 1'\n>>> str2.split(':', 1)[1]\n' this is a heading for section 1.1'...
[ 2, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003770024_python.txt
Q: Is this a memory leak? I'm using gc module to debug a leak. It's a gui program and I've hooked this function to a button. I've set set debug more to gc.SAVE_ALL > gc.collect() > > print gc.garbage and this is the output [(<type '_ctypes.Array'>,), {'__module__': 'ctypes._endian', '__dict__': <attribute '__dict_...
Is this a memory leak?
I'm using gc module to debug a leak. It's a gui program and I've hooked this function to a button. I've set set debug more to gc.SAVE_ALL > gc.collect() > > print gc.garbage and this is the output [(<type '_ctypes.Array'>,), {'__module__': 'ctypes._endian', '__dict__': <attribute '__dict__' of 'c_int_Array_3' object...
[ "From the docs:\n\ngc.garbage\nA list of objects which the collector found to be unreachable but could not be freed (uncollectable objects).\n\nSo it looks like some kind of leak to me. Now the docs go on to explain the conditions under which this could occur:\n\nObjects that have del() methods and are part of a r...
[ 1, 0 ]
[]
[]
[ "garbage_collection", "memory_leaks", "python" ]
stackoverflow_0003776291_garbage_collection_memory_leaks_python.txt
Q: Can Django use "external" python scripts linked to other libraries (NumPy, RPy2...) I am new to the world of IT business (serious) development but I have in mind a business idea and still trying to vizualize how the overall infrastructure should work. I have done some few research for a good technology to deliver ...
Can Django use "external" python scripts linked to other libraries (NumPy, RPy2...)
I am new to the world of IT business (serious) development but I have in mind a business idea and still trying to vizualize how the overall infrastructure should work. I have done some few research for a good technology to deliver the solution. I am very inclined to use Python, MySql, Django (Apache) on the server side...
[ "Django is a Python program. And like any other Python program it will be able to access other Python scripts/modules. The question then, is how to execute the script. If your script explicitly defines a main (or another starting point) function then you can merely import it as you would a module and call the main....
[ 5, 1 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0003776515_django_mysql_python.txt
Q: Debug C++ code in visual studio from python code running in eclipse Does any one know how we can do this? I have python code in eclipse and whenever it calls c++ functions, i want the break point to go to the visual studio c++ project. A: You can use a __debugbreak in visual studio so that every time the code is...
Debug C++ code in visual studio from python code running in eclipse
Does any one know how we can do this? I have python code in eclipse and whenever it calls c++ functions, i want the break point to go to the visual studio c++ project.
[ "You can use a __debugbreak in visual studio so that every time the code is invoked it triggers the debugger (you may want to search the function in MSDN).\nInsert the instruction in the C++ function (or class method) you want to debug, e.g.\nvoid foo()\n{\n __debugbreak();\n [...]\n}\n\nat this point compile the...
[ 4, 2 ]
[]
[]
[ "c++", "eclipse", "python", "visual_studio" ]
stackoverflow_0003351110_c++_eclipse_python_visual_studio.txt
Q: Shortest way to break-up long string (add whitespace) after 60 chars? I'm processing a bunch of strings and displaying them on a web page. Unfortunately if a string contains a word that is longer than 60 chars it makes my design implode. Therefore i'm looking for the easiest, most efficient way to add a whitespace...
Shortest way to break-up long string (add whitespace) after 60 chars?
I'm processing a bunch of strings and displaying them on a web page. Unfortunately if a string contains a word that is longer than 60 chars it makes my design implode. Therefore i'm looking for the easiest, most efficient way to add a whitespace after every 60 chars without whitespaces in a string in python. I only ca...
[ "\n>>> import textwrap\n>>> help(textwrap.wrap)\nwrap(text, width=70, **kwargs)\n Wrap a single paragraph of text, returning a list of wrapped lines.\n\n Reformat the single paragraph in 'text' so it fits in lines of no\n more than 'width' columns, and return a list of wrapped lines. By\n default, tabs...
[ 5, 0, 0 ]
[]
[]
[ "python", "string", "whitespace" ]
stackoverflow_0003776627_python_string_whitespace.txt
Q: free implementation of counting user sessions from a web server log? Web server log analyzers (e.g. Urchin) often display a number of "sessions". A session is defined as a series of page visits / clicks made by an individual within a limited, continuous time segment. The attempt is made to identify these segments ...
free implementation of counting user sessions from a web server log?
Web server log analyzers (e.g. Urchin) often display a number of "sessions". A session is defined as a series of page visits / clicks made by an individual within a limited, continuous time segment. The attempt is made to identify these segments using IP addresses, and often supplementary info like user agent and OS, a...
[ "OK, in the absence of any other answer, here's my Python implementation. I'm not a Python expert. Suggestions for improvement are welcome.\n#!/usr/bin/env python\n\n\"\"\"Reconstruct sessions: Take a space-delimited web server access log\nincluding IP addresses, timestamps, and User Agent,\nand output a list of th...
[ 2 ]
[]
[]
[ "python", "session", "web_analytics", "web_analytics_tools" ]
stackoverflow_0003773840_python_session_web_analytics_web_analytics_tools.txt
Q: Writing a module for both Python 2.x and 3.x I've written a pure-Python module for Python 3.0/3.1 which I'd also like to make it compatible with 2.x (probably just 2.6/2.7) in order to make it available to the widest possible audience. The module is concerned with reading and writing a set of related file formats,...
Writing a module for both Python 2.x and 3.x
I've written a pure-Python module for Python 3.0/3.1 which I'd also like to make it compatible with 2.x (probably just 2.6/2.7) in order to make it available to the widest possible audience. The module is concerned with reading and writing a set of related file formats, so the differences between 2.x and 3.x versions w...
[ "Write your code entirely against 2.x, targeting the most recent version in the 2.x series. In this case, it's probably going to remain 2.7. Run it through 2to3, and if it doesn't pass all of its unit tests, fix the 2.x version until the generated 3.x version works.\nEventually, when you want to drop 2.x support, y...
[ 11 ]
[]
[]
[ "python", "python_2.x", "python_3.x" ]
stackoverflow_0003776665_python_python_2.x_python_3.x.txt
Q: Right alignment for table cell in pyqt I have QStandardItemModel and QTableView. I want to have the number align to the right. How can i specify this in pyqt? Now i have it like this (see ID) http://simple-database-explorer.googlecode.com/files/Main2.jpg Working example: self.model.setData(self.model.index(i, j, Q...
Right alignment for table cell in pyqt
I have QStandardItemModel and QTableView. I want to have the number align to the right. How can i specify this in pyqt? Now i have it like this (see ID) http://simple-database-explorer.googlecode.com/files/Main2.jpg Working example: self.model.setData(self.model.index(i, j, QtCore.QModelIndex()), value, role=0) if isNu...
[ "Are you using QStandardItems as well? Then you can use setTextAlignment.\nUpdate\nUsing setData:\nmodel.setData(index, QtCore.QVariant(QtCore.Qt.AlignRight),\n QtCore.Qt.TextAlignmentRole)\n\n" ]
[ 3 ]
[]
[]
[ "datatable", "pyqt", "python", "qt" ]
stackoverflow_0003776533_datatable_pyqt_python_qt.txt
Q: Python xlrd data extraction I am using python xlrd http://scienceoss.com/read-excel-files-from-python/ to read data from an excel sheet My question is if i read a row with first cell as "Employee name" in the excel sheet And there is another row named whose first cell is "Employee name" How can we read the last co...
Python xlrd data extraction
I am using python xlrd http://scienceoss.com/read-excel-files-from-python/ to read data from an excel sheet My question is if i read a row with first cell as "Employee name" in the excel sheet And there is another row named whose first cell is "Employee name" How can we read the last column starting with the last row w...
[ "I am using python xlrd http://scienceoss.com/read-excel-files-from-python/ to read data from an excel sheet\nYou need to think about what you are doing, instead of grabbing some blog code and leaving in totally irrelevant stuff like wb.sheet_names() and omitting parts very relevant to your requirement like first_c...
[ 5, 0 ]
[]
[]
[ "python", "xlrd" ]
stackoverflow_0003775695_python_xlrd.txt
Q: Django and FeinCMS: A way to use the Media Library in other normal models? I'm using Django and FeinCMS on a project. I'm currently using FeinCMS for all the pages on the site. But I also have another separate model that handles very simple stock for the site too. This stock model has the usual fields (name, descr...
Django and FeinCMS: A way to use the Media Library in other normal models?
I'm using Django and FeinCMS on a project. I'm currently using FeinCMS for all the pages on the site. But I also have another separate model that handles very simple stock for the site too. This stock model has the usual fields (name, description, etc) but I also want it to have photos. Because FeinCMS has a media libr...
[ "Sure -- there's nothing stopping you from adding a ForeignKey or a ManyToManyField to the MediaFile model to one of your own models. Note that you'll have a hard time limiting the media files to only images. Maybe limit_choices_to will help though.\n" ]
[ 1 ]
[]
[]
[ "content_management_system", "django", "django_admin", "feincms", "python" ]
stackoverflow_0003542723_content_management_system_django_django_admin_feincms_python.txt
Q: Best way to create Singleton Table in Django/MySQL I want a table which can only have one record. My current solution is: class HitchingPost(models.Model): SINGLETON_CHOICES = (('S', 'Singleton'),) singleton = models.CharField(max_length=1, choices=SINGLETON_CHOICES, unique=True, null=False, default='S');...
Best way to create Singleton Table in Django/MySQL
I want a table which can only have one record. My current solution is: class HitchingPost(models.Model): SINGLETON_CHOICES = (('S', 'Singleton'),) singleton = models.CharField(max_length=1, choices=SINGLETON_CHOICES, unique=True, null=False, default='S'); value = models.IntegerField() def __unicode__(...
[ "\nThis is a bit ugly, and doesn't enforce the constraint at the MySQL level.\n\nIf you are worried about enforcement you ought to look at Django's model validation methods. You can write a custom validate_unique that will raise a ValidationError if HitchingPost.objects.count() != 0.\nclass HitchingPost(models.Mode...
[ 2 ]
[]
[]
[ "django", "django_models", "mysql", "python" ]
stackoverflow_0003777602_django_django_models_mysql_python.txt
Q: Lightweight framework for forms w Ajax in Python I'm new to Python and would like to know of some good framework / code library out there to help me out with building forms w/ ajax (and fallback to no-js) submits. Doing it from scratch is possible ofcourse, but since this is such a common task I figured there must...
Lightweight framework for forms w Ajax in Python
I'm new to Python and would like to know of some good framework / code library out there to help me out with building forms w/ ajax (and fallback to no-js) submits. Doing it from scratch is possible ofcourse, but since this is such a common task I figured there must be some great stuff out there. Django could be the wa...
[ "Are you looking for built-in AJAX support like Ruby on Rails? Or are you looking for a web framework that will work well with AJAX? \nIf you are looking for the latter, then Flask is a \"micro framework\" that is considerably smaller than Django. There are others such as web.py (again, very compact), Pylons and Tu...
[ 1, 1, 1 ]
[]
[]
[ "ajax", "forms", "python" ]
stackoverflow_0003777418_ajax_forms_python.txt
Q: how to get the value of the 'class' attribute in a link? I wrote the sentence as follows: allLinkValues = ie.getLinksValue('class') but the return values are all None, don't know why... A: should be 'className' in IE...
how to get the value of the 'class' attribute in a link?
I wrote the sentence as follows: allLinkValues = ie.getLinksValue('class') but the return values are all None, don't know why...
[ "should be 'className' in IE...\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003752154_python.txt
Q: Possible to use unittest-like fixtures in py.test? I really like py.test, but I am having lots of difficulty understanding how funcargs work. Is it possible to use a command line argument or an extension to enable the use of something that performs a similar role to unittest.TestCase.setUp and unittest.TestCase.t...
Possible to use unittest-like fixtures in py.test?
I really like py.test, but I am having lots of difficulty understanding how funcargs work. Is it possible to use a command line argument or an extension to enable the use of something that performs a similar role to unittest.TestCase.setUp and unittest.TestCase.tearDown?
[ "py.test supports \"normal\" xunit method-based fixtures by default, see:\nhttp://codespeak.net/py/dist/test/xunit_setup.html\nAlternatively you can subclass from unittest.TestCase and use .setUp/tearDown but the latter may be a bit limited.\n" ]
[ 1 ]
[]
[]
[ "pytest", "python", "unit_testing" ]
stackoverflow_0003731768_pytest_python_unit_testing.txt
Q: i want a to resize an image but without distortion I have an image having dimension 1000*500 I want to make it of 400*300 But My image should not looked distorted. http://www.daniweb.com/forums/thread295652.html - i used this as a reference. But My image get distorted. A: Your target image size has a different...
i want a to resize an image but without distortion
I have an image having dimension 1000*500 I want to make it of 400*300 But My image should not looked distorted. http://www.daniweb.com/forums/thread295652.html - i used this as a reference. But My image get distorted.
[ "Your target image size has a different aspect ratio to that of the original. The original is 2:1 but the target is 4:3.\nYou can resize preserving the aspect ratio, but depending on which dimension you choose you'll either get an image that's 400 x 200 or 600 x 300.\nIf you need the image to be 400 x 300 then you'...
[ 5 ]
[]
[]
[ "image_processing", "python" ]
stackoverflow_0003778043_image_processing_python.txt
Q: Is there a app or python package for managing background python script add,execute,stop? I want an app or python package that can 1.Dynamically add python script to the background 2.Execute a specified time 3.Check is this python script is running, 4.Also i can kill the current execute script. Is already has such...
Is there a app or python package for managing background python script add,execute,stop?
I want an app or python package that can 1.Dynamically add python script to the background 2.Execute a specified time 3.Check is this python script is running, 4.Also i can kill the current execute script. Is already has such package,so i needn't care about cron, at, check processing is running etc. Cron only can prov...
[ "Take a look at http://supervisord.org/.\n" ]
[ 0 ]
[]
[]
[ "at_job", "background", "process", "python" ]
stackoverflow_0003778106_at_job_background_process_python.txt
Q: PySide Error - QPaintDevice: Cannot destroy paint device that is being painted I'm baffled by this one. I tried moving the QPainter to it's own def as some have suggested, but it gives the exact same error. Here's the def I created. def PaintButtons(self): solid = QtGui.QPixmap(200, 32) paint = QtGui.QPain...
PySide Error - QPaintDevice: Cannot destroy paint device that is being painted
I'm baffled by this one. I tried moving the QPainter to it's own def as some have suggested, but it gives the exact same error. Here's the def I created. def PaintButtons(self): solid = QtGui.QPixmap(200, 32) paint = QtGui.QPainter() paint.begin(solid) paint.setPen(QtGui.Qcolor(255,255,255)) paint.s...
[ "It was just a typo. You're using Qcolor (the first occurrence).Changing that to QColor will do the trick. :)\n" ]
[ 2 ]
[]
[]
[ "pyside", "python" ]
stackoverflow_0003768440_pyside_python.txt
Q: how to displace an image in python? I have an image size 400*200. I have a frame size 400* 300. I want to put the image in the center of frame. That is my image cordinate (0,0) starts with the frame cordinates (0,50). A: frame= Image.new(image.mode, (400, 300)) frame.paste(image, (0, 50)) (frame.paste(image, (...
how to displace an image in python?
I have an image size 400*200. I have a frame size 400* 300. I want to put the image in the center of frame. That is my image cordinate (0,0) starts with the frame cordinates (0,50).
[ "frame= Image.new(image.mode, (400, 300))\nframe.paste(image, (0, 50))\n\n(frame.paste(image, (0, 50), image) if the image to be framed has a transparency mask you want to keep. And pass a third parameter to Image.new to set the background colour of the frame if the default isn't what you want.)\n" ]
[ 2 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0003778300_python_python_imaging_library.txt
Q: Get original row number from .get_model() and .get_path() after TreeView was resorted So I have this TreeView/TreeStore, which I fill with data from a list. My application uses only said list as reference data. The TreeStore is just constructed for display. And the TreeView can be resorted by tipping the column he...
Get original row number from .get_model() and .get_path() after TreeView was resorted
So I have this TreeView/TreeStore, which I fill with data from a list. My application uses only said list as reference data. The TreeStore is just constructed for display. And the TreeView can be resorted by tipping the column headers. Because .set_sort_column_id() was used for initialization of each column. Problem is...
[ "Congratulations, you have entered just about the most nightmarish thing that PyGTK has to offer. I don't expect any bounty for this, but my solution revolves around wrapping your Model in a Sortable model and also in a Filterable one. This way, you can get the various paths and iters for the 3 nested models depend...
[ 1 ]
[]
[]
[ "gtk", "gtktreeview", "pygtk", "python" ]
stackoverflow_0003743756_gtk_gtktreeview_pygtk_python.txt
Q: Find all tags with a specific attribute value How can I iterate over all tags which have a specific attribute with a specific value? For instance, let's say we need the data1, data2 etc... only. <html> <body> <invalid html here/> <dont care> ... </dont care> <invalid html here too/> ...
Find all tags with a specific attribute value
How can I iterate over all tags which have a specific attribute with a specific value? For instance, let's say we need the data1, data2 etc... only. <html> <body> <invalid html here/> <dont care> ... </dont care> <invalid html here too/> <interesting attrib1="naah, it is not this"> ....
[ "Here's one way, using lxml and the XPath 'descendant::*[@attrib1=\"yes, this is what we want\"]'. The XPath tells lxml to look at all the descendants of the current node and return those with an attrib1 attribute equal to \"yes, this is what we want\".\nimport lxml.html as lh \nimport cStringIO\n\ncontent='''\n<ht...
[ 3 ]
[]
[]
[ "html_parsing", "lxml", "python" ]
stackoverflow_0003778512_html_parsing_lxml_python.txt
Q: why can't I fetch sql statements in python? I have a very large table (374870 rows) and when I run the following code timestamps just ends up being a long int with the value 374870.... I want to be able to grab all the timestamps in the table... but all I get is a long int :S import MySQLdb db = MySQLdb.connect( ...
why can't I fetch sql statements in python?
I have a very large table (374870 rows) and when I run the following code timestamps just ends up being a long int with the value 374870.... I want to be able to grab all the timestamps in the table... but all I get is a long int :S import MySQLdb db = MySQLdb.connect( host = "Some Host", ...
[ "Try this:\ncur = db.cursor()\ncur.execute(sql)\ntimestamps = []\nfor rec in cur:\n timestamps.append(rec[0])\n\n", "You need to call fetchmany() on the cursor to fetch more than one row, or call fetchone() in a loop until it returns None.\n", "Consider the possibility that the not-very-long integer that you...
[ 2, 1, 0 ]
[]
[]
[ "mysql", "python", "sql" ]
stackoverflow_0003778935_mysql_python_sql.txt
Q: Create Python array.array Object from cStringIO Object I want to create an array.array object from a cStringIO object: import cStringIO, array s = """ <several lines of text> """ f = cStringIO.StringIO(s) a = array.array('c') a.fromfile(f, len(s)) But I get the following exception: ...
Create Python array.array Object from cStringIO Object
I want to create an array.array object from a cStringIO object: import cStringIO, array s = """ <several lines of text> """ f = cStringIO.StringIO(s) a = array.array('c') a.fromfile(f, len(s)) But I get the following exception: Traceback (most recent call last): File "./myfile.py", l...
[ "Why not use a.fromstring()? Since the StringIO buffer is entirely in memory, there is no benefit to trying to use a file api to read the bits from one memory location to another.\na = array.array('c')\na.fromstring(s)\n\nIf you are using StringIO for another reason (as a memory buffer, or as a file earlier on), th...
[ 4 ]
[]
[]
[ "python", "stringio" ]
stackoverflow_0003779206_python_stringio.txt
Q: Pre-interpret Django site at deployment time I deploy Django apps using a fabric script that checks out a copy of my project and when everything is in place the source is symlinked and the web server is reloaded (guessing this is a typical approach). My concern is that the first time the site gets hit after deploy...
Pre-interpret Django site at deployment time
I deploy Django apps using a fabric script that checks out a copy of my project and when everything is in place the source is symlinked and the web server is reloaded (guessing this is a typical approach). My concern is that the first time the site gets hit after deployment all the python scripts need to be re-interpre...
[ "python -m compileall /path/to/django/site\n\nWill precompile any .py files under the directory recursively.\nHow are you running django? If you're using WSGI the interpreter or interpreters are already running and would have already compiled a lot of your django site. What is being dynamically loaded?\n" ]
[ 1 ]
[]
[]
[ "django", "fabric", "python" ]
stackoverflow_0003779365_django_fabric_python.txt
Q: Loop thru a directory and search in all pre-filtered XML files for a word I would like to loop through a given directory and seach in all pre-filtered files for a search word. I prepared this code, but it is not looping thru all files, only the last file which was found is analyzed. Ideally all files should be ana...
Loop thru a directory and search in all pre-filtered XML files for a word
I would like to loop through a given directory and seach in all pre-filtered files for a search word. I prepared this code, but it is not looping thru all files, only the last file which was found is analyzed. Ideally all files should be analyzed and the output should be saved in a textfile. Could someone help? import ...
[ "Indent the 2nd for-loop one more level to make it loop for every file found.\nfor filename in glob.glob(\"C:\\\\test*.xml\"):\n print filename\n\n#-->\n for line in open(filename):\n if \"SEARCHWORD\" in line:\n print line\n\nBTW, since you are just iterating on the globbed result instead o...
[ 2, 0 ]
[]
[]
[ "indentation", "python", "syntax" ]
stackoverflow_0003779632_indentation_python_syntax.txt
Q: Best dynamic languages for OpenGL/general graphics Which are the most mature and well supported solutions for writing graphical programs? I have been using C++ with OpenGL/GLUT, but would like to try a more flexible and expressive approach. Ruby and Processing? Python and OGRE? What things have worked well for you...
Best dynamic languages for OpenGL/general graphics
Which are the most mature and well supported solutions for writing graphical programs? I have been using C++ with OpenGL/GLUT, but would like to try a more flexible and expressive approach. Ruby and Processing? Python and OGRE? What things have worked well for you?
[ "If you are just interested in experimenting, I'd suggest picking a 3D framework with bindings for a dynamic language you are already familiar with.\nI started doing experiments with Ruby/OpenGL a year or three ago and that was easy enough to play around with.\nIf you seriously want to build a project (for whatever...
[ 8, 5, 4, 2, 2 ]
[]
[]
[ "graphics", "processing", "python", "ruby", "scheme" ]
stackoverflow_0001904454_graphics_processing_python_ruby_scheme.txt
Q: Determining a file's path name from different working directories in python I have a python module that is shared among several of my projects (the projects each have a different working directory). One of the functions in this shared module, executes a script using os.spawn. The problem is, I'm not sure what pa...
Determining a file's path name from different working directories in python
I have a python module that is shared among several of my projects (the projects each have a different working directory). One of the functions in this shared module, executes a script using os.spawn. The problem is, I'm not sure what pathname to give to os.spawn since I don't know what the current working directory ...
[ "So I just learned about the __file__ variable, which will provide a solution to my problem. I can use file to get a pathname which will be constant among all projects, and use that to reference the script I need to call, since the script will always be in the same location relative to __file__. However, I'm open t...
[ 1, 0, 0, 0 ]
[]
[]
[ "file", "python", "relative_path" ]
stackoverflow_0003780094_file_python_relative_path.txt
Q: How to fix ImportError in matplotlib I compiled matplotlib on a mac running snow leopard only to find that when I import matplotlib.pyplot I get the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site...
How to fix ImportError in matplotlib
I compiled matplotlib on a mac running snow leopard only to find that when I import matplotlib.pyplot I get the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/pyplot.py", line 6, i...
[ "Building matplotlib on OS X is notoriously fraught with problems linking to mismatched versions of libraries that can be in the system directories, /usr/local, /opt/local, what have you. That's why there is a README.osx file in the source distribution advising you to use the make.osx file provided in the distribut...
[ 0 ]
[]
[]
[ "import", "importerror", "matplotlib", "python" ]
stackoverflow_0003120265_import_importerror_matplotlib_python.txt
Q: Regex in python to get javadoc-style comments in CSS I'm writing a python script to loop through a directory of CSS files and save the contents of any which contain a specifically-formatted javadoc style comment. The comment/CSS looks like this: /**thirdpartycss * @description Used for fixing stuff */ .class_one...
Regex in python to get javadoc-style comments in CSS
I'm writing a python script to loop through a directory of CSS files and save the contents of any which contain a specifically-formatted javadoc style comment. The comment/CSS looks like this: /**thirdpartycss * @description Used for fixing stuff */ .class_one { margin: 10px; } #id_two { padding: 2px; } The ...
[ "{(.*)} is a greedy match -- it will match from the first { to the last }, thus gobble up any {/} pairs that might be inside those. You want non-greedy matching, that is\n{(.*?)}\n\nthe difference is the question mark after the asterisk, making it non-greedy.\nThis still won't work if you need to properly match \"...
[ 2, 1 ]
[]
[]
[ "css", "javadoc", "python", "regex" ]
stackoverflow_0003780722_css_javadoc_python_regex.txt
Q: Need help with wxPython, NotebookCtrl in particular I am trying to write a non-webbased client for a chat service on a web site, it connects to it fine via socket and can communicate with it and everything. I am writing a GUI for it (I tried writing it in tkinter but I hit some walls I really wantd to get passed, ...
Need help with wxPython, NotebookCtrl in particular
I am trying to write a non-webbased client for a chat service on a web site, it connects to it fine via socket and can communicate with it and everything. I am writing a GUI for it (I tried writing it in tkinter but I hit some walls I really wantd to get passed, so I switched to wxPython) What I'm having a problem with...
[ "Here is your problem:\nlambda: self.App.AddChatroom('#TestChatroom{0}'.format(self.roomcount), self) )\n\nFixed by using wx.CallAfter (tested on win xp sp3):\nlambda: wx.CallAfter(self.App.AddChatroom, '#TestChatroom{0}'.format(self.roomcount), self)\n\nYou were probably tying up the GUI by calling wx objects from...
[ 1, 0, 0 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0003765852_python_user_interface_wxpython.txt